Swap——二分图最大匹配

Given an NN 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的01矩阵,问经过怎样的交换才能使得所有对角线上的值都为1,每次交换只能交换任意的行或列。若无法交换成功则输出-1
解题思路:首先要确定一点,其实可以考虑只交换行或只交换列,比如若只交换列,行其实不管交不交换都是没影响的。把一个图做一次二分匹配,所有的列都匹配到了一个行。若是最大匹配数不能到达n,则说明无论怎么交换都是不能得到对角线全部为1。匹配完成后,再看每行的匹配值,若是x[i] != i,则进行交换
如果要交换列,那么输入矩阵时是e[i][j],
如果要交换行,那么输入矩阵时是e[j][i];
亲测有效

AC代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX=1e2+10;
int book[MAX],e[MAX][MAX],match[MAX],l[MAX*MAX];
int n,k,s;
int dfs(int x)
{
	for(int i=1;i<=n;i++)
	{
		if(!book[i]&&e[x][i])
		{
			book[i]=1;
			if(!match[i]||dfs(match[i]))
			{
				match[i]=x;
				return 1;
			}
		}
	}
	return 0;
}
void solve()
{
	while(~scanf("%d",&n))
	{
		int s=0,k=0;
		memset(e,0,sizeof(e));
		memset(match,0,sizeof(match));
		memset(l,0,sizeof(l));
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++)
				scanf("%d",&e[i][j]);//注意这里用e[j][i]下方输出应为R。
		for(int i=1;i<=n;i++)
		{
			memset(book,0,sizeof(book));
			if(dfs(i))
			s++;
		}
		if(s<n)
		{
			printf("-1\n");
			continue;
		}
		for(int i=1;i<=n;i++)
		{
			if(match[i]!=i)
			{
				for(int j=i+1;j<=n;j++)
				{
					if(match[j]==i)
					{
						l[++k]=i;
						l[++k]=j;
						match[j]=match[i];
						match[i]=i;
						break;
					}
				}
			}
		}
		printf("%d\n",k/2);
		for(int i=1;i<=k;i+=2)
			printf("C %d %d\n",l[i],l[i+1]);//R
	}
}
int main()
{
	solve();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值