线段树模板题,没啥好说的.....注意输出是case之间空一行就行.........之前一直没注意,一直wa
代码如下:
#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<iostream> #include<algorithm> #include<vector> #include<map> #include<queue> #include<stack> #include<string> #include<map> #include<set> using namespace std; #define LL long long const int maxn = 200000 + 10; const int INF = 1000000000; int A[maxn], sumv[2 * maxn]; int query(int o, int L, int R, int ql, int qr) { int M = (L + R) >> 1, ans = 0; if(L >= ql && R <= qr) return sumv[o]; if(ql <= M) ans += query(2 * o, L, M, ql, qr); if(qr > M) ans += query(2 * o + 1, M + 1, R, ql, qr); return ans; } void update(int o, int L, int R, int p, int v) { int M = (L + R) >> 1; if(L == R) sumv[o] = v; else { if(p <= M) update(o * 2, L, M, p, v); else update(o * 2 + 1, M + 1, R, p, v); sumv[o] = sumv[2 * o] + sumv[2 * o + 1]; } } void buildTree(int o, int L, int R) { int M = (L + R) >> 1; if(L == R) sumv[o] = A[L]; else { buildTree(2 * o, L, M); buildTree(2 * o + 1, M + 1, R); sumv[o] = sumv[2 * o] + sumv[2 * o + 1]; } } int main() { //freopen("input.txt", "r", stdin); int n, kase = 0; while(scanf("%d", &n) == 1 && n) { if(kase) printf("\n"); for(int i = 1; i <= n; i++) scanf("%d", &A[i]); buildTree(1, 1, n); //printf("%d", sumv[1]); printf("Case %d:\n", ++kase); char cmd[4]; while(scanf("%s", cmd) && cmd[0] != 'E') { int u, v; scanf("%d%d", &u, &v); if(cmd[0] == 'M') { printf("%d\n", query(1 ,1, n, u, v)); } else { update(1, 1, n, u, v); } // printf("%d %d", u, v); } } return 0; }
原文地址:http://blog.csdn.net/u014664226/article/details/46007891