HDU 1754 i hate it

本文通过HDU1754题目的实现,深入探讨线段树的数据结构与算法原理。作者分享了从构建到更新查询的全过程,并反思自身在编码实践中的不足之处。

线段树问题。

看完STATISTICS的第一页有感:和高手比还是有差距啊!

/*
 * HDU 1754 i hate it
 * mike-w
 * 2011-8-14
 * ----------------------
 * hint: segment tree
 * PS:看来对线段树的IMPLEMENTATION还不是很熟悉,
 *    debug了十几分钟,鄙人coding委实有待加强
 *    400+ms,高手门是140+ms :D
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 200000
#define L 0
#define R 1
#define BEST 2
#define max(x,y) ((x)>(y)?(x):(y))
int seg[MAXSIZE][3];

int build(long r,long x1,long x2)
{
	seg[r][L]=x1;
	seg[r][R]=x2;
	seg[r][BEST]=0;
	
	long t=r<<1;
	if(x1==x2)
		return 0;
	else if(x2-x1==1)
	{
		build(t,x1,x1);
		build(t+1,x2,x2);
	}
	else
	{
		long mid=(x1+x2)>>1;
		build(t,x1,mid);
		build(t+1,mid+1,x2);
	}
	return 0;
}

int update(long r,long id,long scr)
{
	long  mid=(seg[r][L]+seg[r][R])>>1,
		  t=r<<1;
	if(seg[r][L]==seg[r][R])
	{
		seg[r][BEST]=scr;
		return 0;
	}
	else if(id<=mid)
		update(t,id,scr);
	else
		update(t+1,id,scr);
	seg[r][BEST]=max(seg[t][BEST],seg[t+1][BEST]);
	return 0;
}

int query(long r,long x1,long x2)
{
	long mid=(seg[r][L]+seg[r][R])>>1,
		 t=r<<1;
	if(seg[r][L]==x1&&seg[r][R]==x2)
		return seg[r][BEST];
	else if(x2<=mid)
		return query(t,x1,x2);
	else if(x1>mid)
		return query(t+1,x1,x2);
	else
		return max(query(t,x1,mid),query(t+1,mid+1,x2));
}

int main(void)
{
	long N,M,i;
	int tmp,arg1,arg2;
	char buf[5];

#ifndef ONLINE_JUDGE
	freopen("1754.in","r",stdin);
#endif

	while(scanf("%ld%ld",&N,&M)!=EOF)
	{
		build(1,1,N);
		for(i=1;i<=N;i++)
		{
			scanf("%d",&tmp);
			update(1,i,tmp);
		}
		for(i=1;i<=M;i++)
		{
			scanf("%s%d%d",buf,&arg1,&arg2);
			if(*buf=='Q')
				printf("%d\n",query(1,arg1,arg2));
			else
				update(1,arg1,arg2);
		}
	}
	return 0;
}


 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值