概述
//hdoj1166 排兵布阵 //做的第一题线段树。。。 #include <cstdio> #include <cstring> #include <iostream> using namespace std; const int MAXN = 50010; struct Node{ int sum; int left, right; }tree[MAXN * 3]; int arr[MAXN]; int nN, nCase; void build(int left, int right, int root){ tree[root].left = left; tree[root].right = right; if(left == right){ tree[root].sum = arr[left] - arr[left - 1]; return; } int mid = (left + right) >> 1; build(left, mid, root * 2); build(mid + 1, right, root * 2 + 1); tree[root].sum = tree[root * 2].sum + tree[root * 2 + 1].sum; } int search(int left, int right, int root){ if(tree[root].left == left && tree[root].right == right) return tree[root].sum; int mid = (tree[root].left + tree[root].right) >> 1; if(mid < left) return search(left, right, root * 2 + 1); else if(mid >= right) return search(left, right, root* 2); else return search(left, mid, root * 2) + search(mid + 1, right, root * 2 + 1); } void ADD(int root, int x, int y){ tree[root].sum += y; if(tree[root].left == tree[root].right ) return; int mid = (tree[root].right + tree[root].left) >> 1; if(mid >= x) ADD(root * 2, x, y); else ADD(root * 2 + 1, x, y); } int main(){ cin >> nCase; for(int i = 1; i <= nCase; i++){ cin >> nN; memset(arr, 0, sizeof(arr)); memset(tree, 0, sizeof(tree)); for(int i = 1; i <= nN; i++){ scanf("%d", &arr[i]); arr[i] += arr[i - 1]; } build(1, nN, 1); getchar(); cout << "Case " << i << ":" << endl; while(1){ char tmp[7]; int a, b; scanf("%s", tmp); if(!strcmp(tmp, "End")) break; scanf("%d %d", &a, &b); if(!strcmp(tmp, "Add")){ ADD(1, a, b); }else if(!strcmp(tmp, "Query")){ cout << search(a, b, 1) << endl; }else if(!strcmp(tmp, "Sub")){ ADD(1, a, -b); } } } return 0; }
//hdoj 1166排兵布阵 //树状数组 #include <cstdio> #include <iostream> using namespace std; const int MAXN = 50010; int arr[MAXN], arrSum[MAXN]; int nN, nCase; int lowbit(int x){ return x & (-x); } int getSum(int x){ int sum = 0; while(x > 0){ sum += arrSum[x]; x -= lowbit(x); } return sum; } void update(int x, int m, int n){ while(x <= n){ arrSum[x] += m; x += lowbit(x); } } int main(){ cin >> nCase; for(int i = 1; i <= nCase; i++){ cin >> nN; memset(arr, 0,sizeof(arr)); memset(arrSum, 0, sizeof(arrSum)); for(int j = 1; j <= nN; j++) scanf("%d", &arr[j]); for(int j = 1; j <= nN; j++) update(j, arr[j], nN); getchar(); cout << "Case " << i << ":" << endl; while(1){ char tmp[7]; int a, b; scanf("%s", tmp); if(!strcmp(tmp, "End")) break; scanf("%d %d", &a, & b); if(!strcmp(tmp, "Add")){ update(a, b, nN); }else if(!strcmp(tmp, "Query")){ cout << getSum(b) - getSum(a - 1) << endl; }else if(!strcmp(tmp, "Sub")){ update(a, -b, nN); } } } return 0; }
最后
以上就是合适可乐为你收集整理的hdoj1166_排兵布阵(线段树、树状数组)的全部内容,希望文章能够帮你解决hdoj1166_排兵布阵(线段树、树状数组)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复