HDU2819 Swap(二分图匹配匈牙利算法+记录路径)

本文探讨了一个矩阵转换问题,即通过交换矩阵的行或列,尝试将矩阵的主对角线元素全部变为1。文章提出了解决该问题的有效算法,并通过构建二分图进行完美匹配来判断是否有可行解,最后给出了具体的实现代码。

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

思路

题目给了一个nn的图,问能不能通过交换行和列,使这个图的主对角线变成1(A[i][i]=1),如果不可以输出-1,如果可以输出路径

首先要明确:
只交换行或者只交换列,就一定可以达到题目的要求,可以这么理解:

所有的对角线都是1,所以也就是矩阵的秩就是N,所以秩小于N就无解。另外,根据矩阵的性质,任意交换矩阵的两行 或者
两列,矩阵的秩不变,也就保证了如果通过 只交换行 或 只交换列 无法得到解的话,那么其他交换形式也必然无解

我们假设交换列,建立二分图,左边的节点为每一行的行号,二分图右边的节点为每一行中出现的“1”对应的列号
那么首先要保证问题有解,就必须达到完美匹配,只有当最大匹配的个数为n,才可以保证有解,这个画一个图就知道为什么了

在记录路径的时候,因为我们要达到的状态是A[i][i]=1,所以当我们遇到match[i]!=i的时候,就要寻找变换,找到以后记录一下,并且交换match[i]match[j],最后输出交换的列就可以

代码

#include <bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
const int N=100+20;
int e[N][N],vis[N],match[N],l[N],r[N],n;
int dfs(int u)
{
    for(int i=1; i<=n; i++)
    {
        if(e[u][i]&&!vis[i])
        {
            vis[i]=1;
            if(!match[i]||dfs(match[i]))
            {
                match[i]=u;
                return 1;
            }
        }
    }
    return 0;
}
int query()
{
    mem(match,0);
    int sum=0;
    for(int i=1; i<=n; i++)
    {
        mem(vis,0);
        if(dfs(i))sum++;
    }
    return sum;
}
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1; i<=n; i++)
            for(int j=1; j<=n; j++)
                scanf("%d",&e[i][j]);
        if(query()!=n)puts("-1");
        else
        {
            int num=0;
            for(int i=1; i<=n; i++)
                if(match[i]!=i)
                    for(int j=1; j<=n; j++)
                        if(match[j]==i)
                        {
                            l[num]=i;
                            r[num++]=j;
                            swap(match[i],match[j]);
                            break;
                        }
            printf("%d\n",num);
            for(int i=0; i<num; i++)
                printf("C %d %d\n",l[i],r[i]);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值