您的位置:首页 > 其它

【BZOJ 2809】dispatching(主席树)

2014-12-06 15:24 260 查看
这道题用主席树做做感觉非常舒服~~~

首先题意来看,是说需要在树形结构中找到一个点i,并且找到这个点子树中的一些点组成一个集合,使得集合中的c之和不超过M,且Li*集合中元素个数和最大

简单地想想首先需要枚举每一个点,然后在子树中找到最小的k个点,使得sigma(C[i])(i = 1..k)不超过M,那么L[i]*k就是对于这个点来说的最优解

那么我们应该想到可以利用主席树中的性质,首先将树形结构通过dfs序转化到线性结构上,然后可以通过对子树中的记录信息进行判断从而得到答案(详见代码)

再想想其实有些点没有必要对它进行枚举。如果它的祖先中有L比它大,那么这个点肯定不会优于它的祖先,因此不用枚举它了。

#include<cstdio>
#include<cstring>
#include<algorithm>
#define Rep(a,b,c) for(int a = b ; a <= c ; a ++)
#define clr(a) memset(a,0,sizeof(a))
#define clr1(a) memset(a,-1,sizeof(a))
#define LL long long
#define Mid int mid = (l + r) >> 1
#define N 100500
using namespace std;
struct edge{
int to,next;
};
struct node{
node *ch[2];
LL w;
int siz;
void init(){
w = siz = 0;
ch[0] = ch[1] = NULL;
}
node(){init();}
void update(){
siz = w = 0;
if(ch[0]) {siz += ch[0]->siz;w += ch[0]->w;}
if(ch[1]) {siz += ch[1]->siz;w += ch[1]->w;}
}
}T[N * 20];
int qcnt,size;
int C
,L
,C2
;
struct SegmentTree{
node *root
,*null;
void init(){
null = &T[qcnt ++];
null->init();
null->ch[0] = null->ch[1] = null;
}
void __build(node *&y,node *&x,int l,int r,int t){
if(x == NULL) x = null;
y = &T[qcnt ++];
y->init();
if(l == r){
*y = *x;
y->w += t;
y->siz ++;
return;
}
Mid;
if(t <= C2[mid]){
__build(y->ch[0],x->ch[0],l,mid,t);
y->ch[1] = x->ch[1];
y->update();
}
else{
__build(y->ch[1],x->ch[1],mid+1,r,t);
y->ch[0] = x->ch[0];
y->update();
}
}
void __find(node *x1,node *x2,int l,int r,int lim,int &ans){
if(x1 == NULL) x1 = null;
if(x2 == NULL) x2 = null;
if(l == r){
ans += min(lim / C2[l],x2->siz - x1->siz);
return;
}
LL lw = 0;
int ls = 0;
lw += x2->ch[0]->w;ls += x2->ch[0]->siz;
lw -= x1->ch[0]->w;ls -= x1->ch[0]->siz;
Mid;
if(lim >= lw){
ans += ls;
__find(x1->ch[1],x2->ch[1],mid + 1,r,lim - lw,ans);
}
else __find(x1->ch[0],x2->ch[0],l,mid,lim,ans);
}
void build(int id,int val){
__build(root[id],root[id - 1],1,size,val);
}
int find(int x,int y,int lim){
int ans = 0;
__find(root[x - 1],root[y],1,size,lim,ans);
return ans;
}
}sgt;
edge e[N << 1];
int head
,sz;
int l
,r
,dfsc,rank
;
bool needs
;
int n,m;
void addedge(int u,int v){
e[sz].to = v;
e[sz].next = head[u];
head[u] = sz ++;
}
void init(){
clr(needs);
clr1(head);
sz = dfsc = qcnt = 0;
}
void dfs(int u,int Max){
l[u] = ++dfsc;
rank[dfsc] = u;
if(Max < L[u]) needs[u] = 1;
int nmax = max(Max,L[u]);
for(int i = head[u] ; i != -1 ; i = e[i].next){
int v = e[i].to;
dfs(v,nmax);
}
r[u] = dfsc;
}
void solve(){
int b;
init();
sgt.init();
Rep(i,1,n){
scanf("%d",&b);
addedge(b,i);
scanf("%d%d",&C[i],&L[i]);
C2[i] = C[i];
}
dfs(0,-1);
sort(C2 + 1,C2 + n + 1);
size = unique(C2 + 1,C2 + n + 1) - (C2 + 1);
Rep(i,1,dfsc) sgt.build(i,C[rank[i]]);
LL ans = -1;
Rep(i,1,n){
if(!needs[i]) continue;
ans = max(ans,(LL)sgt.find(l[i],r[i],m) * L[i]);
}
printf("%lld\n",ans);
}
int main()
{
while(~scanf("%d%d",&n,&m)) solve();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: