首先介绍什么是线段树:
线段树是擅长处理区间一种数据结构。主要求区间的和,最大值,最小值,区间更新~~~~~
下面直接看题
题目链接:https://vjudge.net/contest/217846#problem/D
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 EndSample Output
Case 1: 6 33 59
这道题碰到了前所未有的错误 Memory Limit Exceeded ,百度了一下,说什么内存超了,在我这里不是这个意思,就是当我输入End指令时,我的代码不会结束,所有就错了
在题目中有介绍我是怎么错的
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<set>
typedef long long ll;
using namespace std;
#define INF 1e9+7
#define M 50005
#define Lson l,m,rt<<1
#define Rson m+1,r,rt<<1|1
int sum[M<<2];
inline void Pushup(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void Build(int l,int r,int rt)
{
if(l==r)
{
scanf("%d",&sum[rt]);
return ;
}
int m=(l+r)>>1;
Build(Lson);
Build(Rson);
Pushup(rt);
}
void Updata(int l,int r,int rt,int p,int add)
{
if(l==r)
{
sum[rt]+=add;
return ;
}
int m=(l+r)>>1;
if(m<p)
Updata(Rson,p,add);
else
Updata(Lson,p,add);
Pushup(rt);
}
int Query(int l,int r,int rt,int L,int R)
{
if(L<=l&&r<=R)
return sum[rt];
int m=(l+r)>>1;
int ans=0;
if(L<=m)
ans+=Query(Lson,L,R);
if(R>m)
ans+=Query(Rson,L,R);
return ans;
}
int main()
{
int t;
char a[10];
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
printf("Case %d:\n",i);
int n,c,d;
scanf("%d",&n);
Build(1,n,1);
getchar();
while(scanf("%s",a)!=EOF&&a[0]!=‘E‘)//就是这个地方,如果把下面输入的c,d也在这里输入,当碰到End时,就不会退出来,原因我也不知道
{
scanf("%d%d",&c,&d);
if(a[0]==‘E‘)
break;
else if(a[0]==‘A‘)
Updata(1,n,1,c,d);
else if(a[0]==‘S‘)
Updata(1,n,1,c,-d);
else if(a[0]==‘Q‘)
printf("%d\n",Query(1,n,1,c,d));
}
}
return 0;
}
原文:https://www.cnblogs.com/caijiaming/p/9291294.html