hdu 2795 Billboard(线段树)

hhanger大牛的题。我在他的博客里看到这道题是线段树,但是对着题目枯死良久,也想不明白该怎么建树。直到我看到一篇博客。

博客链接:点击打开链接

只要能想清楚怎么建树,这道题其实还是比较水的。

#include<stdio.h>
#include<string.h>
#define N 200005
struct node
{
	int l,r;
	int x;
}a[N*3];
int h,w,n;
int Max(int x,int y)
{
	if(x>y)
		return x;
	else
		return y;
}
void CreatTree(int t,int x,int y)
{
	a[t].l=x;
	a[t].r=y;
	a[t].x=w;
	if(x==y)
		return ;
	int temp=t*2;
	int mid=(x+y)/2;
	CreatTree(temp,x,mid);
	CreatTree(temp+1,mid+1,y);
	return ;
}
int FindTree(int t,int x)
{
	int ans;
	if(a[t].l==a[t].r)
	{
		int temp=a[t].x;
		a[t].x-=x;
		return a[t].l;
	}
	int temp=t*2;
	if(a[temp].x>=x)
		ans=FindTree(temp,x);
	else
		ans=FindTree(temp+1,x);
	a[t].x=Max(a[temp].x,a[temp+1].x);
	return ans;
}
int main()
{
	while(scanf("%d%d%d",&h,&w,&n)!=EOF)
	{
		if(h<n)
			CreatTree(1,1,h);
		else
			CreatTree(1,1,n);
		while(n--)
		{
			int x;
			scanf("%d",&x);
			if(a[1].x>=x)
				printf("%d
",FindTree(1,x));
			else
				printf("-1
");
		}
	}
	return 0;
}


原文地址:https://www.cnblogs.com/snake-hand/p/3190322.html