#include <iostream> #include <algorithm> #include <queue> #include <tuple> using namespace std; #define N 300005 int n, k, q; int a, b; int cur = -1; long long w[N]; long long dp[N]; long long ans[N]; tuple<int, int, int> queries[N]; void calculate(int p){ long long sum = 0; for(int i=p;i<n;i++){ sum += w[i]; if(i >= p+k-1){ if(i >= p+k){ sum -= w[i-k]; dp[i] = max((sum > 0 ? sum : 0) + dp[i-k], dp[i-1]); } else{ dp[i] = max(sum, 0LL); } } else{ dp[i] = 0; } //cout << sum << " "; } //cout << "\n"; } int main(){ cin.tie(0); ios_base::sync_with_stdio(0); cin >> n >> k >> q; for(int i=0;i<n;i++){ cin >> w[i]; } for(int i=0;i<q;i++){ cin >> a >> b; a--, b--; queries[i] = make_tuple(a, b, i); } sort(queries, queries+q); for(int i=0;i<q;i++){ int index; tie(a, b, index) = queries[i]; if(a != cur){ cur = a; calculate(a); } /* for(int i=cur;i<n;i++){ cout << dp[i] << " "; } cout << "\n";*/ ans[index] = dp[b]; } for(int i=0;i<q;i++){ cout << ans[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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | #include <iostream> #include <algorithm> #include <queue> #include <tuple> using namespace std; #define N 300005 int n, k, q; int a, b; int cur = -1; long long w[N]; long long dp[N]; long long ans[N]; tuple<int, int, int> queries[N]; void calculate(int p){ long long sum = 0; for(int i=p;i<n;i++){ sum += w[i]; if(i >= p+k-1){ if(i >= p+k){ sum -= w[i-k]; dp[i] = max((sum > 0 ? sum : 0) + dp[i-k], dp[i-1]); } else{ dp[i] = max(sum, 0LL); } } else{ dp[i] = 0; } //cout << sum << " "; } //cout << "\n"; } int main(){ cin.tie(0); ios_base::sync_with_stdio(0); cin >> n >> k >> q; for(int i=0;i<n;i++){ cin >> w[i]; } for(int i=0;i<q;i++){ cin >> a >> b; a--, b--; queries[i] = make_tuple(a, b, i); } sort(queries, queries+q); for(int i=0;i<q;i++){ int index; tie(a, b, index) = queries[i]; if(a != cur){ cur = a; calculate(a); } /* for(int i=cur;i<n;i++){ cout << dp[i] << " "; } cout << "\n";*/ ans[index] = dp[b]; } for(int i=0;i<q;i++){ cout << ans[i] << "\n"; } return 0; } |