#include <bits/stdc++.h> using namespace std; vector<int> soldiers; vector<long long> DP; vector<long long> sums; int numberOfSoldiers; int sizeOfSquad; int L; int R; long long test() { if (R - L < sizeOfSquad - 1) { return 0; } for (int i = L; i < L + sizeOfSquad; i++) { DP[i] = 0; } DP[L + sizeOfSquad - 1] = max(DP[L + sizeOfSquad - 1], sums[L + sizeOfSquad] - sums[L]); for (int i = L + sizeOfSquad; i < R; i++) { DP[i] = max(sums[i + 1] - sums[i + 1 - sizeOfSquad] + DP[i - sizeOfSquad], DP[i - 1]); } return DP[R - 1]; } int main() { cin.tie(0); ios::sync_with_stdio(0); int tests; cin >> numberOfSoldiers >> sizeOfSquad >> tests; soldiers = vector<int>(numberOfSoldiers); DP = vector<long long>(numberOfSoldiers); sums = vector<long long>(numberOfSoldiers + 1); cin >> soldiers[0]; sums[0] = 0; sums[1] = soldiers[0]; for (int i = 1; i < numberOfSoldiers; i++) { cin >> soldiers[i]; sums[i + 1] = sums[i] + soldiers[i]; } while (tests--) { cin >> L >> R; L--; cout << test() << 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 | #include <bits/stdc++.h> using namespace std; vector<int> soldiers; vector<long long> DP; vector<long long> sums; int numberOfSoldiers; int sizeOfSquad; int L; int R; long long test() { if (R - L < sizeOfSquad - 1) { return 0; } for (int i = L; i < L + sizeOfSquad; i++) { DP[i] = 0; } DP[L + sizeOfSquad - 1] = max(DP[L + sizeOfSquad - 1], sums[L + sizeOfSquad] - sums[L]); for (int i = L + sizeOfSquad; i < R; i++) { DP[i] = max(sums[i + 1] - sums[i + 1 - sizeOfSquad] + DP[i - sizeOfSquad], DP[i - 1]); } return DP[R - 1]; } int main() { cin.tie(0); ios::sync_with_stdio(0); int tests; cin >> numberOfSoldiers >> sizeOfSquad >> tests; soldiers = vector<int>(numberOfSoldiers); DP = vector<long long>(numberOfSoldiers); sums = vector<long long>(numberOfSoldiers + 1); cin >> soldiers[0]; sums[0] = 0; sums[1] = soldiers[0]; for (int i = 1; i < numberOfSoldiers; i++) { cin >> soldiers[i]; sums[i + 1] = sums[i] + soldiers[i]; } while (tests--) { cin >> L >> R; L--; cout << test() << endl; } return 0; } |