#include <iostream> constexpr int MAX_N = 3 * 100000; int n; int k; int q; long long a[MAX_N]; long long sums[MAX_N]; void prepareVariables() { for (int i = 0; i < k; i++) { sums[0] += a[i]; } for (int i = 1; i < n - k + 1; i++) { sums[i] = sums[i - 1]; sums[i] -= a[i - 1]; sums[i] += a[i + k - 1]; } } long long solveOneBruteForce(int left, int right) { long long biggestSum = 0; for (int i = 0 + left; i < right - k + 2; i++) { // for every k sized squad // in range if (sums[i] > 0) { // bigger than 0 long long sum = sums[i]; sum += solveOneBruteForce(i + k, right); if (sum > biggestSum) { biggestSum = sum; } } } return biggestSum; } void readInputAndSolve() { std::cin >> n >> k >> q; for (int i = 0; i < n; i++) { std::cin >> a[i]; } prepareVariables(); for (int i = 0; i < q; i++) { int l; int r; std::cin >> l >> r; l--; r--; std::cout << solveOneBruteForce(l, r); if (i != q - 1) std::cout << std::endl; } } int main() { readInputAndSolve(); 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 62 63 64 65 66 | #include <iostream> constexpr int MAX_N = 3 * 100000; int n; int k; int q; long long a[MAX_N]; long long sums[MAX_N]; void prepareVariables() { for (int i = 0; i < k; i++) { sums[0] += a[i]; } for (int i = 1; i < n - k + 1; i++) { sums[i] = sums[i - 1]; sums[i] -= a[i - 1]; sums[i] += a[i + k - 1]; } } long long solveOneBruteForce(int left, int right) { long long biggestSum = 0; for (int i = 0 + left; i < right - k + 2; i++) { // for every k sized squad // in range if (sums[i] > 0) { // bigger than 0 long long sum = sums[i]; sum += solveOneBruteForce(i + k, right); if (sum > biggestSum) { biggestSum = sum; } } } return biggestSum; } void readInputAndSolve() { std::cin >> n >> k >> q; for (int i = 0; i < n; i++) { std::cin >> a[i]; } prepareVariables(); for (int i = 0; i < q; i++) { int l; int r; std::cin >> l >> r; l--; r--; std::cout << solveOneBruteForce(l, r); if (i != q - 1) std::cout << std::endl; } } int main() { readInputAndSolve(); return 0; } |