Given an N*N matrix with each entry equal to 0 or 1. You can swap any two rows or any two columns. Can you find a way to make all the diagonal entries equal to 1?
If it is impossible to make all the diagonal entries equal to 1, output only one one containing “-1”.
2 0 1 1 0 2 1 0 1 0
1 R 1 2 -1
通过对换矩阵的两行或两列使得矩阵的主对角线上的元素均为1
思路
二分图的最大匹配
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node{
int a,b;
}op[1010];
const int N = 110;
int match[N],used[N];
int e[N][N];
int n;
int Find(int x){
for(int i=1;i<=n;i++){
if(e[x][i]&&!used[i]){
used[i]=1;
if(!match[i]||Find(match[i])){
match[i]=x;
return 1;
}
}
}
return 0;
}
int hungary(){
memset(match,0,sizeof(match));
int ans=0;
for(int i=1;i<=n;i++){
memset(used,0,sizeof(used));
if(Find(i)) ans++;
}
return ans;
}
int main(){
while(scanf("%d",&n)!=EOF){
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&e[i][j]);
int ans=hungary();
if(ans<n){
printf("-1\n");
continue;
}
int cnt=0;
for(int i=1;i<=n;i++){
int j;
for(j=1;j<=n;j++){
if(match[j]==i) break;
}
if(j!=i){
op[cnt].a=i;
op[cnt++].b=j;
swap(match[i],match[j]);
}
}
printf("%d\n",cnt);
for(int i=0;i<cnt;i++)
printf("C %d %d\n",op[i].a,op[i].b);
}
return 0;
}