#include <bits/stdc++.h> #define dbg(x) " [" << #x << ": " << (x) << "] " using namespace std; template<typename A,typename B> ostream& operator<<(ostream& out,const pair<A,B>& p) { return out << "(" << p.first << ", " << p.second << ")"; } template<typename T> ostream& operator<<(ostream& out,const vector<T>& c) { out << "{"; for(auto it = c.begin(); it != c.end(); it++) { if(it != c.begin()) out << ", "; out << *it; } return out << "}"; } void solve() { int n,k,q; cin >> n >> k >> q; vector<int> v(n); for(int& i : v) cin >> i; vector<long long> sm(n); long long s = 0; for(int i = 0; i < n; i++) { s += v[i]; if(0 <= i - k) s -= v[i - k]; if(k - 1 <= i) { sm[i] = max(s,0LL); } } vector<long long> dp(n); while(q--) { int l,r; cin >> l >> r; l--; r--; for(int i = l; i <= r; i++) { if(i < l + k - 1) { dp[i] = 0; } else if(i == l + k - 1) { dp[i] = sm[i]; } else { dp[i] = max(dp[i - 1],dp[i - k] + sm[i]); } } cout << dp[r] << '\n'; } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int testNum = 1; //cin >> testNum; for(int i = 1; i <= testNum; i++) { solve(); } 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 | #include <bits/stdc++.h> #define dbg(x) " [" << #x << ": " << (x) << "] " using namespace std; template<typename A,typename B> ostream& operator<<(ostream& out,const pair<A,B>& p) { return out << "(" << p.first << ", " << p.second << ")"; } template<typename T> ostream& operator<<(ostream& out,const vector<T>& c) { out << "{"; for(auto it = c.begin(); it != c.end(); it++) { if(it != c.begin()) out << ", "; out << *it; } return out << "}"; } void solve() { int n,k,q; cin >> n >> k >> q; vector<int> v(n); for(int& i : v) cin >> i; vector<long long> sm(n); long long s = 0; for(int i = 0; i < n; i++) { s += v[i]; if(0 <= i - k) s -= v[i - k]; if(k - 1 <= i) { sm[i] = max(s,0LL); } } vector<long long> dp(n); while(q--) { int l,r; cin >> l >> r; l--; r--; for(int i = l; i <= r; i++) { if(i < l + k - 1) { dp[i] = 0; } else if(i == l + k - 1) { dp[i] = sm[i]; } else { dp[i] = max(dp[i - 1],dp[i - k] + sm[i]); } } cout << dp[r] << '\n'; } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int testNum = 1; //cin >> testNum; for(int i = 1; i <= testNum; i++) { solve(); } return 0; } |