您的位置:首页 > 其它

HDU-1754-I Hate It【线段树求区间最值】

2018-03-09 10:57 363 查看
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

const int maxn=200005;

#define lson l,m,rt;
#define LL(x) (x<<1)
#define RR(x) (x<<1|1)

int num[maxn];
struct
{
int l,r;
int Max;
} tree[maxn<<2];

void build(int rt,int l,int r)
{
tree[rt].l=l;
tree[rt].r=r;
if(tree[rt].l==tree[rt].r)
{
tree[rt].Max=num[l];
return ;
}
int mid=(tree[rt].l+tree[rt].r)>>1;
build(LL(rt),l,mid);
build(RR(rt),mid+1,r);
tree[rt].Max=max(tree[LL(rt)].Max,tree[RR(rt)].Max);
}

void update(int rt,int pos,int val)
{
if(tree[rt].l==tree[rt].r)
{
tree[rt].Max=val;
return ;
}
int mid=(tree[rt].l+tree[rt].r)>>1;
if(pos<=mid)
update(LL(rt),pos,val);
else
update(RR(rt),pos,val);
tree[rt].Max=max(tree[LL(rt)].Max,tree[RR(rt)].Max);
}

int query(int rt,int l,int r)
{
if(l <= tree[rt].l && r >= tree[rt].r)
{
return tree[rt].Max;
}
int mid = (tree[rt].l + tree[rt].r)>>1;
int ret = 0;
if(l <= mid) ret =max(ret, query(LL(rt), l, r) );
if(r > mid ) ret =max(ret, query(RR(rt), l, r) );
return ret;
}

int main()
{
int n,m,a,b,val;
while(~scanf("%d%d",&n,&m))
{
for(int i=1; i<=n; i++)
{
scanf("%d",&num[i]);
}
build(1,1,n);
char op[5];
while(m--)
{
scanf("%s",op);
if(op[0]=='Q')
{
scanf("%d%d",&a,&b);
printf("%d\n",query(1,a,b));
}
else if (op[0]=='U')
{
scanf("%d%d",&a,&val);
update(1,a,val);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDU1754