题解:P17182 [ICPC 2017 Hong Kong R] Black and White

· · 题解

题目传送门

思路

简单的二维差分,如果不会的花可以去 这里 学习一下。

直接对于每次翻转进行二维差分,然后对差分数组前缀和:

记得卡常。

AC CODE

#include <bits/stdc++.h>
using namespace std;
int T, n, k, a, b, c, d, res[10002][10002];
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin >> T;
    while (T--) {
        cin >> n >> k;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                res[i][j] = 0;
            }
        }
        for (int i = 1; i <= k; i++) {
            cin >> a >> c >> b >> d;
            res[a][b]++;
            res[c + 1][b]--;
            res[a][d + 1]--;
            res[c + 1][d + 1]++;
        }
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                res[i][j] = res[i][j] + res[i - 1][j] + res[i][j - 1] - res[i - 1][j - 1];
                if (res[i][j] % 2) ans++;
            }
        }
        cout << ans << '\n';
    }
    return 0;
}