Swap

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2819

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

解析:如果能够实现主对角线上都是1,则如果在每行每列只能放一个点的前提下每行每列应该都有一个点,即在二分匹配下,ans>n,才能够实现主对角线上都是一,然后便利 i 行,找到有1的那一列 j ,把 j 这一列和 i 这一列交换下,就可以实现 i 行 i 列这个位置是1,由于题目没有要求找最小的交换次数,所以不需要交换行和交换列相结合,只交换行或是只交换列就可以实现。

具体解释在代码中。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int M=110;
int n;
int g[M][M];
int line[M];
int vis[M];
int p[M][2];
int find(int k)//二分匹配的核心代码
{
    for(int i=1; i<=n; i++)
    {
        if(g[k][i]==1&&vis[i]==0)
        {
            vis[i]=1;
            if(line[i]==0||find(line[i]))
            {
                line[i]=k;
                return 1;
            }
        }
    }
    return 0;
}
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=n; j++)
                scanf("%d",&g[i][j]);
        }
        memset(line,0,sizeof(line));
        int ans=0;
        for(int i=1; i<=n; i++)
        {
            memset(vis,0,sizeof(vis));
            ans+=find(i);
        }
        if(ans<n)
        {
            printf("-1\n");
        }
        else
        {
            int k=0,i,j;
            for(i=1; i<=n; i++)//便利行数
            {
                for(j=1; j<=n; j++)
                {
                    if(i==line[j])//一定会碰到在第i行有1的j列,由于要实现i行i列是1,
                                  //所以交换i列和j列即可
                      break;
                }
                if(i!=j)
                {
                    p[k][0]=i;//存储需要交换的两列
                    p[k][1]=j;
                    k++;
                    int t=line[i];//实质性的交换
                    line[i]=line[j];
                    line[j]=t;
                }
            }
            printf("%d\n",k);
            for(int i=0; i<k; i++)
                printf("C %d %d\n",p[i][0],p[i][1]);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41129854/article/details/81262012