HDU1698Just a Hook(线段树 + 区间修改 + 求和)
分析:1-N区间内初始都是1,然后q个询问,每个询问修改区间【a,b】的值为2或3或者1,统计最后整个区间的和
本来想刷刷手速,结果还是写了一个小时,第一个超时,因为输出的时候去每个区间查找了,直接输出tree[1].value就可以了 =_=
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstdio> 5 using namespace std; 6 const int Max = 100000; 7 int hook[Max + 10]; 8 struct node 9 { 10 int l,r; 11 int value; 12 int tag; 13 }; 14 node tree[3 * Max]; 15 void buildTree(int left, int right, int k) 16 { 17 tree[k].l = left; 18 tree[k].r = right; 19 tree[k].tag = -1; 20 if(left == right) 21 { 22 tree[k].value = 1; 23 return; 24 } 25 int mid = (left + right ) / 2; 26 buildTree(left, mid, k * 2); 27 buildTree(mid + 1, right, k * 2 + 1); 28 tree[k].value = tree[k * 2].value + tree[k * 2 + 1].value; 29 } 30 void upDate(int left, int right, int k, int newp) 31 { 32 if(tree[k].l ==left && tree[k].r == right) 33 { 34 tree[k].value = (right - left + 1) * newp; 35 tree[k].tag = newp; 36 return; 37 } 38 if(tree[k].tag != -1) 39 { 40 tree[k * 2].tag = tree[k * 2 + 1].tag = tree[k].tag; 41 tree[k * 2].value = (tree[k * 2].r - tree[k * 2].l + 1) * tree[k].tag; 42 tree[k * 2 + 1].value = (tree[k * 2 + 1].r - tree[k * 2 + 1].l + 1) * tree[k].tag; 43 tree[k].tag = -1; 44 } 45 int mid = (tree[k].l + tree[k].r) / 2; 46 if(right <= mid) 47 { 48 upDate(left, right, k * 2, newp); 49 } 50 else if(mid < left) 51 { 52 upDate(left, right, k * 2 + 1, newp); 53 } 54 else 55 { 56 upDate(left, mid, k * 2, newp); 57 upDate(mid + 1, right, k * 2 + 1, newp); 58 } 59 tree[k].value = tree[k * 2].value + tree[k * 2 + 1].value; 60 } 61 int Search(int k) 62 { 63 if(tree[k].tag != -1) 64 { 65 tree[k * 2].tag = tree[k * 2 + 1].tag = tree[k].tag; 66 tree[k * 2].value = (tree[k * 2].r - tree[k * 2].l + 1) * tree[k].tag; 67 tree[k * 2 + 1].value = (tree[k * 2 + 1].r - tree[k * 2 + 1].l + 1) * tree[k].tag; 68 tree[k].tag = -1; 69 } 70 if(tree[k].l == tree[k].r) 71 return tree[k].value; 72 return Search(k * 2) + Search(k * 2 + 1); 73 } 74 int main() 75 { 76 int test,n; 77 scanf("%d", &test); 78 for(int t = 1; t <= test; t++) 79 { 80 int q,a,b,newp; 81 scanf("%d", &n); 82 buildTree(1, n, 1); 83 scanf("%d", &q); 84 for(int i = 1; i <= q; i++) 85 { 86 scanf("%d%d%d", &a, &b, &newp); 87 upDate(a, b, 1, newp); 88 } 89 printf("Case %d: The total value of the hook is %d.\n", t, tree[1].value); 90 } 91 return 0; 92 }