题目地址:http://www.lydsy.com/JudgeOnline/problem.php?id=2809
题目大意:在一棵树中,每个节点有2个权值(val1和val2)。求一个节点x,在这个节点和其子树中找一个点集S,使得Σval1(i),i∈S小于某个下界,并使得val2(x)*|s|最大。
算法分析:
根据题目大意我们可以比较显然的发现,在一个子树中我们不断地删除这个子树的Max,我们总能使该子树的sum小于下界,于是我们可以用堆来维护这个子树的Max。因为如果某个节点对于该子树不符合条件,那么把它合并到规模更大的子树中肯定更劣而不会更优。
由于题目中严格保证了0<=Bi<i,我们只需要从后往前将节点扫一遍,先维护这棵子树的sum小于下界,再把它并到它父亲所在的堆就可以了。
对于一棵子树val1的总和以及它的size,我们可以用类似线段树Update操作进行维护。
值得提醒的是,题目中给的val2的范围已经达到了[1,1e9],而点的个数的范围又是[1,1e5],因此我们需要用long long来记录答案。
Code:
/*
* Problem:2809
* Author:PYC
*/
#include <cstdio>
#include <algorithm>
#define maxn 1000000
using namespace std;
int n,m,B[maxn],L[maxn],rt[maxn];
long long ans,t;
struct node{
int key,l,r,num;
long long sum;
}heap[maxn];
void up(int x){
heap[x].sum=(long long)(heap[heap[x].l].sum+heap[heap[x].r].sum+(long long)heap[x].key);
heap[x].num=heap[heap[x].l].num+heap[heap[x].r].num+1;
}
int merge(int p,int q){
if (!p || !q) return p?p:q;
if (heap[p].key<heap[q].key) swap(p,q);
heap[p].r=merge(heap[p].r,q);
up(p);
swap(heap[p].l,heap[p].r);
return p;
}
void del(int &x){
x=merge(heap[x].l,heap[x].r);
}
void renew(int x){
heap[x].l=heap[x].r=0;
}
int main(){
scanf("%d%d",&n,&m);
for (int i=1;i<=n;++i) scanf("%d%d%d",&B[i],&heap[i].key,&L[i]),rt[i]=i,heap[i].num=1,heap[i].sum=(long long)heap[i].key;
for (int i=n;i;--i){
while (heap[rt[i]].sum>(long long)m) del(rt[i]);
if ((t=(long long)((long long)heap[rt[i]].num*(long long)L[i]))>ans) ans=t;
if (rt[i] && B[i]) rt[B[i]]=merge(rt[B[i]],rt[i]);
}
printf("%lld\n",ans);
return 0;
}
By Charlie Pan
Mar 9,2014