P2055 [ZJOI2009]假期的宿舍
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<map>
#include<iomanip>
#include<cstring>
#define reg register
#define EN std::puts("")
#define LL long long
inline int read(){
register int x=0;register int y=1;
register char c=std::getchar();
while(c<'0'||c>'9'){if(c=='-') y=0;c=std::getchar();}
while(c>='0'&&c<='9'){x=x*10+(c^48);c=std::getchar();}
return y?x:-x;
}
#define N 106
#define M 100006
int n,m,need_bed,tot;
int school[N],go_home[N],bed[N];
struct graph{
int fir[N],nex[M],to[M],tot;
inline void add(int u,int v){
to[++tot]=v;
nex[tot]=fir[u];fir[u]=tot;
}
}G;
int match[N],pre[N];
int que[N],tail,head,check[N];
inline int max_match(){
int ans=0,u,v;
std::memset(check,0,sizeof check);
std::memset(pre,0,sizeof pre);std::memset(match,0,sizeof match);
for(reg int i=1;i<=n;i++)if(!match[i]&&(!school[i]||(school[i]&&!go_home[i]))){
tail=head=0;que[0]=i;
pre[i]=0;
while(tail<=head){
u=que[tail++];
for(reg int j=G.fir[u];j;j=G.nex[j]){
v=G.to[j];
if(check[v]^i){
check[v]=i;
if(match[v]) pre[match[v]]=u,que[++head]=match[v];
else{
int d=u,e=v,t;
while(d){
t=match[d];
match[d]=e;match[e]=d;
d=pre[d];e=t;
}
goto BREAK;
}
}
}
}
BREAK:;
if(match[i]) ans++;
}
// std::printf("ans : %d\n",ans);
return ans==need_bed;
}
int main(){int T=read();while(T--){
tot=n=read();need_bed=0;
for(reg int i=1;i<=n;i++){
school[i]=read();
if(school[i]) bed[i]=++tot;
}
for(reg int i=1;i<=n;i++){
go_home[i]=read();
if(!go_home[i]&&school[i]) G.add(i,bed[i]),G.add(bed[i],i);//j 在校且不回家
}
for(reg int i=1;i<=n;i++) need_bed+=(!school[i]||(school[i]&&!go_home[i]));
for(reg int a,i=1;i<=n;i++)for(reg int j=1;j<=n;j++){
a=read();
if(a&&school[j]) G.add(bed[j],i),G.add(i,bed[j]);//认识 j 并且 j 是在校
}
std::puts(max_match()?"^_^":"T_T");
// for(reg int i=1;i<=tot;i++){
// std::printf("%d : \n ",i);
// for(reg int j=G.fir[i];j;j=G.nex[j]) std::printf("%d ",G.to[j]);
// EN;
// }
// std::printf("beds : %d\n",need_bed);
std::memset(G.fir,0,sizeof G.fir);std::memset(G.nex,0,sizeof G.nex);G.tot=0;
}
return 0;
}