1722E - Counting Rectangles - CodeForces Solution


brute force data structures dp implementation

Please click on ads to support us..

Python Code:

def solve(rectangles, queries):
    acc = [[0] * 1001 for _ in range(1001)]
    for hi, wi in rectangles:
        acc[hi][wi] += hi * wi

    for r in range(1001):
        for c in range(1001):
            acc[r][c] += acc[r-1][c] + acc[r][c-1] - acc[r-1][c-1]

    ans = []
    for hs, ws, hb, wb in queries:
        cur = acc[hb-1][wb-1] - acc[hb-1][ws] - acc[hs][wb-1] + acc[hs][ws]
        ans.append(cur)

    return ans


def main():
    t = int(input())
    output = []
    for _ in range(t):
        n, q = read_ints()
        rectangles = [read_ints() for _ in range(n)]
        queries = [read_ints() for _ in range(q)]

        ans = solve(rectangles, queries)
        output += ans

    print_int_lines(output)


def read_ints():
    return [int(c) for c in input().split()]


def print_int_lines(lst):
    print('\n'.join(map(str, lst)))


if __name__ == "__main__":
    main()

C++ Code:

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

const int cnst = 1e3+5;
// const int mod = 1e9+7;
bool mutipletestcase = true;

void solve() {
    int n, q; 
    cin >> n >> q;

    int presum2d[cnst][cnst];
    memset(presum2d, 0, sizeof(presum2d));

    for(int i = 1; i<=n; i++) {
        int a, b; cin >> a >> b;
        presum2d[a][b] += (a*b);
    }


    for(int i = 1; i<=cnst-5; i++) {
        for(int j = 1; j<=cnst-5; j++) {
            presum2d[i][j] += presum2d[i-1][j]+presum2d[i][j-1]-presum2d[i-1][j-1];
        }
    }

    while(q--) {
        int rst, cst, rnd, cnd; cin >> rst >> cst >> rnd >> cnd;
        cout << presum2d[rnd-1][cnd-1]-presum2d[rst][cnd-1]-presum2d[rnd-1][cst]+presum2d[rst][cst] << endl;
    }
}

signed main() {
    ios_base::sync_with_stdio(false);
    int t = 1; 
    if(mutipletestcase) cin >> t;
    while(t--) solve();
}


Comments

Submit
0 Comments
More Questions

144. Binary Tree Preorder Traversal
137. Single Number II
130. Surrounded Regions
129. Sum Root to Leaf Numbers
120. Triangle
102. Binary Tree Level Order Traversal
96. Unique Binary Search Trees
75. Sort Colors
74. Search a 2D Matrix
71. Simplify Path
62. Unique Paths
50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram