#include <cstdio> #include <algorithm> #include <vector> #include <unordered_map> using namespace std; typedef long long ll; #define MAX 300100 ll S[2*MAX]; ll Sk[2*MAX]; ll Sk0[2*MAX]; ll a[2*MAX]; struct Query { int l,r; }; Query query[MAX]; vector<int> l_pos[MAX]; vector<int> r_pos; unordered_map<ll, ll> result; int main() { int n,k,q; scanf("%d %d %d", &n, &k, &q); for(int i=1;i<=n;i++) scanf("%lld", &a[i]); for(int i=0;i<q;i++) { scanf("%d %d", &query[i].l, &query[i].r); if(query[i].r-query[i].l+1>=k) { l_pos[query[i].r].push_back(query[i].l); r_pos.push_back(query[i].r); } } for(int r=1;r<=n;r++) { auto &v = l_pos[r]; sort(v.begin(),v.end()); auto last = std::unique(v.begin(), v.end()); v.erase(last, v.end()); } { auto &v = r_pos; sort(v.begin(),v.end()); auto last = std::unique(v.begin(), v.end()); v.erase(last, v.end()); } for(int i=1;i<=n;i++) S[i] = S[i-1] + a[i]; for(int i=1;i<=n-k+1;i++) Sk[i] = S[i+k-1] - S[i-1]; ll tmp[2*MAX] = {}; for(int r: r_pos) { int min_l = l_pos[r][0]; for (int l=r+1;l>r-k+1;l--) tmp[l] = 0; for (int l=r-k+1;l>=min_l;l--) tmp[l] = max(tmp[l+1],Sk[l]+tmp[l+k]); for(int l:l_pos[r]) { ll h = (ll(r)<<20) | ll(l); result[h]=tmp[l]; } } for(int i=0;i<q;i++) { ll h = (ll(query[i].r)<<20) | ll(query[i].l); printf("%lld\n", result[h]); } }
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 | #include <cstdio> #include <algorithm> #include <vector> #include <unordered_map> using namespace std; typedef long long ll; #define MAX 300100 ll S[2*MAX]; ll Sk[2*MAX]; ll Sk0[2*MAX]; ll a[2*MAX]; struct Query { int l,r; }; Query query[MAX]; vector<int> l_pos[MAX]; vector<int> r_pos; unordered_map<ll, ll> result; int main() { int n,k,q; scanf("%d %d %d", &n, &k, &q); for(int i=1;i<=n;i++) scanf("%lld", &a[i]); for(int i=0;i<q;i++) { scanf("%d %d", &query[i].l, &query[i].r); if(query[i].r-query[i].l+1>=k) { l_pos[query[i].r].push_back(query[i].l); r_pos.push_back(query[i].r); } } for(int r=1;r<=n;r++) { auto &v = l_pos[r]; sort(v.begin(),v.end()); auto last = std::unique(v.begin(), v.end()); v.erase(last, v.end()); } { auto &v = r_pos; sort(v.begin(),v.end()); auto last = std::unique(v.begin(), v.end()); v.erase(last, v.end()); } for(int i=1;i<=n;i++) S[i] = S[i-1] + a[i]; for(int i=1;i<=n-k+1;i++) Sk[i] = S[i+k-1] - S[i-1]; ll tmp[2*MAX] = {}; for(int r: r_pos) { int min_l = l_pos[r][0]; for (int l=r+1;l>r-k+1;l--) tmp[l] = 0; for (int l=r-k+1;l>=min_l;l--) tmp[l] = max(tmp[l+1],Sk[l]+tmp[l+k]); for(int l:l_pos[r]) { ll h = (ll(r)<<20) | ll(l); result[h]=tmp[l]; } } for(int i=0;i<q;i++) { ll h = (ll(query[i].r)<<20) | ll(query[i].l); printf("%lld\n", result[h]); } } |