// #include <bits/stdc++.h> #define FAST ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); #include <iostream> #include <vector> #include <unordered_map> using namespace std; int k; vector<int64_t> sums; unordered_map<int, unordered_map<int, int64_t>> memo; int64_t solve(int l, int r) { // printf("DBGGGG XD %d %d\n", l, r); if (memo[l][r]) if (memo[l][r] == -1) return 0; else return memo[l][r]; if (r - l + 1 < k) return 0; int64_t curr; int64_t max = 0; for (int i = 0; i < k && (l + i + k) <= r + 1; i++) { curr = sums[l + i + k] - sums[i + l]; if (curr < 0) curr = 0; curr += solve(l + i + k, r); if (curr > max) max = curr; // printf("dbg l= %d r=%d i=%d v=%ld \n", l, r, i, curr); } if (max == 0) memo[l][r] = -1; else memo[l][r] = max; return max; } int main() { int n, q, l, r; cin >> n >> k >> q; sums.resize(n + 1); sums[0] = 0; for (int i = 0; i < n; i++) { cin >> sums[i + 1]; sums[i + 1] += sums[i]; } for (int i = 0; i < q; i++) { cin >> l >> r; l--; r--; cout << solve(l, r) << endl; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | // #include <bits/stdc++.h> #define FAST ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); #include <iostream> #include <vector> #include <unordered_map> using namespace std; int k; vector<int64_t> sums; unordered_map<int, unordered_map<int, int64_t>> memo; int64_t solve(int l, int r) { // printf("DBGGGG XD %d %d\n", l, r); if (memo[l][r]) if (memo[l][r] == -1) return 0; else return memo[l][r]; if (r - l + 1 < k) return 0; int64_t curr; int64_t max = 0; for (int i = 0; i < k && (l + i + k) <= r + 1; i++) { curr = sums[l + i + k] - sums[i + l]; if (curr < 0) curr = 0; curr += solve(l + i + k, r); if (curr > max) max = curr; // printf("dbg l= %d r=%d i=%d v=%ld \n", l, r, i, curr); } if (max == 0) memo[l][r] = -1; else memo[l][r] = max; return max; } int main() { int n, q, l, r; cin >> n >> k >> q; sums.resize(n + 1); sums[0] = 0; for (int i = 0; i < n; i++) { cin >> sums[i + 1]; sums[i + 1] += sums[i]; } for (int i = 0; i < q; i++) { cin >> l >> r; l--; r--; cout << solve(l, r) << endl; } } |