USACO · 1541

Photoshoot

This C++ solution uses range queries for USACO 1541 Photoshoot. Read the reasoning, inspect the code, or try your own test case below.

1541Implementation & simulationRange queriesC++29 lines
Solution163of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Range queries

This duplicate implementation also exactly matches the official Photoshoot update and maximum K-by-K attractiveness task.

Implementation & simulation

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

Problem_3_Photoshoot.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    int main() {
        ios::sync_with_stdio(0); cin.tie(0); 
        int n, k, q; cin >> n >> k >> q;
        ///we maintain previous window and updated window. suprisingly easier than p1
        //throwing 2d seg tree at this problem is too hard so we just brute force!!!!
        //since k is so tiny we brute force. We do not need to loop all k * k squares only the ones influenced
        //the cur[i][j] will be the sum of beauty values inside the k × k square and top left corner is row i col j
        vector<vector<int>> pre(n, vector<int>(n)), cur(n, vector<int>(n));
        int ans = 0;
        while (q--) {
            int r, c, v; cin >> r >> c >> v;
            r--; c--;
            int change = v - pre[r][c];
            pre[r][c] = v;
            // boundaries of winodws
            int topr = max(0, r - k + 1), bottomr = min(r, n - k), leftcol = max(0, c - k + 1), rightcol = min(c, n - k);
            //all windows affected by this update 
            for (int i = topr; i <= bottomr; i++) {
                for (int j = leftcol; j <= rightcol; j++) {
                    cur[i][j] += change;
                    ans = max(ans, cur[i][j]);
                }
            }
            cout << ans << '\n';
        }
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.