#include <bits/stdc++.h> using namespace std; int n, k, q; long long skill[300002]; struct hash_pair { size_t operator() (const pair<int, int> &pair) const { return hash<int>()(pair.first) ^ hash<int>()(pair.second); } }; vector<long long> best; unordered_map< pair<int, int>, int, hash_pair> range_to_idx; vector< pair<int, int>> ranges; long long result[300002]; long long prefix[300002]; int main() { cin >> n >> k >> q; for (int i = 1; i <= n; i++) { cin >> skill[i]; prefix[i] = prefix[i-1] + skill[i]; } for (int i = 1; i <= q; i++) { int l, r; cin >> l >> r; ranges.push_back({l, r}); range_to_idx[{l, r}] = i; } sort(ranges.begin(), ranges.end()); //for (auto range : ranges) // cout << range.first << " " << range.second << endl; int curr_first = 0; for (auto range : ranges) { if (curr_first < range.first) { best.clear(); curr_first = range.first; } if (range.second - range.first < k - 1) { result[range_to_idx[range]] = 0; continue; } int pos = range.first + k - 1 + best.size(); while (pos <= range.second) { //cout << "POS: " << pos << endl; long long range_sum = prefix[pos] - prefix[pos - k]; best.push_back(max((!best.empty()) ? best.back() : 0, range_sum + ( (best.size() < k) ? 0 : best[best.size() - k]))); pos++; } result[range_to_idx[range]] = (!best.empty()) ? best.back() : 0; } for (int i = 1; i <= q; i++) { cout << result[i] << endl; } return 0; }
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> using namespace std; int n, k, q; long long skill[300002]; struct hash_pair { size_t operator() (const pair<int, int> &pair) const { return hash<int>()(pair.first) ^ hash<int>()(pair.second); } }; vector<long long> best; unordered_map< pair<int, int>, int, hash_pair> range_to_idx; vector< pair<int, int>> ranges; long long result[300002]; long long prefix[300002]; int main() { cin >> n >> k >> q; for (int i = 1; i <= n; i++) { cin >> skill[i]; prefix[i] = prefix[i-1] + skill[i]; } for (int i = 1; i <= q; i++) { int l, r; cin >> l >> r; ranges.push_back({l, r}); range_to_idx[{l, r}] = i; } sort(ranges.begin(), ranges.end()); //for (auto range : ranges) // cout << range.first << " " << range.second << endl; int curr_first = 0; for (auto range : ranges) { if (curr_first < range.first) { best.clear(); curr_first = range.first; } if (range.second - range.first < k - 1) { result[range_to_idx[range]] = 0; continue; } int pos = range.first + k - 1 + best.size(); while (pos <= range.second) { //cout << "POS: " << pos << endl; long long range_sum = prefix[pos] - prefix[pos - k]; best.push_back(max((!best.empty()) ? best.back() : 0, range_sum + ( (best.size() < k) ? 0 : best[best.size() - k]))); pos++; } result[range_to_idx[range]] = (!best.empty()) ? best.back() : 0; } for (int i = 1; i <= q; i++) { cout << result[i] << endl; } return 0; } |