「HDU2819」 Swap 题解
「HDU2819」 Swap 题解
题目
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
1 | 2 |
Sample Output
1 | 1 |
题目大意
给定 的矩阵,矩阵中每一个位置都有 个数 或者 ,现在需要你通过交换某两行或者某两列使得这个矩阵的对角线的格子中都是 ,如果有解则输出任意一组解,如果没有解则输出 。
其中输入数据包含若干组数据,每组数据第一行为 ,接下来 行 每行包括 个数代表这个矩阵。
对于每组数据,如果有解,则第一行输出交换的次数 ,接下来 行第一个为 或者 表示交换行或者列,第二三个数据 和 表示交换第 与第 行或列。
解题
不难发现,如果每一行都能找到一个与其他行不冲突的列,并且行与列的交点位置为 ,则可以通过交换行或列使得对角线上都为 。
对于每一个位置 ,如果这个位置的数为 ,则从 号点向 号点连边,表示 行与 列可以进行匹配,建图完成后,对这个二分图进行匹配,如果能形成 个匹配则说明每一行都能找到与其他行不冲突的一列,并且交点位置是 ,即有解,否则无解。
最后在根据 result
数组统计输出方案即可。
代码
1 |
|