题目传送门:HDU 1166 - 敌兵布阵
单点更新,区间求和
线段树入门题 也是树状数组的入门题
线段树AC Code:
//AcerGY
//#pragma comment (linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#define ll long long
#define BUG puts("BUG!")
#define ci(val) scanf("%d",&val)
#define pi(val) printf("%d\n",val)
#define clr(a,val) memset(a,val,sizeof(a))
#define lowbit(x) ((x)&(-x))
#define inf 0x3f3f3f3f
#define inf64 1LL<<60
#define PI acos(-1.0)
#define eps 1e-8
//Game Theory
#define P "First"
#define N "Second"
#define maxn 50010
#define mod 10009
using namespace std;
void readfile(char s[])
{
#ifndef ONLINE_JUDGE
freopen(s,"r",stdin);
#endif
}
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
int seg[maxn<<2];
void push(int root)
{
seg[root] = seg[root<<1]+seg[root<<1|1];
}
void build(int l,int r,int root)
{
if(l==r)
{
scanf("%d",&seg[root]);
return;
}
int mid = (l+r)>>1;
build(lson);build(rson);
push(root);
}
void update(int pos,int val,int l,int r,int root)
{
if(l==r)
{
seg[root] += val;
return;
}
int mid = (l+r)>>1;
if(pos<=mid)
update(pos,val,lson);
else
update(pos,val,rson);
push(root);
}
int query(int L,int R,int l,int r,int root)
{
int sum = 0;
if(L<=l && r<=R)
return seg[root];
int mid = (l+r)>>1;
if(L<=mid)
sum += query(L,R,lson);
if(R>mid)
sum += query(L,R,rson);
return sum;
}
int main()
{
ios::sync_with_stdio(0);
readfile("1166.txt");
int T , cas = 1 , pos ,val;
scanf("%d",&T);
while(T--)
{
printf("Case %d:\n",cas++);
int n;scanf("%d",&n);
build(1,n,1);
char op[10];
while(~scanf("%s",op))
{
if(op[0]=='E')
break;
scanf("%d%d",&pos,&val);
if(op[0]=='A')
update(pos,val,1,n,1);
else if(op[0]=='S')
update(pos,-val,1,n,1);
else
printf("%d\n",query(pos,val,1,n,1));
}
}
return 0;
}
树状数组AC Code:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
using namespace std;
const int maxn = 50010;
int n,a[maxn],tree[maxn];
int lowbit(int x)
{
return x&(-x);
}
void update(int i,int val)
{
while(i<=n)
{
tree[i] += val;
i += lowbit(i);
}
}
int query(int i)
{
int sum = 0;
while(i>0)
{
sum += tree[i];
i -= lowbit(i);
}
return sum;
}
int main()
{
int t , cas = 1;
scanf("%d",&t);
string op;
int u , v;
while(t--)
{
memset(tree,0,sizeof(tree));
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
update(i,a[i]);
}
printf("Case %d:\n",cas++);
while(cin>>op && op[0]!='E')
{
if(op[0]=='A')
{
scanf("%d%d",&u,&v);
update(u,v);
}
else if(op[0]=='S')
{
scanf("%d%d",&u,&v);
update(u,-v);
}
else if(op[0]=='Q')
{
scanf("%d%d",&u,&v);
printf("%d\n",query(v)-query(u-1));
}
}
}
return 0;
}