Explanation
The overall approach is to use 2D prefix sums along with some jank combinatorics stuff.
We start by constructing a 2D array where contains the area of all rectangles with height and width exactly.
To get the area of all rectangles that satisfy a certain query, we perform a 2D prefix sum from to inclusive.
Implementation
Time Complexity: , where is the largest dimension we have to handle.
C++
#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;constexpr int MAX_SIDE = 1000;int main() {
Java
import java.io.*;import java.util.*;public class CountingRectangles {private static final int MAX_SIDE = 1000;public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new InputStreamReader(System.in));int testNum = Integer.parseInt(read.readLine());for (int t = 0; t < testNum; t++) {
Python
Warning!
This solution only runs in time when submitted with PyPy.
MAX_SIDE = 1000overall_ans = []for _ in range(int(input())):rect_num, query_num = [int(i) for i in input().split()]pref = [[0 for _ in range(MAX_SIDE + 1)] for _ in range(MAX_SIDE + 1)]for _ in range(rect_num):h, w = [int(i) for i in input().split()]
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!