您的位置:首页 > 其它

hdu 2819 Swap(二分匹配+记录路径,好题)

2016-08-24 17:19 381 查看


题目链接


Swap

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 2892    Accepted Submission(s): 1032
Special Judge


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

 

Source

2009 Multi-University Training
Contest 1 - Host by TJU

题解:

这里先说明的一点就是,如果通过交换某些行没有办法的到解的话,那么只交换列 或者 既交换行又交换列 那也没办法得到解。其实个人感觉这个可以用矩阵的秩来解释,所有的对角线都是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<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=100+10;
int g[maxn][maxn],match[maxn];
bool used[maxn];
int n;
vector<pair<int,int> > res;
bool bfs(int u)
{
for(int i=1;i<=n;i++)
{
if(g[u][i]&&!used[i])
{
used[i]=true;
if(match[i]<0||bfs(match[i]))
{
match[i]=u;
return true;
}
}
}
return false;
}

int hungry()
{
int ans=0;
memset(match,-1,sizeof(match));
for(int i=1;i<=n;i++)
{
memset(used,false,sizeof(used));
if(bfs(i)) ans++;
}
return ans;
}

int main()
{
while(~scanf("%d",&n))
{
res.clear();
memset(g,0,sizeof(g));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
scanf("%d",&g[i][j]);
}
if(hungry()<n)
{
puts("-1");
continue;
}
int u,v;
for(u=1;u<=n;u++)  //路径记录
{
for(v=u;v<=n;v++)
{
if(match[v]==u)
break;
}
if(u!=v)
{
res.push_back(make_pair(u,v));
swap(match[u],match[v]);
}
}
printf("%d\n",res.size());
for(int i=0;i<res.size();i++)
printf("C %d %d\n",res[i].first,res[i].second);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: