题解:
考虑先打i,再打j会造成HP+max(-ai,-ai+bi-aj),故排序时只要(-ai,-ai+bi-aj) < (-aj,-aj+bj-ai)比较排序即可。
然后因为必须先打父亲结点,再打儿子结点,如果按当前能打的点来一个个贪心是错误的,因为我们并不知道哪个高消耗hp的父亲结点下会有回复hp很多的儿子结点,可能打这样一颗子树更优。
做法:一开始就全部入优先队列,然后每次将该结点与父亲结点合并成一个点。合并时遵循max(-ai,-ai+bi-aj)贪心的规则。
#include"bits/stdc++.h"
using namespace std;
typedef long long LL;
int T,n,m;
const int mod = 1e9+7;
const LL INFLL = 0x3f3f3f3f3f3f3f3f;
const int MX = 1e5+7;
LL now;
struct node{
int id,num;
LL x,y;
node(){}
node(LL x,LL y) : x(x),y(y){}
bool operator < (const node &b) const{
return min(x, x+b.x+y) < min(b.x, x+b.x+b.y);
}
}p[MX];
int f[MX];
vector<int> G[MX];
bool del[MX];
priority_queue <node> q;
void dfs(int u, int fa)
{
f[u] = fa;
for(auto v : G[u]){
if(v == fa) continue;
dfs(v,u);
}
}
int get_fa(int x)
{
return del[f[x]]? f[x] = get_fa(f[x]) : f[x];
}
void solve()
{
scanf("%d",&n);
p[1] = node(0,0);
p[1].id = 1;
p[1].num = 0;
for(int i = 2; i <= n; i++){
scanf("%lld%lld",&p[i].x,&p[i].y);
p[i].x *= -1;
p[i].id = i;
p[i].num = 0;
}
int cnt = 0;
for(int i = 1; i <= n; i++) G[i].clear();
for(int i = 0; i <= n; i++) del[i] = 0;
for(int i = 1; i < n; i++){
int u,v;
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1,1);
for(int i = 2; i <= n; i++)
q.push(p[i]);
while(q.size())
{
node e = q.top(); q.pop();
int u = e.id;
if(del[u]) continue;
if(e.num != p[u].num) continue;
del[u] = 1;
int fa = get_fa(u);
if(p[u].x+p[fa].y < 0){
p[fa].x += p[u].x+p[fa].y;
p[fa].y = p[u].y;
}
else p[fa].y += p[u].y + p[u].x;
if(fa > 1){
p[fa].num = ++cnt;
q.push(p[fa]);
}
}
cout<<-p[1].x<<endl;
}
int main()
{
#ifdef LOCAL
freopen("input.txt","r",stdin);
#endif // LOCAL
for(scanf("%d",&T); T; T--)
solve();
return 0;
}