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
题意
给定一个仅含有0与1的n阶方阵,询问是否可以通过行列变换将其对角线上的所有元素变为1,若能则输出变换方法。
思路
行列进行匹配,若结果小于n则说明现存元素无法使得对角线全为1,否则作行列变换。需要清楚的是,仅通过行或列变换即可以满足题目要求。
代码
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1e5+5;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
bool ch[maxn];
int t,n,m,p,k,ans,cnt,ed[maxn],maze[105][105];
struct node
{
int c1,c2;
}a[maxn];
bool find(int x)
{
for(int i=1;i<=n;i++)
{
if(!ch[i]&&maze[x][i])
{
ch[i]=1;
if(!ed[i]||find(ed[i]))
{
ed[i]=x;
return true;
}
}
}
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
while(scanf("%d",&n)!=EOF)
{
ans=0;
cnt=0;
memset(ed,0,sizeof ed);
memset(maze,0,sizeof maze);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d",&maze[i][j]);
}
}
for(int i=1;i<=n;i++)
{
memset(ch,0,sizeof ch);
if(find(i))
ans++;
}//二分匹配
if(ans!=n)
printf("-1\n");//无法满足条件
else
{
for(int i=1;i<=n;i++)
{
if(i!=ed[i])//列与其对应的行并不相等(对角线元素横纵坐标相等)
{
for(int j=1;j<=n;j++)
{
if(i==ed[j])//寻找到对应的行与i相等的列
{
a[++cnt].c1=i;
a[cnt].c2=j;
swap(ed[i],ed[j]);
}//记录列并交换对应行
}
}
}
printf("%d\n",cnt);
for(int i=1;i<=cnt;i++)
printf("C %d %d\n",a[i].c1,a[i].c2);
}
}
return 0;
}