#include<bits/stdc++.h> using namespace std; vector<int> V; vector<long long> P; int main() { int n,k,q; cin>>n>>k>>q; V.resize(n+1); P.resize(n+1,0); for(int i=1;i<=n;i++) { cin>>V[i]; P[i]=P[i-1]+V[i]; } if(n<q) { vector< vector<long long> > DP; DP.resize(n+1); for(int i=0;i<=n;i++) DP[i].resize(n+1,1e9); for(int l=1;l<=n;l++) { DP[l][l-1]=0; for(int i=l-1;i<min(l+k-1,n+1);i++) DP[l][i]=0; for(int r=l+k-1;r<=n;r++) { DP[l][r] = max(DP[l][r-1],DP[l][r-k]+(P[r]-P[r-k])); } } int l,r; while(q--) { cin>>l>>r; cout<<DP[l][r]<<"\n"; } } else { vector<long long> DP; DP.resize(n+1,1e9); int l,r; while(q--) { cin>>l>>r; for(int i=l-1;i<min(l+k-1,r+1);i++) DP[i]=0; for(int i=l+k-1;i<=r;i++) { DP[i] = max(DP[i-1],DP[i-k]+(P[i]-P[i-k])); } cout<<DP[r]<<"\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; vector<int> V; vector<long long> P; int main() { int n,k,q; cin>>n>>k>>q; V.resize(n+1); P.resize(n+1,0); for(int i=1;i<=n;i++) { cin>>V[i]; P[i]=P[i-1]+V[i]; } if(n<q) { vector< vector<long long> > DP; DP.resize(n+1); for(int i=0;i<=n;i++) DP[i].resize(n+1,1e9); for(int l=1;l<=n;l++) { DP[l][l-1]=0; for(int i=l-1;i<min(l+k-1,n+1);i++) DP[l][i]=0; for(int r=l+k-1;r<=n;r++) { DP[l][r] = max(DP[l][r-1],DP[l][r-k]+(P[r]-P[r-k])); } } int l,r; while(q--) { cin>>l>>r; cout<<DP[l][r]<<"\n"; } } else { vector<long long> DP; DP.resize(n+1,1e9); int l,r; while(q--) { cin>>l>>r; for(int i=l-1;i<min(l+k-1,r+1);i++) DP[i]=0; for(int i=l+k-1;i<=r;i++) { DP[i] = max(DP[i-1],DP[i-k]+(P[i]-P[i-k])); } cout<<DP[r]<<"\n"; } } return 0; } |