|
3 | 3 | ### KGSS - Maximum Sum
|
4 | 4 | - **Link:** https://www.spoj.com/problems/KGSS/
|
5 | 5 | - **Algorithm:** Segment tree, Pair Segment Tree
|
6 |
| - |
| 6 | + |
7 | 7 | > Firstly store all value
|
| 8 | +<details> |
| 9 | + <summary>Code</summary> |
| 10 | + |
| 11 | + ```c++ |
| 12 | +#include<bits/stdc++.h> |
| 13 | +#define MAX 100007 |
| 14 | +using namespace std; |
| 15 | +typedef long long ll; |
| 16 | + |
| 17 | +pair<int,int>tree[4*MAX]; |
| 18 | +int in[MAX]; |
| 19 | + |
| 20 | +pair<int,int>cmp(pair<int,int>a,pair<int,int>b) { |
| 21 | + vector<int>v; |
| 22 | + v.push_back(a.first); |
| 23 | + v.push_back(a.second); |
| 24 | + v.push_back(b.first); |
| 25 | + v.push_back(b.second); |
| 26 | + sort(v.begin(),v.end(),greater<int>()); |
| 27 | + return {v[0],v[1]}; |
| 28 | +} |
| 29 | + |
| 30 | +void build(int node,int l,int r) { |
| 31 | + if(l == r) { |
| 32 | + tree[node] = {in[l],-1}; |
| 33 | + return; |
| 34 | + } |
| 35 | + int mid = (l+r)/2; |
| 36 | + build(node*2,l,mid); |
| 37 | + build(node*2+1,mid+1,r); |
| 38 | + tree[node] = cmp(tree[node*2],tree[node*2+1]); |
| 39 | +} |
| 40 | + |
| 41 | +void update(int node,int l,int r,int i,int val) { |
| 42 | + if(l>i || r<i)return; |
| 43 | + if(l == r && l == i) { |
| 44 | + tree[node] = {val,-1}; |
| 45 | + return; |
| 46 | + } |
| 47 | + int mid = (l+r)/2; |
| 48 | + update(node*2,l,mid,i,val); |
| 49 | + update(node*2+1,mid+1,r,i,val); |
| 50 | + tree[node] = cmp(tree[node*2],tree[node*2+1]); |
| 51 | +} |
| 52 | + |
| 53 | +pair<int,int>query(int node,int l,int r,int i,int j) { |
| 54 | + if(l>j || r<i)return {-1,-1}; |
| 55 | + if(l >= i && r <=j)return tree[node]; |
| 56 | + int mid = (l+r)/2; |
| 57 | + return cmp(query(node>>1,l,mid,i,j),query(node>>1|1,mid+1,r,i,j)); |
| 58 | +} |
| 59 | + |
| 60 | +int main() { |
| 61 | + int test=4,t,i,n,q,l,r; |
| 62 | + char type; |
| 63 | + cin >> n; |
| 64 | + for(i=1; i<=n; i++)cin >> in[i]; |
| 65 | + build(1,1,n); |
| 66 | + cin >> q; |
| 67 | + for(i=0; i<q; i++) { |
| 68 | + cin >> type >> l >> r; |
| 69 | + if(type == 'Q') { |
| 70 | + pair<int,int>get = query(1,1,n,l,r); |
| 71 | + cout << (get.first+get.second) << "\n"; |
| 72 | + } else update(1,1,n,l,r); |
| 73 | + } |
| 74 | + |
| 75 | + return 0; |
| 76 | +} |
| 77 | + |
| 78 | +``` |
| 79 | +</details> |
| 80 | +
|
| 81 | +
|
0 commit comments