Skip to content

USACO 2019 February Contest Silver Division - Painting the Barn#

Problem link: here

Solution Author: Stefan Dascalescu

Problem Solution#

Do a 2D prefix sum in a 2D grid with the lower coordinate and upper coordinate. Then compute the full prefix sums and find which ones are equal to the desired amount of "overlaps". Add 1 to both points given and add -1 to the opposite corners.

Source code#

The source code in C++ can be seen below.

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

const int MAXCOORD = 1e3;

int mat[MAXCOORD][MAXCOORD], prefix[MAXCOORD][MAXCOORD];

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

    freopen("paintbarn.in", "r", stdin);
    freopen("paintbarn.out", "w", stdout);

    int n, k, x1, y1, x2, y2;

    cin >> n >> k;
    for (int i = 0; i < n; i++) {
        cin >> x1 >> y1 >> x2 >> y2;
        mat[x1][y1]++;
        mat[x1][y2 + 1]--;
        mat[x2 + 1][y1]--;
        mat[x2][y2]++;
    }
    int ans = 0;
    for (int lin = 1; lin <= MAXCOORD; lin++) {
        for (int col = 1; col <= MAXCOORD; col++) {
            prefix[lin][col] = prefix[lin - 1][col] + prefix[lin][col - 1] - prefix[lin - 1][col - 1] + mat[lin][col];
            if (prefix[lin][col] == k) ++ans;
        }
    }
    cout << ans;
    return 0;
}