您的位置:首页 > 其它

HDU 1754 I hate it 线段树的应用

2011-05-22 22:01 525 查看
#include<stdio.h>

#define N_MAX 200010
typedef struct {
int left,right;
int maxScore;
}seg_tree;

seg_tree trees[N_MAX*4 +1];
int score[N_MAX+10];

int get_max(int x,int y){
return x>y?x:y;
}
void build_tree(int root,int left,int right)
{
trees[root].left = left;
trees[root].right = right;
if(left == right)
{
trees[root].maxScore = score[left];
return ;
}
int mid = (left + right)>>1;
build_tree(root*2,left,mid);
build_tree(root*2+1,mid+1,right);
trees[root].maxScore = get_max(trees[root*2].maxScore,trees[root*2+1].maxScore);
}

int find_max(int root,int left,int right)
{
if(trees[root].left == left && trees[root].right == right )
{
return trees[root].maxScore;
}
int mid = (trees[root].left + trees[root].right)>>1;
if(right <= mid)
{
return find_max(root*2,left,right);
}
if(left > mid)
{
return find_max(root*2+1,left,right);
}

return get_max(find_max(root*2,left,mid),find_max(root*2+1,mid+1,right));
}

void update(int root,int id,int new_value)
{
if(trees[root].left  == trees[root].right)
{
trees[root].maxScore = new_value;
return ;
}
int mid = (trees[root].left + trees[root].right)>>1;
if(id <= mid)
update(root*2,id, new_value);
else
update(root*2+1,id,new_value);

trees[root].maxScore = get_max(trees[root*2].maxScore,trees[root*2+1].maxScore);
}

int
main(void)
{
int N,M;
while(scanf("%d %d",&N,&M) != EOF)
{
int i,j,k;
char C;
int A,B;

for(i = 1;i<=N;i++)
scanf("%d",&score[i]);

build_tree(1,1,N);
getchar();

for(i = 1;i<=M;i++)
{
scanf("%c",&C);

if(C == 'Q')
{
scanf("%d %d",&A,&B);
printf("%d\n",find_max(1,A,B));
}
else{
scanf("%d %d",&A,&B);
update(1,A,B);
}
getchar();
}

}
return 0;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: