您的位置:首页 > 其它

HDU 1754 I Hate It(线段树) 2984MS水过

2011-07-12 01:48 344 查看
第一次用线段树,G++ 2984ms,未用输入输出优化。

#include<stdio.h>
#define inf 1000000000

int min(int a,int b)
{
return a>b ? b:a;
}

int max(int a,int b)
{
return a>b ? a:b;
}

int mid(int a,int b)
{
return (a+b)/2;
}

struct Tnode {
int l;
int r;
int pl;
int pr;
int minval;
int maxval;
}node[10000000];

int tot;

int buildtree(int l, int r)
{
int p=tot++;
node[p].l=l;
node[p].r=r;

node[p].minval=inf;
node[p].maxval=-inf;

if (l<r) {
node[p].pl=buildtree(l,mid(l,r));
node[p].pr=buildtree(mid(l,r)+1,r);
}

return p;
}

void insert(int key,int val,int p)
{
if (node[p].l>key || node[p].r<key)
return;

if (node[p].l<node[p].r) {
insert(key,val,node[p].pl);
insert(key,val,node[p].pr);
node[p].minval=min(node[node[p].pl].minval, node[node[p].pr].minval);
node[p].maxval=max(node[node[p].pl].maxval, node[node[p].pr].maxval);
}
else {
node[p].minval=val;
node[p].maxval=val;
}
return;
}

int searchmin(int l,int r,int p)
{
if (node[p].r<l || node[p].l>r)
return inf;
else if(node[p].l>=l && node[p].r<=r)
return node[p].minval;
else
return min(searchmin(l,r,node[p].pl), searchmin(l,r,node[p].pr));
}

int searchmax(int l,int r,int p)
{
if (node[p].r<l || node[p].l>r)
return -inf;
else if(node[p].l>=l && node[p].r<=r)
return node[p].maxval;
else
return max(searchmax(l,r,node[p].pl), searchmax(l,r,node[p].pr));
}

int N,M;

int main()
{
int a,b,c;

while (~scanf("%d%d",&N,&M)) {
tot=0;
buildtree(1, N);
for (int i=1; i<=N; i++) {
scanf("%d",&a);
insert(i,a,0);
}
getchar();
for (int i=0; i<M; i++) {
c=getchar();
scanf("%d%d",&a,&b);
getchar();
if (c=='Q')
printf("%d\n",searchmax(a, b, 0));
else
insert(a, b, 0);
}
}
}


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