hdu2819 Swap(二分匹配)

来源:互联网 发布:梦幻西游手游mac客户端 编辑:程序博客网 时间:2024/06/05 18:29

Swap

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1732    Accepted Submission(s): 580
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
20 11 021 01 0
 

Sample Output
1R 1 2-1
 

Source
2009 Multi-University Training Contest 1 - Host by TJU 
/*二分匹配输出过程。挺经典的。在寻找匹配的过程值得思考。。加油!!Time:2015-3-15 16:31*/#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int MAX=103;typedef long long LL;const int INF=0x3f3f3f3f;int linker[MAX];bool vis[MAX];int g[MAX][MAX];int n;bool DFS(int u){    for(int v=1;v<=n;v++){        if(g[u][v]&&!vis[v]){            vis[v]=true;            if(linker[v]==-1||DFS(linker[v])){                linker[v]=u;                return true;            }        }    }    return false;}int hungary(){    memset(linker,-1,sizeof(linker));    int ans=0;    for(int i=1;i<=n;i++){        memset(vis,0,sizeof(vis));        if(DFS(i))ans++;    }    return ans;}int a[1005],b[1005];int main(){    int num;    int i,j;    while(scanf("%d",&n)!=EOF){        for(i=1;i<=n;i++){            for(j=1;j<=n;j++){               scanf("%d",&g[i][j]);            }        }        int ans=hungary();        //printf("ans=%d\n",ans);        if(ans<n){printf("-1\n");continue;}            num=0;            for(i=1;i<=n;i++){                for(j=i;j<=n;j++){                    if(linker[j]==i)break;                }                if(j!=i){                    a[num]=i;b[num++]=j;                    swap(linker[i],linker[j]);                }            }            printf("%d\n",num);            for(i=0;i<num;i++){                printf("C %d %d\n",a[i],b[i]);            }    }return 0;}

0 0
原创粉丝点击