hdu 1166敌兵布阵(线段树入门题)
思路:这两天在学线段树,这个题直接手敲一下线段树就行了,都没有用上懒人标记。入门题
cin,cout会超时,记得加std::ios::sync_with_stdio(false);
#include<string> #include<iostream> #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 using namespace std; const int maxn = 5e4 + 5; int add[maxn << 2]; int tree[maxn << 2]; void PushDown(int rt) { if (add[rt]){ add[rt << 1] += add[rt]; add[rt << 1 | 1] += add[rt]; tree[rt << 1] += add[rt]; tree[rt << 1 | 1] += add[rt]; add[rt] = 0; } } void build(int l, int r, int rt) { if (l == r){ cin >> tree[rt]; return; } int m = (l + r) >> 1; build(lson); build(rson); tree[rt] = tree[rt << 1] + tree[rt << 1 | 1]; } void update(int x, int ans, int l, int r, int rt) { if (l == r){ tree[rt] += ans; return; } int m = (l + r) >> 1; if (x <= m)update(x, ans, lson); else update(x, ans, rson); tree[rt] = tree[rt << 1] + tree[rt << 1 | 1]; } int query(int L, int R, int l, int r, int rt) { if (L <= l&&r <= R){ return tree[rt]; } int m = (l + r) >> 1, ans = 0; if (L <= m)ans += query(L, R, lson); if (R > m)ans += query(L, R, rson); return ans; } int main() { std::ios::sync_with_stdio(false); int t, ca = 1; cin >> t; while (t--){ int n; cin >> n; build(1, n, 1); string flag; int i, j; cout << "Case " << ca++ << ":" << endl; while (cin >> flag, flag != "End"){ cin >> i >> j; if (flag == "Add"){ update(i, j, 1, n, 1); } else if (flag == "Sub"){ update(i, -1 * j, 1, n, 1); } else if (flag == "Query"){ cout << query(i, j, 1, n, 1) << endl; } } } return 0; }