[HDU]6326 Problem H. Monster Hunter 贪心

Solution

回顾一下经典的打怪兽问题。
设打死一只怪兽先掉 a i a_i ai血,再回 b i b_i bi血,那么我们排序策略是:对于 a i ≤ b i a_i\le b_i aibi a i a_i ai小的排在前;对于 a i > b i a_i>b_i ai>bi b i b_i bi大的排在前,前一种情况排在前面,正确性显然。
到了树上,并且有了打完父亲才能打儿子的限制,考虑怎么做。用一个优先队列维护当前的最优解,如果能打就直接打;否则的话因为这个是当前的最优解,在打完父亲之后一定是马上来打他,所以可以考虑把这个点与他的父亲合并,合并后的 a i , b i a_i,b_i ai,bi显然只由过程中的最低点和到达最低点后回升的血量有关。这样每次都是减少一个连通块,复杂度 O ( n log ⁡ n ) O(n\log n) O(nlogn)

Code

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
#define LL long long
const int Maxn=100010;
int read()
{
	int x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
	return x*f;
}
int n,fa[Maxn],rt[Maxn];bool mark[Maxn];
struct Edge{int y,next;}e[Maxn<<1];
int last[Maxn],len;
void ins(int x,int y)
{
	int t=++len;
	e[t].y=y;e[t].next=last[x];last[x]=t;
}
void dfs(int x,int ff)
{
	fa[x]=ff;
	for(int i=last[x];i;i=e[i].next)
	{
		int y=e[i].y;
		if(y==ff)continue;
		dfs(y,x);
	}
}
LL ans;
struct P{LL a,b;int id,T;P(LL _a,LL _b,int _id,int _T){a=_a,b=_b,id=_id;T=_T;}};
bool operator<(P x,P y)//true x在后 
{
	if(x.a<=x.b&&y.a>y.b)return false;
	if(x.a>x.b&&y.a<=y.b)return true;
	if(x.a<=x.b&&y.a<=y.b)
	{
		if(x.a>y.a)return true;
		if(x.a<y.a)return false;
		return x.id<y.id;
	}
	if(x.b<y.b)return true;
	if(x.b>y.b)return false;
	return x.id<y.id;
}
priority_queue<P>q;
int ff(int x){return((rt[x]==x)?x:rt[x]=ff(rt[x]));}
LL A[Maxn],B[Maxn];int tim[Maxn],Tim;
int main()
{
	int T=read();
	while(T--)
	{
		n=read();Tim=0;
		for(int i=1;i<=n;i++)last[i]=0,mark[i]=false,rt[i]=i;len=0;mark[1]=true;
		for(int i=1;i<n;i++)
		{
			LL a=read(),b=read();
			A[i+1]=a,B[i+1]=b;
			q.push(P(a,b,i+1,tim[i+1]=++Tim));
		}
		for(int i=1;i<n;i++)
		{
			int x=read(),y=read();
			ins(x,y);ins(y,x);
		}
		dfs(1,0);
		ans=0;LL now=0;
		while(!q.empty())
		{
			while(!q.empty())
			{
				P t=q.top();
				if(t.T!=tim[t.id])q.pop();
				else break;
			}
			if(q.empty())break;
			P t=q.top();q.pop();
			int u=ff(fa[t.id]);
			if(mark[u])
			{
				if(now<t.a)ans+=t.a-now,now=t.a;
				now=now-t.a+t.b;
				mark[t.id]=true;
			}
			else
			{
				LL na=-min(-A[u],-A[u]+B[u]-t.a);
				LL nb=-A[u]+B[u]-t.a+t.b+na;
				q.push(P(A[u]=na,B[u]=nb,u,tim[u]=++Tim));
				rt[t.id]=u;
			}
		}
		printf("%lld\n",ans);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值