一、题目
二、分析
区间更新,用线段树的懒标记即可。需要注意的时,由于是在最后才查询的,没有必要每次更新都对$sum$进行求和。还有一点就是初始化的问题,一定记得线段树上每个点都需要初始化。
三、AC代码
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 #include <vector> 6 #include <cmath> 7 8 using namespace std; 9 #define ll long long 10 #define lson (rt<<1) 11 #define rson (rt<<1|1) 12 #define Min(a,b) ((a)>(b)?(b):(a)) 13 #define Max(a,b) ((a)>(b)?(a):(b)) 14 const int MAXN = 5e4; 15 struct Node 16 { 17 int lazy, sum; 18 }segTree[MAXN<<2]; 19 20 void Push_down(int rt) 21 { 22 if(segTree[rt].lazy > 0) { 23 segTree[lson].lazy = Max(segTree[rt].lazy, segTree[lson].lazy); 24 segTree[rson].lazy = Max(segTree[rt].lazy, segTree[rson].lazy); 25 } 26 } 27 28 void Push_up(int rt) 29 { 30 segTree[rt].sum = segTree[lson].sum + segTree[rson].sum; 31 } 32 33 void Build(int rt, int l, int r) 34 { 35 segTree[rt].lazy = segTree[rt].sum = 0; 36 if(l == r) { 37 return; 38 } 39 int mid = (l + r) >> 1; 40 Build(lson, l, mid); 41 Build(rson, mid + 1, r); 42 Push_up(rt); 43 } 44 45 void Update(int rt, int l, int r, int L, int R, int p) 46 { 47 if(L <= l && r <= R) { 48 segTree[rt].lazy = Max(segTree[rt].lazy, p); 49 return; 50 } 51 int mid = (l + r) >> 1; 52 if(L <= mid) 53 Update(lson, l, mid, L, R, p); 54 if(R > mid) 55 Update(rson, mid + 1, r, L, R, p); 56 } 57 58 void Query(int rt, int l, int r) 59 { 60 if(l == r) { 61 segTree[rt].sum = Max(segTree[rt].sum, segTree[rt].lazy); 62 //cout << l << " : " << segTree[rt].sum << " lazy: " << segTree[rt].lazy << " / " << endl; 63 return; 64 } 65 Push_down(rt); //关键,不是叶子的时候,懒标记一定要下传 66 int mid = (l + r) >> 1; 67 Query(lson, l, mid); 68 Query(rson, mid + 1, r); 69 Push_up(rt); //总和 70 } 71 72 int main() 73 { 74 int N, M; 75 //freopen("input.txt", "r", stdin); 76 while(scanf("%d%d", &N, &M) != EOF) { 77 int S, T, P; 78 //memset(segTree, 0, sizeof(segTree)); 79 Build(1, 1, N); 80 for(int i = 0; i < M; i++) { 81 scanf("%d%d%d", &S, &T, &P); 82 //++后相当于是以区间来当点用 83 S++; 84 Update(1, 1, N, S, T, P); 85 } 86 Query(1, 1, N); 87 printf("%d ", segTree[1].sum); 88 89 } 90 return 0; 91 }