首页 > 代码库 > HDU 5700 区间交(线段树)

HDU 5700 区间交(线段树)

题目链接 区间交

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 #define rep(i, a, b)    for (int i(a); i <= (b); ++i)
 6 #define dec(i, a, b)    for (int i(a); i >= (b); --i)
 7 
 8 #define lson i << 1, L, mid
 9 #define rson i << 1 | 1, mid + 1, R
10 
11 typedef long long LL;
12 
13 const int N = 200010;
14 
15 struct node{
16         int l, r;
17         friend bool operator < (const node &a, const node &b){
18             return a.l < b.l;
19         }
20 } a[N];
21 
22 int tree[N << 2];
23 int n, k, m;
24 LL sum[N], ans, x;
25 
26 void pushup(int i){ tree[i] = tree[i << 1] + tree[i << 1 | 1];  }
27 
28 
29 void update(int i, int L, int R, int x){
30         if (L == R){ ++tree[i]; return;}
31         int mid = (L + R) >> 1;
32         if (x <= mid) update(lson, x); else update(rson, x);
33         pushup(i);
34 }
35 
36 int query(int i, int L, int R, int x){
37         if (L == R) return L;
38         int mid = (L + R) >> 1;
39         if (tree[i << 1 | 1] >= x) return query(rson, x);
40         else return query(lson, x - tree[i << 1 | 1]);
41 }
42 
43 int main(){
44 
45         while (~scanf("%d%d%d", &n, &k, &m)){
46             sum[0] = 0; ans = 0;
47             memset(tree, 0, sizeof tree);
48             rep(i, 1, n){
49                     scanf("%lld", &x);
50                     sum[i] = sum[i - 1] + x;
51             }
52 
53             rep(i, 1, m) scanf("%d%d", &a[i].l, &a[i].r);
54             sort(a + 1, a + m + 1);
55             dec(i, k, 1) update(1, 1, n, a[i].r);
56             a[m + 1].r = 1;
57             rep(i, k, m){
58                     int pos = query(1, 1, n, k);
59                     if (pos >= a[i].l) ans = max(ans, sum[pos] - sum[a[i].l - 1]);
60                     update(1, 1, n, a[i + 1].r);
61             }    
62 
63             printf("%lld\n", ans);
64         }
65         return 0;
66 }

 

HDU 5700 区间交(线段树)