Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code

#include <bits/stdc++.h>
using namespace std;

void solve(vector<vector<int>> &m) {
    int n = m.size();

    vector<int> a(n);

    // In each iteration, we compute the answer for i-th bit.
    for (int bit = 0; bit < 30; bit++) {
        int zero_location = -1;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // If this is a one, ignore it.
                if ((1 << bit) & m[i][j]) {
                } else {
                    zero_location = i;
                }
            }
        }
        // All bits should be set.
        if (zero_location == -1) {
            for (int i = 0; i < n; i++) {
                a[i] |= (1 << bit);
            }
        } else {
            // 0 | x = x
            for (int j = 0; j < n; j++) {
                if (j != zero_location) {
                    if ((1 << bit) & m[zero_location][j]) {
                        a[j] |= (1 << bit);
                    }
                }
            }
        }
    }

    // Now do a simple verification.
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == j) {
                continue;
            }
            if (m[i][j] != (a[i] | a[j])) {
                cout << "NO"
                     << "\n";
                return;
            }
        }
    }

    cout << "YES"
         << "\n";
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
    cout << "\n";
}

int main() {
    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        int n;
        cin >> n;
        vector<vector<int>> m(n, vector<int>(n, 0));
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cin >> m[i][j];
            }
        }
        solve(m);
    }
    return 0;
}