1059: [ZJOI2007]矩阵游戏
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 4986 Solved: 2388
[Submit][Status][Discuss]
Description
小Q是一个非常聪明的孩子,除了国际象棋,他还很喜欢玩一个电脑益智游戏——矩阵游戏。矩阵游戏在一个N
*N黑白方阵进行(如同国际象棋一般,只是颜色是随意的)。每次可以对该矩阵进行两种操作:行交换操作:选择
矩阵的任意两行,交换这两行(即交换对应格子的颜色)列交换操作:选择矩阵的任意行列,交换这两列(即交换
对应格子的颜色)游戏的目标,即通过若干次操作,使得方阵的主对角线(左上角到右下角的连线)上的格子均为黑
色。对于某些关卡,小Q百思不得其解,以致他开始怀疑这些关卡是不是根本就是无解的!!于是小Q决定写一个程
序来判断这些关卡是否有解。
Input
第一行包含一个整数T,表示数据的组数。接下来包含T组数据,每组数据第一行为一个整数N,表示方阵的大
小;接下来N行为一个N*N的01矩阵(0表示白色,1表示黑色)。
Output
输出文件应包含T行。对于每一组数据,如果该关卡有解,输出一行Yes;否则输出一行No。
Sample Input
2
2
0 0
0 1
3
0 0 1
0 1 0
1 0 0
2
0 0
0 1
3
0 0 1
0 1 0
1 0 0
Sample Output
No
Yes
【数据规模】
对于100%的数据,N ≤ 200
Yes
【数据规模】
对于100%的数据,N ≤ 200
思路{首先手玩发现一个元素所在的行,列的元素内容是不变的.那么问题转化为是否存在n个本质不同的位置.直接x行向y列连边做最大匹配就可以了.}
#include<bits/stdc++.h>
#define LL long long
#define RG register
#define il inline
#define N 100010
using namespace std;
struct ed{int nxt,to,c;}e[N];
int head[N],tot,n,dep[N];
void link(int u,int v,int c){e[tot].nxt=head[u];e[tot].to=v;e[tot].c=c;head[u]=tot++;}
void LINK(int u,int v,int c){link(u,v,c),link(v,u,0);}
bool BFS(int s,int t){
memset(dep,0,sizeof(dep));
dep[s]=1;queue<int>que;while(!que.empty())que.pop();
que.push(s);
while(!que.empty()){
int u=que.front();que.pop();
for(int i=head[u];i!=-1;i=e[i].nxt)if(!dep[e[i].to]&&e[i].c){
int v=e[i].to;
dep[v]=dep[u]+1;
if(v==t)return true;
que.push(v);
}
}return false;
}
int dinic(int s,int t,int T){
if(s==t)return T;int tag(0);
for(int i=head[s];i!=-1;i=e[i].nxt)if(dep[s]+1==dep[e[i].to]&&e[i].c){
int d=dinic(e[i].to,t,min(T-tag,e[i].c));
e[i].c-=d,e[i^1].c+=d,tag+=d;
if(tag==T)break;
}if(!tag)dep[s]=0;return tag;
}
int maxflow(int s,int t){
int flow(0);
while(BFS(s,t))flow+=dinic(s,t,(1<<30));
return flow;
}
void clear(){tot=0;memset(head,-1,sizeof(head));}
int main(){
int T;scanf("%d",&T);
while(T--){
clear();
scanf("%d",&n);int kk;
for(int i=1;i<=n;++i)LINK(0,i,1),LINK(i+n,2*n+1,1);
for(int i=1;i<=n;++i)
for(int j=n+1;j<=2*n;++j){
scanf("%d",&kk);
if(kk)LINK(i,j,1);
}
if(maxflow(0,2*n+1)==n)cout<<"Yes
";
else cout<<"No
";
}
}