您的位置:首页 > 其它

CSA:Flipping Matrix(二分图匹配 & 思维)

2018-03-02 12:23 239 查看

Flipping Matrix

Time limit: 1000 ms
Memory limit: 256 MB

You are given a binary matrix AA of size N \times NN×N. You are allowed to perform the following two operations:Take two rows and swap them. If we want to swap rows xx and yy, we'll encode this operation as 
R x y
.
Take two columns and swap them. If we want to swap columns xx and yy, we'll encode this operation as 
C x y
.
Is it possible to obtain only values of 11 on the main diagonal of AA by performing a sequence of at most NN operations? If so, print the required operations.

Standard input

The first line contains NN.The next NN lines contain NN binary values separated by spaces, representing AA.

Standard output

If there is no solution, print -1−1. Otherwise, print every operation on a separated line.

Constraints and notes

2 \leq N \leq 10^32≤N≤10​3​​ 
0 \leq A_{i, j} \leq 10≤A​i,j​​≤1 for every 1 \leq i, j \leq N1≤i,j≤N
InputOutput
3
0 0 1
0 1 0
1 0 0
C 1 3
4
1 1 0 0
0 1 0 1
1 1 0 0
0 0 0 1
-1
5
0 1 0 0 1
0 0 1 0 0
0 1 0 0 0
0 0 1 1 0
1 0 0 0 0
R 1 5
C 2 3
题意:给一个01矩阵,问能否通过若干次行或列的交换,使得主对角线上全为1,输出其中一种交换方案。思路:如果有解,一定能仅用行交换或者仅用列交换完成,因为无论怎么交换,同一行的1永远在同一行,最终对角线上的1一定来自不同的行和不同的列,假设去除其他无用的1,交换行和交换列效果等价。我们对交换列讨论,如果a[i][j]为1,i到j建边,表示j列换到i列可以匹配到一个1,最后跑一次最大匹配看是否为N即可。# include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3+3;
int a[maxn][maxn];
int l[maxn], vis[maxn];
vector<int>g[maxn];
int dfs(int u)
{
for(int v:g[u])
{
if(!vis[v])
{
vis[v]=1;
if(l[v]==0 || dfs(l[v]))
{
l[v] = u;
return 1;
}
}
}
return 0;
}
int main()
{
int n, ans=0;
scanf("%d",&n);
for(int i=1; i<=n; ++i)
for(int j=1; j<=n; ++j) scanf("%d",&a[i][j]);
for(int i=1; i<=n; ++i)
for(int j=1; j<=n; ++j) if(a[i][j]) g[i].push_back(j);
for(int i=1; i<=n; ++i)
{
memset(vis, 0, sizeof(vis));
if(dfs(i)) ++ans;
}
if(ans < n) puts("-1");
else
{
memset(vis, 0, sizeof(vis));
for(int i=1; i<=n; ++i)
{
if(vis[i]) continue;
int j=i;
while(l[j]!=i)
{
vis[l[j]]=1;
printf("C %d %d\n",i,l[j]);
j=l[j];
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: