hdu 1166 敌兵布阵 区间和
2016-12-13 16:27
260 查看
Problem:
给n个节点,有很多命令,两种命令,一种是更新节点的值,一种是区间求和:
Solution:
利用线段树堆区间求和
note:
要关闭cin的同步,不然会超时。
给n个节点,有很多命令,两种命令,一种是更新节点的值,一种是区间求和:
Solution:
利用线段树堆区间求和
note:
要关闭cin的同步,不然会超时。
#include<cstdio> #include<iostream> #include<sstream> #include<cstdlib> #include<cmath> #include<cctype> #include<string> #include<cstring> #include<algorithm> #include<stack> #include<queue> #include<set> #include<map> #include<ctime> #include<vector> #include<fstream> #include<list> using namespace std; #define ms(s) memset(s,0,sizeof(s)) typedef unsigned long long ULL; typedef long long LL; const double PI = 3.141592653589; const int INF = 0x3fffffff; #define maxn 50000 struct node{ int l, r, sum; int mid(){ return (l+r)/2; } }; node Tree[maxn*4]; int value[maxn+10]; int flag; //初始化树,根节点是1 void init_tree(int root, int l, int r){ Tree[root].l = l; Tree[root].r = r; if(l == r) Tree[root].sum = value[l]; else{ init_tree(2*root, l, (l+r)/2); init_tree(2*root+1, (l+r)/2 + 1, r); Tree[root].sum = Tree[2*root].sum + Tree[2*root+1].sum; } } //查找和 int query_tree(int root, int l, int r){ int m = Tree[root].mid(); if(l == Tree[root].l && r == Tree[root].r) return Tree[root].sum; else{ if(l > m) return query_tree(2*root+1, l, r); else if(r <= m) return query_tree(2*root, l, r); else return query_tree(2*root, l, m) + query_tree(2*root+1, m+1, r); } } void update_tree(int root, int idx, int v){ if(Tree[root].l == Tree[root].r) Tree[root].sum += flag*v; else{ Tree[root].sum += flag*v; if(idx <= Tree[root].mid()) update_tree(2*root, idx, v); else update_tree(2*root+1, idx, v); } } int main(){ // freopen("/Users/really/Documents/code/input","r",stdin); // freopen("/Users/really/Documents/code/output","w",stdout); ios::sync_with_stdio(false); int t, n; int a, b; string s; int res; cin >> t; for(int k = 1; k <= t; ++k){ cout << "Case " << k << ":"<<endl; cin >> n; for(int i = 1; i <= n; ++i) cin >> value[i]; init_tree(1, 1, n); while(cin >> s){ if(s == "Add"){ cin >> a >> b; flag = 1; update_tree(1, a, b); } else if(s == "Sub"){ cin >> a >> b; flag = -1; update_tree(1, a, b); } else if(s == "Query"){ cin >> a >> b; res = query_tree(1, a, b); cout << res << endl; } else break; } } return 0; }
相关文章推荐
- hdu 1166 敌兵布阵(求区间的和,单节点更新)
- 【树状数组 单点修改,区间求值】hdu 1166 敌兵布阵
- HDU 1166 敌兵布阵 数据结构+树状数组+(单点更新区间求和)
- hdu 1166 敌兵布阵——(区间和)树状数组/线段树
- HDU 1166 敌兵布阵 (线段树单点更新 区间查询)
- HDU 1166 敌兵布阵(线段树:点更新,区间求和)
- 线段树 hdu 1166 敌兵布阵 单点更新区间求和
- HDU 1166 敌兵布阵 (线段树单点更新 区间查询)
- hdu 1166 敌兵布阵【线段树】单点更新,区间求和
- hdu(1166)——敌兵布阵(更新节点,区间求和)
- HDU 1166 敌兵布阵(树状数组 or 线段树 单点修改 区间求和)
- HDU 1166 敌兵布阵 (树状数组--单点更新,区间求值)
- HDU 1166 敌兵布阵(线段树:单点add,区间求和)
- HDU-1166 敌兵布阵 (线段树 入门题 点修改 区间查询)
- hdu 1166 敌兵布阵 单点更新 区间求值
- hdu1166 敌兵布阵(线段树单点更新+区间求和)
- HDU 1166 敌兵布阵 (线段树单点更新 区间查询)
- 敌兵布阵(HDU - 1166)(线段树的点更新-区间查询)
- HDU 1166 敌兵布阵(线段树单点更新区间求和)
- HDU 1166 敌兵布阵 (线段树点更新区间查询)