HDU 2819 — Swap 二分匹配

时间:2021-10-06 12:59:06

Swap

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2174    Accepted Submission(s): 774
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
题意:给定一个n*n的01矩阵;通过行或列的变换使得主对角线上都为1;
题解:

 1.第i行放到第j行可以使得第j行的主对角线为1;

2.第j列放到第i列可以使得第j列的主对角线为1;

那么将行作为X集合,列作为Y集合,如果map[i][j]==1,那么Xi->Yj连边,求最大匹配,这样的话没有任何一个行被两个列匹配,

倘若最大匹配为n,即满足题意;

///
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <queue>
#include <typeinfo>
#include <map>
typedef long long ll;
using namespace std;
#define inf 10000000
inline ll read()
{
ll x=,f=;
char ch=getchar();
while(ch<''||ch>'')
{
if(ch=='-')f=-;
ch=getchar();
}
while(ch>=''&&ch<='')
{
x=x*+ch-'';
ch=getchar();
}
return x*f;
}
//***************************************************************
int lk[],vis[],n;
char mp[][];
bool dfs(int x){
for(int i=;i<=n;i++){
if(mp[x][i]==''&&!vis[i])
{
vis[i]=;
if(lk[i]==||dfs(lk[i]))
{
lk[i]=x;
return ;
}
}
}
return ; }
int main()
{ while(scanf("%d",&n)!=EOF)
{int x;
for(int i=;i<=n;i++){
for(int j=;j<=n;j++){
scanf("%d",&x);
mp[i][j]=x+'';
}
}
memset(lk,,sizeof(lk));
int ans=;
for(int i=;i<=n;i++){
memset(vis,,sizeof(vis));
if(dfs(i))ans++;
}
int flag;
if(ans<n)printf("-1\n");
else {
cout<<n<<endl;
//for(int i=1;i<=n;i++) cout<<i<<" "<<lk[i]<<endl;
// for(int i=1;i<=n;i++)flk[lk[i]]=i;
for(int i=;i<=n;i++)
{
for(int j=i;j<=n;j++)
{
if(lk[j]==i){
flag=j;break;
}
}
lk[flag]=lk[i];
cout<<"C "<<i<<" "<<flag<<endl;
}
}
}
return ;
}

代码