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

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 -11.

Otherwise, print every operation on a separated line.

Constraints and notes

  • 2 \leq N \leq 10^32N103 
  • 0 \leq A_{i, j} \leq 10Ai,j1 for every 1 \leq i, j \leq N1i,jN
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值