您的位置:首页 > 其它

hdu1754 I Hate It (线段树)

2013-07-29 20:33 225 查看
#include<stdio.h>

#define max(a,b) a>b?a:b

#define N 200002

struct node

{

int x,y;

int max;

}aa[N*20];

int num
;

int CreatTree(int t,int x,int y)// 构建线段树

{

aa[t].x=x;

aa[t].y=y;

if(x==y)// 左右区间相同,则此节点为叶子,max 应储存对应某个学生的值

return aa[t].max=num[x];

int mid=(x+y)/2;// 当前节点所表示的区间

int a,b;

int temp=2*t;

a=CreatTree(temp,x,mid);

b=CreatTree(temp+1,mid+1,y);

return aa[t].max=max(a,b);//递归建立左右子树,并从子树中获得最大值

}

int find(int t,int x,int y)// 从节点 t 开始,查找 x和 y 之间的最大值

{

if(aa[t].x>y||aa[t].y<x)// 若此区间与t 所管理的区间无交集

return 0;

if(x<=aa[t].x&&y>=aa[t].y)// 若此区间包含t所管理的区间

{

return aa[t].max;

}

int a,b; // 若此区间与 root 所管理的区间部分相交

int temp=2*t;

a=find(temp,x,y);

b=find(temp+1,x,y);

return max(a,b);// 不能这样 max (find(...), find(...));

}

int update(int t,int i,int j)

{

if(i<aa[t].x||i>aa[t].y)// 若 i 不存在于 t所管理的区间内

return aa[t].max;

if(i==aa[t].x&&i==aa[t].y)// 若 t 正好是一个符合条件的叶子

return aa[t].max=j;

int a,b;// 否则。。。。

int temp=2*t;

a=update(temp,i,j);

b=update(temp+1,i,j);

aa[t].max=max(a,b);// 不能这样 max (find(...), find(...));

return aa[t].max;

}

int main()

{

int n,m,w,e;

int i;

char ch;

while(scanf("%d%d",&n,&m)!=EOF)

{

for(i=1;i<=n;i++)

scanf("%d",&num[i]);

CreatTree(1,1,n);

while(m--)

{

getchar();

scanf("%c%d%d",&ch,&w,&e);

if(ch=='Q')

printf("%d\n",find(1,w,e));

else

{

num[w]=e;

update(1,w,e);

}

}

}

return 0;

}

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1754
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: