hdu 2819 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”对应的列号

如果某行或者某列全是0。那怎么换都没办法的。
否则,一定能换出来。

其次要明确:只交换行或者只交换列都是可以换出来的。

#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#define INF 99999999;
using namespace std;

int n;
int mp[110][110];
int match[110];
int vis[110];

int dfs(int u)
{
	for (int v = 1; v <= n; v++)
	{
		if (mp[u][v] && !vis[v])
		{
			vis[v] = 1;
			if (match[v] == -1 || dfs(match[v]))
			{
				match[v] = u;
				return 1;
			}
		}
	}
	return 0;
}

int hungarian()
{
	int ans = 0;
	memset(match, -1, sizeof(match));

	for (int i = 1; i <= n; i++)
	{
		memset(vis, 0, sizeof(vis));
		ans += dfs(i);
	}
	return ans;
}

int main()
{
	//freopen("C://input.txt", "r", stdin);
	while (scanf("%d", &n)!=EOF)
	{
		memset(mp, 0, sizeof(mp));

		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
				scanf("%d", &mp[i][j]);

		if (hungarian() != n)
			printf("-1\n");
		else
		{
			int num = 0;
			int a[110], b[110];
			for (int i = 1; i <= n; i++)
			{
				if (i != match[i])
				{
					for (int j = 1; j <= n; j++)
					{
						if (i == match[j])
						{
							a[num] = i;
							b[num] = j;
							num++;
							swap(match[i], match[j]);
							break;
						}
					}
				}
			}

			printf("%d\n", num);
			for (int i = 0; i < num; i++)
			{
				printf("C %d %d\n", a[i], b[i]);
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Evildoer_llc/article/details/83021208