Problem Description
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
思路
题目给了一个n∗n的图,问能不能通过交换行和列,使这个图的主对角线变成1(A[i][i]=1),如果不可以输出-1,如果可以输出路径
首先要明确:
只交换行或者只交换列,就一定可以达到题目的要求,可以这么理解:
所有的对角线都是1,所以也就是矩阵的秩就是N,所以秩小于N就无解。另外,根据矩阵的性质,任意交换矩阵的两行 或者
两列,矩阵的秩不变,也就保证了如果通过 只交换行 或 只交换列 无法得到解的话,那么其他交换形式也必然无解
我们假设交换列,建立二分图,左边的节点为每一行的行号,二分图右边的节点为每一行中出现的“1”对应的列号
那么首先要保证问题有解,就必须达到完美匹配,只有当最大匹配的个数为n,才可以保证有解,这个画一个图就知道为什么了
在记录路径的时候,因为我们要达到的状态是
代码
#include <bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
const int N=100+20;
int e[N][N],vis[N],match[N],l[N],r[N],n;
int dfs(int u)
{
for(int i=1; i<=n; i++)
{
if(e[u][i]&&!vis[i])
{
vis[i]=1;
if(!match[i]||dfs(match[i]))
{
match[i]=u;
return 1;
}
}
}
return 0;
}
int query()
{
mem(match,0);
int sum=0;
for(int i=1; i<=n; i++)
{
mem(vis,0);
if(dfs(i))sum++;
}
return sum;
}
int main()
{
while(~scanf("%d",&n))
{
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
scanf("%d",&e[i][j]);
if(query()!=n)puts("-1");
else
{
int num=0;
for(int i=1; i<=n; i++)
if(match[i]!=i)
for(int j=1; j<=n; j++)
if(match[j]==i)
{
l[num]=i;
r[num++]=j;
swap(match[i],match[j]);
break;
}
printf("%d\n",num);
for(int i=0; i<num; i++)
printf("C %d %d\n",l[i],r[i]);
}
}
return 0;
}