Swap(二分匹配)
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?
Input
There are several test cases in the input. The first line of each test case is an integer N (1 <= N <= 100). Then N lines follow, each contains N numbers (0 or 1), separating by space, indicating the N*N matrix.
Output
For each test case, the first line contain the number of swaps M. Then M lines follow, whose format is “R a b” or “C a b”, indicating swapping the row a and row b, or swapping the column a and column b. (1 <= a, b <= N). Any correct answer will be accepted, but M should be more than 1000.
If it is impossible to make all the diagonal entries equal to 1, output only one one containing “-1”.
Sample Input
2
0 1
1 0
2
1 0
1 0
Sample Output
1
R 1 2
-1
题意: 交换任意行和列,使对角线上的元素(i==j)都为1,如果可以输出交换次数和方法,否则输出-1
思路: 刚看到这个题时,我是毫无思路,学长讲了,才知道是二分匹配,有1的行和列匹配,如果匹配数等于行数,那就代表可以通过交换达到对角线上的元素全为1,然后就是判断对角线上的元素是不是1,也就是判断与当前行匹配的列是否相等,不相等就要找到与这个列匹配的行,交换列
AC代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,book[1100],match[1100],a[1100][1100];
int b[1100],c[1100];
int dfs(int x)
{
int i,j;
for(i=1; i<=n; i++)
{
if(!book[i]&&a[x][i])//
{
book[i]=1;
if(!match[i]||dfs(match[i]))
{
match[i]=x;
return 1;
}
}
}
return 0;
}
int main()
{
while(~scanf("%d",&n))
{
int i,j,k;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
memset(book,0,sizeof(book));
memset(match,0,sizeof(match));
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
scanf("%d",&a[i][j]);
int ans=0;
for(i=1; i<=n; i++)
{
memset(book,0,sizeof(book));
if(dfs(i))
ans++;
}
if(ans<n)//小于说明不可能出现对角线元素全为1的情况
{
printf("-1\n");
continue;
}
k=0;
for(i=1; i<=n; i++)
{
if(match[i]!=i)//行列不相等,即当前行与匹配的列不相等,即不在对角线上
{
for(j=1; j<=n; j++)
{
if(match[j]==i)//找到与当前列匹配的行
{
b[k]=i;//记录
c[k]=j;
k++;
swap(match[i],match[j]);//交换列
break;
}
}
}
}
printf("%d\n",k);
for(i=0; i<k; i++)
printf("C %d %d\n",b[i],c[i]);
}
return 0;
}