#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll inf = 1e17; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k, q; cin >> n >> k >> q; int a[n + 1]; ll S[n + 1]; S[0] = 0; ll R[n - k + 1]; for (int i = 1; i <= n; i++) { cin >> a[i]; S[i] = S[i - 1] + a[i]; } for (int i = 0; i <= n - k; i++) { R[i] = S[i + k] - S[i]; } ll dp[n + 1][n + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j < min(n + 1, i + k - 1); j++) { dp[i][j] = 0; } } for (int i = 1; i <= n; i++) { for (int j = i + k - 1; j <= n; j++) { dp[i][j] = max(dp[i][j - 1], dp[i][j - k] + R[j - k]); } } int x, y; ll res[q + 1]; for (int i = 1; i <= q; i++) { cin >> x >> y; res[i] = dp[x][y]; } for (int i = 1; i <= q; i++) { cout << res[i] << "\n"; } 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 | #include <bits/stdc++.h> using namespace std; typedef long long ll; const ll inf = 1e17; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k, q; cin >> n >> k >> q; int a[n + 1]; ll S[n + 1]; S[0] = 0; ll R[n - k + 1]; for (int i = 1; i <= n; i++) { cin >> a[i]; S[i] = S[i - 1] + a[i]; } for (int i = 0; i <= n - k; i++) { R[i] = S[i + k] - S[i]; } ll dp[n + 1][n + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j < min(n + 1, i + k - 1); j++) { dp[i][j] = 0; } } for (int i = 1; i <= n; i++) { for (int j = i + k - 1; j <= n; j++) { dp[i][j] = max(dp[i][j - 1], dp[i][j - k] + R[j - k]); } } int x, y; ll res[q + 1]; for (int i = 1; i <= q; i++) { cin >> x >> y; res[i] = dp[x][y]; } for (int i = 1; i <= q; i++) { cout << res[i] << "\n"; } return 0; } |