Tidy非常苦恼,这么算他真的会崩溃的,聪明的读者,你能写个程序帮他完毕这项工作吗?只是假设你的程序效率不够高的话。Tidy还是会受到Derek的责骂的.
1 10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 End
Case 1: 6 33 59
线段树。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
struct node
{
int left,right,val;
}c[50000*3];
void build_tree(int l,int r,int root)//建树
{
c[root].left=l;
c[root].right=r;
if(l==r)
{
scanf("%d",&c[root].val);
return ;
}
int mid=(c[root].left+c[root].right)/2;
build_tree(l,mid,root*2);
build_tree(mid+1,r,root*2+1);
c[root].val=c[root*2].val+c[root*2+1].val;
}
void search_tree(int l,int r,int root,int &sum)//计算和
{
if(c[root].left==l&&c[root].right==r)
{
sum=c[root].val;
return ;
}
int mid=(c[root].left+c[root].right)/2;
if(mid<l)
search_tree(l,r,root*2+1,sum);
else if(mid>=r)
search_tree(l,r,root*2,sum);
else
{
int sum1;
search_tree(l,mid,root*2,sum);
search_tree(mid+1,r,root*2+1,sum1);
sum=sum1+sum;
}
}
void update_tree(int pos,int root,int x)//更新
{
if(c[root].left==c[root].right&&c[root].left==pos)
{
c[root].val+=x;
return ;
}
int mid=(c[root].left+c[root].right)/2;
if(mid<pos)
update_tree(pos,root*2+1,x);
else
update_tree(pos,root*2,x);
c[root].val=c[root*2].val+c[root*2+1].val;
}
int main()
{
int n,t;
scanf("%d",&t);
for(int ncase=1;ncase<=t;ncase++)
{
scanf("%d",&n);
memset(&c,0,sizeof(&c));
build_tree(1,n,1);
getchar();
printf("Case %d:\n",ncase);
while(1)
{
char ch[10];
scanf("%s",ch);
if(ch[0]=='Q')
{
int a,b,sum;
scanf("%d %d",&a,&b);
getchar();
if(a<b)
search_tree(a,b,1,sum);
else
search_tree(b,a,1,sum);
printf("%d\n",sum);
}
else if(ch[0]=='A')
{
int a,b;
scanf("%d %d",&a,&b);
getchar();
update_tree(a,1,b);
}
else if(ch[0]=='S')
{
int a,b;
scanf("%d %d",&a,&b);
getchar();
update_tree(a,1,-b);
}
else
break;
}
}
return 0;
}原文:http://www.cnblogs.com/cynchanpin/p/7343937.html