F。
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2819
题目大意很明确,交换图的某些行或者是某些列(可以都换),使得这个N*N的图对角线上全部都是1.
这里有一点需要说明,就是说题目的交换,其实是将原来图的某一行移到最后图的某一行,而不是指先交换两行,得到一个新图,再交换新图的两行。感觉这里比较坑。
这里先说明的一点就是,如果通过交换某些行没有办法的到解的话,那么只交换列 或者 既交换行又交换列 那也没办法得到解。其实个人感觉这个可以用矩阵的秩来解释,所有的对角线都是1,所以也就是矩阵的秩就是N,所以秩小于N就无解。另外,根据矩阵的性质,任意交换矩阵的两行 或者 两列,矩阵的秩不变,也就保证了如果通过 只交换行 或 只交换列 无法得到解的话,那么其他交换形式也必然无解。
既然说是用二分图的最大匹配,那怎么构建二分图呢,我们构建的二分图,第一部分X表示的是横坐标,第二部分Y表示纵坐标,所以范围都是1~N,然后如果a[i][j]是1,那我们就从X的i向Y的j引一条边,那么这条边的含义就可以解释为可以将Y的第j列(因为Y表示的是列的集合)移到第i列,使得a[i][i]变成1,这样就相当于是第i行第i列就变成了1,也就是说对角线多了一个1。
因此我们求这个二分图的最大匹配(目的是为了让每一列只与X中的某一行匹配),这样来就形成了N条边,那我们只需要将所有匹配的边的右边(列) 和 左边(行)所在的列 交换,这样一来对角线上这一行就成了1.
上面也也正好提示了如果最大匹配是N,那就存在解,否则无解。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<limits.h>
#include<queue>
#include<math.h>
#include<algorithm>
using namespace std;
#define maxn 205
int ans[maxn];
int map[maxn][maxn];
int a[maxn],b[maxn];
int n;
int v[maxn];
int dfs(int x)
{
for(int i=1;i<=n;i++)
{
if(map[x][i] && !ans[i])
{
ans[i]=1;
if(!v[i]||dfs(v[i]))
{
v[i]=x;
return 1;
}
}
}
return 0;
}
int main()
{
int i,j;
while(scanf("%d",&n)!=EOF)
{
int x;
memset(v,0,sizeof(v));
memset(map,0,sizeof(map));
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&x);
if(x)
map[i][j]=1;
}
}
int sum=0;
for(i=1;i<=n;i++)
{
memset(ans,0,sizeof(ans));
if(dfs(i))
sum++;
}
if(sum<n)//无解
{
printf("-1\n");
continue;
}
int tot=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=n && v[j]!=i;j++);
{
if(i!=j)//交换第i列和第j列
{
int t;
a[tot]=i;b[tot]=j;tot++;
t=v[i];v[i]=v[j];v[j]=t;
}
}
}
printf("%d\n",tot);
for(i=0;i<tot;i++)
printf("C %d %d\n",a[i],b[i]);
}
}