线段树区间合并模板题。第一次写区间合并,花了我好久,按照惯例,我依旧是奔着1A去的。结果提交RE。各种修改,各种反思,就是找不到什么地方越界了。
最后我想了许久,突然想起来我测试数据的时候直接复制粘贴题目给的数据的时候,数据后面有一个空格……我修改了一下,用字符串读入,A了!
这也行?!测试数据后面加空格?后面还是读取的字符!
#include<stdio.h>
#include<string.h>
#define N 100100
struct node
{
int x,y;
int ll,rl;
int lt,rt;
int max;
}a[N*3];
int b[N];
int Max(int x,int y)
{
if(x>y)
return x;
else
return y;
}
int Min(int x,int y)
{
if(x<y)
return x;
else
return y;
}
void CreatTree(int t,int x,int y)
{
a[t].x=x;
a[t].y=y;
if(x==y)
{
a[t].max=1;
a[t].lt=a[t].rt=b[x];
a[t].ll=a[t].rl=1;
return ;
}
int temp=t*2;
int mid=(x+y)/2;
CreatTree(temp,x,mid);
CreatTree(temp+1,mid+1,y);
if(a[temp].rt<a[temp+1].lt)
a[t].max=Max(a[temp].rl+a[temp+1].ll,Max(a[temp].max,a[temp+1].max));
else
a[t].max=Max(a[temp].max,a[temp+1].max);
if(a[temp].ll==a[temp].y-a[temp].x+1&&a[temp].rt<a[temp+1].lt)
a[t].ll=a[temp].ll+a[temp+1].ll;
else
a[t].ll=a[temp].ll;
a[t].lt=a[temp].lt;
if(a[temp+1].rl==a[temp+1].y-a[temp+1].x+1&&a[temp].rt<a[temp+1].lt)
a[t].rl=a[temp].rl+a[temp+1].rl;
else
a[t].rl=a[temp+1].rl;
a[t].rt=a[temp+1].rt;
return ;
}
void InsertTree(int t,int x,int k)
{
if(a[t].x==a[t].y)
{
a[t].lt=a[t].rt=k;
return ;
}
int temp=t*2;
int mid=(a[t].x+a[t].y)/2;
if(x<=mid)
InsertTree(temp,x,k);
else
InsertTree(temp+1,x,k);
if(a[temp].rt<a[temp+1].lt)
a[t].max=Max(a[temp].rl+a[temp+1].ll,Max(a[temp].max,a[temp+1].max));
else
a[t].max=Max(a[temp].max,a[temp+1].max);
if(a[temp].ll==a[temp].y-a[temp].x+1&&a[temp].rt<a[temp+1].lt)
a[t].ll=a[temp].ll+a[temp+1].ll;
else
a[t].ll=a[temp].ll;
a[t].lt=a[temp].lt;
if(a[temp+1].rl==a[temp+1].y-a[temp+1].x+1&&a[temp].rt<a[temp+1].lt)
a[t].rl=a[temp].rl+a[temp+1].rl;
else
a[t].rl=a[temp+1].rl;
a[t].rt=a[temp+1].rt;
return ;
}
int FindTree(int t,int x,int y)
{
int max=0;
if(a[t].x==x&&a[t].y==y)
return a[t].max;
int temp=t*2;
int mid=(a[t].x+a[t].y)/2;
if(y<=mid)
max=FindTree(temp,x,y);
else if(x>mid)
max=FindTree(temp+1,x,y);
else
{
int s,t;
s=FindTree(temp,x,mid);
t=FindTree(temp+1,mid+1,y);
int lsum,rsum;
lsum=Min(a[temp].rl,mid-x+1);
rsum=Min(a[temp+1].ll,y-mid);
if(a[temp].rt<a[temp+1].lt)
max=Max(lsum+rsum,Max(s,t));
else
max=Max(s,t);
}
return max;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,m;
scanf("%d%d",&n,&m);
int i;
for(i=1;i<=n;i++)
scanf("%d",&b[i]);
CreatTree(1,1,n);
while(m--)
{
char s[15];
int x,y;
scanf("%s%d%d",s,&x,&y);
if(s[0]=='Q')
{
x++;
y++;
printf("%d\n",FindTree(1,x,y));
}
else
{
x++;
InsertTree(1,x,y);
}
}
}
return 0;
}