样例输入
10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 End
样例输出
6 33 59
采用标准模板即可。注意线段树的节点个数一般为其范围的4倍。
1 #include<bits/stdc++.h> 2 using namespace std; 3 vector<int> s(50000 * 4); 4 int n; 5 void modify(int p, int l, int r, int x, int y) { 6 s[p] += y; 7 if (l == r) { //到达叶子节点 8 return; 9 } 10 int mid = (l + r) / 2; 11 if (x <= mid) { 12 modify(p * 2, l, mid, x, y); 13 } else { 14 modify(p * 2 + 1, mid + 1, r, x, y); 15 } 16 } 17 int query(int p, int l, int r, int x, int y) { 18 if (x <= l && y >= r) { 19 return s[p]; 20 } 21 int mid = (l + r) / 2, res = 0; 22 if (x <= mid) { 23 res += query(p * 2, l, mid, x, y); 24 } 25 if (y > mid) { 26 res += query(p * 2 + 1, mid + 1, r, x, y); 27 } 28 return res; 29 } 30 31 int main() { 32 cin >> n; 33 int temp; 34 for (int i = 1; i <= n; ++i) { 35 cin >> temp; 36 modify(1, 1, n, i, temp); 37 } 38 string str; 39 int i, j; 40 while (cin >> str && str != "End") { 41 cin >> i >> j; 42 if (str == "Query") { 43 cout << query(1, 1, n, i, j) << endl; 44 }else if (str == "Add") { 45 modify(1, 1, n, i, j); 46 }else { 47 modify(1, 1, n, i, -j); 48 } 49 } 50 }
标签:10,斑点,res,线段,mid,int,str,Query,计蒜客 From: https://www.cnblogs.com/coderhrz/p/18468329