第一道线段树区间更新题目!
本题要求更新某一个区间的数值,最后求出所有数的总值输出!
是一道赤裸裸的线段树更新区间值得题目!
#include<stdio.h>
#define N 100100struct node
{
int x,y,shu;
int sum;
}aa[N*3];
void CreatTree(int t,int x,int y)
{
aa[t].x=x;
aa[t].y=y;
aa[t].shu=1;
if(x==y)
{
aa[t].sum=1;
return ;
}
int temp=2*t;
int mid=(x+y)/2;
CreatTree(temp,x,mid);
CreatTree(temp+1,mid+1,y);
aa[t].sum=aa[temp].sum+aa[temp+1].sum;
}
void UpdateTree(int t,int x,int y,int shu)
{
if(x==aa[t].x&&y==aa[t].y)
{
aa[t].sum=(y-x+1)*shu;
aa[t].shu=shu;
return;
}
int mid=(aa[t].x+aa[t].y)/2;
int temp=2*t;
if(aa[t].shu!=0)
{
aa[temp].shu=aa[t].shu;
aa[temp+1].shu=aa[t].shu;
aa[temp].sum=(aa[temp].y-aa[temp].x+1)*aa[temp].shu;
aa[temp+1].sum=(aa[temp+1].y-aa[temp+1].x+1)*aa[temp+1].shu;
}
if(y<=aa[temp].y)
UpdateTree(temp,x,y,shu);
else if(x>=aa[temp+1].x)
UpdateTree(temp+1,x,y,shu);
else
{
UpdateTree(temp,x,mid,shu);
UpdateTree(temp+1,mid+1,y,shu);
}
if(aa[temp].shu==aa[temp+1].shu)
aa[t].shu=aa[temp].shu;
else
aa[t].shu=0;
aa[t].sum=aa[temp].sum+aa[temp+1].sum;
return;
}
int main()
{
int T,n,t,k,x,y,r;
r=1;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
CreatTree(1,1,n);
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&x,&y,&k);
UpdateTree(1,x,y,k);
}
printf("Case %d: ",r++);
printf("The total value of the hook is %d.\n",aa[1].sum);
}
return 0;
}
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1698