博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hdu 2819 Swap 匈牙利算法
阅读量:3904 次
发布时间:2019-05-23

本文共 2394 字,大约阅读时间需要 7 分钟。

题目:

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

思路:

将这个方阵抽象成一个邻接矩阵,0表示不存在边,1表示存在边,题目的目标状态是对角线元素为1,所以表明,每一横行和每一竖行都必须有边,否则不能转换成目标状态。

此题可以通过匈牙利算法来实现匹配,然后遍历来实现交换元素。

代码如下:

#include 
#include
#include
#include
using namespace std;const int maxn=105;int n;int a[maxn][maxn];int match[maxn];int vis[maxn];bool Find(int x){ for (int i=1;i<=n;i++) { if(a[x][i]&&!vis[i]) { vis[i]=1; if(match[i]==-1||Find(match[i])) { match[i]=x; return true; } } } return false;}int alor(){ int sum=0; for (int i=1;i<=n;i++) { memset (vis,0,sizeof(vis)); if(Find(i)) sum++; } return sum;}int main(){ while(scanf("%d",&n)!=EOF) { memset (match,-1,sizeof(match)); for (int i=1;i<=n;i++) { for (int j=1;j<=n;j++) { scanf("%d",&a[i][j]); } } if(alor()!=n) { printf("-1\n"); continue; } else { int cnt=0; int opa[maxn*maxn],opb[maxn*maxn]; for (int i=1;i<=n;i++) { if(match[i]==i) continue; for (int j=i+1;j<=n;j++) { if(match[j]==i) { opa[cnt]=i,opb[cnt]=j; swap(match[i],match[j]); cnt++; break; } } } printf("%d\n",cnt); for (int i=0;i

 

转载地址:http://mwoen.baihongyu.com/

你可能感兴趣的文章
oracle10g rac 报ora-12545错误的解决方案 转载
查看>>
Linux配置Xmanager
查看>>
IP地址正则表达式
查看>>
对SOAP消息头的处理
查看>>
webservice TCP Monitor
查看>>
各系统下查看cpu物理和逻辑个数
查看>>
Oracle中sysdate的时区偏差
查看>>
【每日一算】旋转有序数组
查看>>
【每日一算】两数之和
查看>>
深入理解Mysql索引底层数据结构与算法
查看>>
B+tree结构详解
查看>>
B+树算法在mysql中能存多少行数据?
查看>>
【vue学习】—条件判断、循环遍历
查看>>
【vue学习】—slot插槽的使用
查看>>
【vue学习】—前端模块化
查看>>
STM32 外部中断
查看>>
STM32 PWM
查看>>
STM32 PWM波驱动模拟舵机(库函数版)
查看>>
STM32——ADC
查看>>
破解百度网盘屏蔽文件分享失效被和谐的独家秘籍
查看>>