hdu(1166)敌兵布阵
2014-03-13 14:14
323 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1166
这题可以用树状数组来做,也可以用线段树来做.
树状数组:
线段树:
这题可以用树状数组来做,也可以用线段树来做.
树状数组:
#include<stdio.h> #include<string.h> #include<algorithm> #define MAX 50005 using namespace std; char str[4][6] ={"Query","Add","Sub","End"}; char st[6]; int a[MAX],c[MAX]; int t,n; int lowbit(int x){ return x&(-x); } void add(int i,int val){ while(i <= n){ c[i] +=val; i += lowbit(i); } } int sum(int i){ int s = 0; while(i > 0){ s += c[i]; i -= lowbit(i); } return s; } int main(){ int i; scanf("%d",&t); int cont = 1; while(t--){ memset(a, 0,sizeof(a)); memset(c, 0,sizeof(c)); scanf("%d",&n); for(i =1;i <=n;i++){ scanf("%d",a+i); for(int j=i;j>i-lowbit(i);j--) c[i] += a[j]; } //for(i = 1;i<= n;i++) // printf("%d ",c[i]); printf("Case%d:\n",cont++); while(scanf("%s",st)){ if ( !strcmp(st,str[3])) break; int u,v; scanf("%d%d",&u,&v); if ( !strcmp(st,str[1])) add(u,v); if ( !strcmp(st,str[2])) add(u,-v); if ( !strcmp(st,str[0])) printf("%d\n",sum(v)-sum(u-1)); } } return 0; }
线段树:
#include <iostream> #include <cstdio> #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 using namespace std; const int maxn = 50005; int tree[maxn<<2]; char str[10]; void PushUp(int rt){ tree[rt] = tree[rt<<1]+tree[rt<<1|1]; } void build(int l, int r, int rt){ if (l == r){ scanf("%d",&tree[rt]); return; } int m = (l + r) >> 1; build (lson); build (rson); PushUp(rt); } void update(int id ,int p, int l, int r, int rt){ if (l == r){ tree[rt] += p; return ; } int m = (l + r) >> 1; if (id <= m) update(id,p,lson); else update(id,p,rson); PushUp(rt); } 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; int ret = 0; if(L <= m) ret += query(L, R, lson); if(R > m) ret += query(L, R, rson); return ret; } int main(){ int t; scanf("%d",&t); for(int cas = 1;cas <= t;cas++){ int n; scanf("%d",&n); build(1,n,1); printf("Case %d:\n",cas); int a,b; while(scanf("%s",str),str[0] != 'E'){ scanf("%d%d",&a,&b); if(str[0] == 'Q') printf("%d\n",query(a,b,1,n,1)); else if(str[0] == 'A') update(a,b,1,n,1); else update(a,-b,1,n,1); // for(int i = 1;i < n*4;i++) // printf("%d ",tree[i]); // printf("\n"); } } return 0; }
相关文章推荐
- HDU-1166 敌兵布阵 简单树状数组
- hdu 1166 敌兵布阵
- HDU 1166 敌兵布阵【线段树 单点更新】
- HDU - 1166 敌兵布阵 解题报告(树状数组魔板题)
- HDU 1166 敌兵布阵
- hdu 1166 敌兵布阵
- HDU 1166 敌兵布阵 -- 线段树
- HDU 1166敌兵布阵
- hdu 1166 敌兵布阵
- HDU 1166 敌兵布阵 Segment Tree题解
- HDU【1166】敌兵布阵
- HDU 1166 敌兵布阵(树状数组 or 线段树 单点修改 区间求和)
- HDU 1166 敌兵布阵
- HDU 1166 敌兵布阵 题解与分析 (普通线段树,ZKW线段树实现)
- HDU 1166 敌兵布阵(线段树区间求和)
- hdu 1166 敌兵布阵(线段树)
- hdu 1166 敌兵布阵(线段树单点更新)
- hdu 1166 敌兵布阵
- HDU 1166 敌兵布阵
- (树状数组) hdu 1166 敌兵布阵