1844E - Great Grids - CodeForces Solution


2-sat constructive algorithms dfs and similar dsu graphs

Please click on ads to support us..

C++ Code:

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

#define ll long long

const int MXN = 4005;
vector<pair<int, int>> adj[MXN];
int color[MXN], bad = 0;

int dfs(int u, int c) {
    if (color[u] != -1) {
        if (color[u] != c) bad = 1;
        return 0;
    }

    color[u] = c;

    for (auto p: adj[u]) dfs(p.first, c ^ p.second);

    return 0;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t;
    cin >> t;

    while (t--) {
        int n, m, k;
        cin >> n >> m >> k;

        for (int i = 0; i < k; ++i) {
            int x1, y1, x2, y2;
            cin >> x1 >> y1 >> x2 >> y2;

            --x1, --x2, --y1, --y2;

            adj[min(x1, x2)].push_back({ n + min(y1, y2), (x1 + y1 != x2 + y2) });
            adj[n + min(y1, y2)].push_back({ min(x1, x2), (x1 + y1 != x2 + y2) });
        }

        fill(color, color+n+m, -1);
        bad = 0;

        for (int i = 0; i < n + m; ++i) {
            if (color[i] == -1) dfs(i, 0);
        }

        cout << (bad ? "NO\n" : "YES\n");

        for (int i = 0; i < n+m; ++i) adj[i].clear();
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

1725D - Deducing Sortability
1501A - Alexey and Train
721B - Passwords
1263D - Secret Passwords
1371B - Magical Calendar
1726E - Almost Perfect
1360C - Similar Pairs
900A - Find Extra One
1093D - Beautiful Graph
748A - Santa Claus and a Place in a Class
1511B - GCD Length
676B - Pyramid of Glasses
597A - Divisibility
1632A - ABC
1619D - New Year's Problem
242B - Big Segment
938A - Word Correction
159C - String Manipulation 10
258A - Little Elephant and Bits
1536C - Diluc and Kaeya
1428C - ABBB
1557A - Ezzat and Two Subsequences
255A - Greg's Workout
1059A - Cashier
1389C - Good String
1561A - Simply Strange Sort
1337B - Kana and Dragon Quest game
137C - History
1443C - The Delivery Dilemma
6C - Alice Bob and Chocolate