/* ***********************************************
Author :xryz
Email :523689985@qq.com
Created Time :4-22 20:46:48
File Name :hdu排兵布阵.cpp
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int c[50000+5];
int lowbit (int x)
{
return x&-x;
}
int sum(int x)
{
int ret=0;
while(x>0)
{
ret+=c[x];
x-=lowbit(x);
}
return ret;
}
void add(int x,int d,int n)
{
while(x<=n)
{
c[x]+=d;
x+=lowbit(x);
}
}
int main()
{
int t,i,n,j,m,tmp1,tmp2;
char s[24];
scanf("%d",&t);
for(int ii=1;ii<=t;ii++)
{
scanf("%d",&n);
memset(c,0,sizeof(c));
for(i=1;i<=n;i++)
{
scanf("%d",&m);
add(i,m,n);
}
printf("Case %d:
",ii);
while(~scanf("%s",s))
{
if(strcmp(s,"End")==0) break;
if(s[0]=='A')
{
scanf("%d%d",&i,&j);
add(i,j,n);
}
else if(s[0]=='Q')
{
scanf("%d%d",&i,&j);
if(i>1)
{i--;
tmp1=sum(i);
}
else tmp1=0;
tmp2=sum(j);
printf("%d
",tmp2-tmp1);
}
else if(s[0]=='S')
{
scanf("%d%d",&i,&j);
add(i,-j,n);
}
}
}
return 0;
}
线段树
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct node
{
int left,right,sum;
} tree[200000+5];
int a[50000+5];
void make(int id,int l,int r)//建树
{
tree[id].left=l;
tree[id].right=r;
if(l==r)
{
tree[id].sum=a[l];
}
else
{
int mid=(l+r)/2;
make(id*2,l,mid);
make(id*2+1,mid+1,r);
tree[id].sum=tree[id*2].sum+tree[id*2+1].sum;
}
}
void add(int id,int pos,int d)//单点更新
{
tree[id].sum+=d;
if(tree[id].left==tree[id].right) return ;
int mid=(tree[id].left+tree[id].right)/2;
if(pos>mid) add(id*2+1,pos,d);
else add(id*2,pos,d);
}
int query(int l,int r,int id)//查询
{
if(tree[id].left==l&&tree[id].right==r)
return tree[id].sum;
else
{
int mid=(tree[id].left+tree[id].right)/2;
if(r<=mid) return query(l,r,id*2);
else if(l>mid) return query(l,r,id*2+1);
else
return query(l,mid,id*2)+query(mid+1,r,id*2+1);
}
}
int main()
{
int T,i,n,j,l,r;
char s[10];
scanf("%d",&T);
for(int k=1; k<=T; k++)
{
scanf("%d",&n);
a[0]=0;
for(i=1; i<=n; i++) scanf("%d",&a[i]);
make(1,1,n);
printf("Case %d:
",k);
while(~scanf("%s",s))
{
if(strcmp(s,"End")==0) break;
else if(strcmp(s,"Add")==0)
{
scanf("%d%d",&i,&j);
add(1,i,j);
}
else if(strcmp(s,"Sub")==0)
{
scanf("%d%d",&i,&j);
add(1,i,-j);
}
else
{
scanf("%d%d",&i,&j);
int ans=query(i,j,1);
printf("%d
",ans);
}
}
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/