HDU -1166 线段树
Posted caibingxu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU -1166 线段树相关的知识,希望对你有一定的参考价值。
#include <algorithm> #include <iostream> #include<sstream> #include<cstring> #include<string> #include<cstdio> #include<cctype> #include<vector> #include<deque> #include<map> #include<set> #define M 50000 #define inf 0x3f3f3f3f typedef long long ll; using namespace std; struct Data { int left, right, sum, lazy; }tree[M*4]; int n; int sum, lazy; int x, y; string str; void built(int l,int r,int k) { tree[k].left = l, tree[k].right = r; if (l == r) { scanf("%d", &tree[k].sum); return; } int mid = (l + r) / 2; built(l, mid,k*2); built(mid + 1, r, k * 2 + 1); tree[k].sum = tree[k * 2].sum + tree[k * 2 + 1].sum; } void down(int k) { lazy = tree[k].lazy; tree[k].lazy = 0; tree[k * 2].lazy += lazy; tree[k * 2 + 1].lazy += lazy; tree[k * 2].sum += (tree[k * 2].right - tree[k * 2].left + 1) * lazy; tree[k * 2 + 1].sum += (tree[k * 2 + 1].right - tree[k * 2 + 1].left + 1) * lazy; } void search(int k) { if (tree[k].left >=x && tree[k].right <=y) { sum += tree[k].sum; return; } if (tree[k].lazy)down(k); int mid = (tree[k].left + tree[k].right) / 2; if (x <= mid)search(k * 2); if (y > mid)search(k * 2 + 1); } void change_inv(int k) { if (tree[k].left == tree[k].right) { //tree[k].lazy += add; tree[k].sum += y; return; } if (tree[k].lazy)down(k); int mid = (tree[k].left + tree[k].right) / 2; if (x <= mid)change_inv(k * 2); else change_inv(k * 2 + 1); tree[k].sum = tree[k * 2].sum + tree[k * 2 + 1].sum; } int main() { int T; cin >> T; for (int Case = 1; Case <= T; Case++) { scanf("%d", &n); built(1, n, 1); printf("Case %d:\n", Case); while (true){ cin >> str; if (str == "End")break; scanf("%d%d", &x, &y); if (str == "Add") { change_inv(1); } else if (str == "Sub") { y *= -1; change_inv(1); } else if (str == "Query") { sum = 0; search(1); printf("%d\n", sum); } } } return 0; }
以上是关于HDU -1166 线段树的主要内容,如果未能解决你的问题,请参考以下文章