AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
    • 吐槽
  • App
  • 登录/注册

AcWing 4804. 构造矩阵

作者: 作者的头像   L-China ,  2023-02-04 23:06:10 ,  所有人可见 ,  阅读 13


4


法一:

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 110;

int m, n;
int b[N][N], a[N][N];
bool flag;

int main() {
    cin >> m >> n;
    for (int i = 1; i <= m; i ++)
        for (int j = 1; j <= n; j ++) 
            cin >> b[i][j];

    memset(a, -1, sizeof a);

    for (int i = 1; i <= m; i ++) 
        for (int j = 1; j <= n; j ++) {
            if (b[i][j] == 0) {
                for (int x = 1; x <= n; x ++) // 行
                        a[i][x] = 0;
                for (int y = 1; y <= m; y ++) // 列
                        a[y][j] = 0;
            }
        }

    for (int i = 1; i <= m; i ++) 
        for (int j = 1; j <= n; j ++) {
            if (b[i][j] == 1) {
                flag = false;
                for (int x = 1; x <= n; x ++) // 行
                    if (a[i][x] == -1 || a[i][x] == 1) {
                        a[i][x] = 1;
                        flag = true;
                    }
                for (int y = 1; y <= m; y ++) // 列
                    if (a[y][j] == -1 || a[y][j] == 1) {
                        a[y][j] = 1;
                        flag = true;
                    }
                if (flag == false) {
                    cout << "NO";
                    return 0;
                }    
            }
        }    


    cout << "YES" << endl;
    for (int i = 1; i <= m; i ++) {
        for (int j = 1; j <= n; j ++) {
            cout << a[i][j] << ' '; 
        }
        cout << endl;
    }

    return 0;
}

法二:

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 110;

int m, n;
int b[N][N], a[N][N];

bool check() {
    for (int i = 1; i <= m; i ++)
        for (int j = 1; j <= n; j ++)
            if (b[i][j]) {
                int cnt = 0;
                for (int x = 1; x <= n; x ++) cnt += a[i][x];
                for (int y = 1; y <= m; y ++) cnt += a[y][j];
                if (!cnt) return false;
            }
    return true;        
}

int main() {
    cin >> m >> n;

    memset(a, -1, sizeof a);
    for (int i = 1; i <= m; i ++) 
        for (int j = 1; j <= n; j ++) {
            cin >> b[i][j];
            if (b[i][j] == 0) {
                for (int x = 1; x <= n; x ++) a[i][x] = 0; // 让第i行全为0
                for (int y = 1; y <= m; y ++) a[y][j] = 0; // 让第j列全为0
            }
        }

    if (check()) {
        cout << "YES" << endl;
        for (int i = 1; i <= m; i ++) {
            for (int j = 1; j <= n; j ++) 
                cout << !!a[i][j] << ' ';
            cout << endl;    
        }
    }
    else cout << "NO";

    return 0;
}

0 评论

你确定删除吗?
1024
x

© 2018-2023 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息