首页 > 代码库 > hdu2819Swap (行列匹配,输出交换路径)

hdu2819Swap (行列匹配,输出交换路径)

Swap

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1453 Accepted Submission(s): 491
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.每一次行与行的交换都记录下来。

输出交换次数 和 一步一步是怎么交换的。

#include<stdio.h>
#include<string.h>
int map[105][105],vist[105],match[105],n;
int find(int i)
{
    for(int j=1;j<=n;j++)
    if(map[i][j]&&!vist[j])
    {
        vist[j]=1;
        if(match[j]==0||find(match[j]))
        {
            match[j]=i; return 1;
        }
    }
    return 0;
}
int main()
{
    int r[105][105],row1[1005],row2[1005];
    while(scanf("%d",&n)>0)
    {
        memset(r,0,sizeof(r));
        for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
        scanf("%d",&map[i][j]);
        memset(match,0,sizeof(match));
        int flag=0;
        for(int i=1;i<=n;i++)//行
        {
            memset(vist,0,sizeof(vist));
            if(!find(i))//如果找不到一条曾广路,说明左上到右下的斜对角线会断层
            {
                flag=1;break;
            }
        }
        if(flag)printf("-1\n");
        else
        {
            flag=0;
            for(int i=1;i<=n;i++)//列
            if(r[i][match[i]]==0&&i!=match[i])
            {
                flag++; r[i][match[i]]=r[match[i]][i]=1;//行i与行match[i]交换了
                if(i<match[i])row1[flag]=i,row2[flag]=match[i];//记录每次哪两行进行交换
                else row1[flag]=match[i],row2[flag]=i;
                
                for(int j=i+1;j<=n;j++)//每交换行一次,列与对应的行也要进行变化一次。
                if(match[j]==i)
                {
                    match[j]=match[i]; break;
                }
            }
            printf("%d\n",flag);
            for(int i=1;i<=flag;i++)
            printf("R %d %d\n",row1[i],row2[i]);
        }
    }
}