BZOJ2809【左偏树】

/* I will wait for you */ 
    
#include<cstdio>  
#include<cstdlib>  
#include<cstring>  
#include<cmath>  
#include<ctime>  
#include<algorithm>  
#include<iostream>  
#include<fstream>  
#include<vector>  
#include<queue>  
#include<deque>  
#include<set>  
#include<map>  
#include<string>  
    
typedef long long LL;  
typedef unsigned long long ULL;  
    
using namespace std;  
    
const int maxn=100010;  
const int maxm=1010;  
const int maxs=26;  
const int INF=1<<29;  
const int P=1000000007;  
const double error=1e-9;  
    
struct node  
{  
    LL max,size,sum,dis;  
    node* son[2];  
        
    node(int num) { max=sum=num;size=dis=1;son[0]=son[1]=0; }  
}*su[maxn];  
    
struct edge{ int v,next; }e[maxn];  
    
int n,m,cnt=0;LL ans=0;  
LL pr[maxn],w[maxn],fa[maxn],head[maxn];  
    
void add(int u,int v)  
{  
    e[cnt]=(edge){v,head[u]};head[u]=cnt++;  
}  
    
void maintain(node* o)  
{  
    o->sum=o->max;o->size=1;  
    int dis[2];  
    for(int i=0;i<2;i++) if(o->son[i])  
    {  
        o->size+=o->son[i]->size;  
        o->sum+=o->son[i]->sum;  
        dis[i]=o->son[i]->dis;  
    }  
    if(dis[1]>dis[0]) swap(o->son[0],o->son[1]); 
    o->dis=dis[0]+1;
}  
    
node* marge(node* a,node* b)  
{  
    if(!a||!b) return a?a:b;  
    if(a->max<b->max) swap(a,b);  
    a->son[1]=marge(a->son[1],b);  
    maintain(a);return a;  
}  
    
void del(node* &o)  
{  
    o=marge(o->son[0],o->son[1]);  
}  
    
void ins(node* &o,int k)  
{  
    o=marge(o,new node(k));  
}  
    
void dfs(int u)  
{  
    ins(su[u],pr[u]);  
    for(int i=head[u];i!=-1;i=e[i].next)  
    {  
        int v=e[i].v;  
        if(v!=fa[u]) dfs(v),su[u]=marge(su[u],su[v]);  
    }  
    while(su[u]->sum>m) del(su[u]);  
    ans=max(ans,su[u]->size*w[u]);  
}  
            
    
int main()  
{  
    memset(head,-1,sizeof(head));  
        
    scanf("%d%d",&n,&m);  
    for(int i=1;i<=n;i++)   
    {  
        scanf("%lld%lld%lld",&fa[i],&pr[i],&w[i]);  
        add(fa[i],i);  
    }  
        
    dfs(1);printf("%lld\n",ans);  
        
    return 0;  
}  


你可能感兴趣的:(BZOJ2809【左偏树】)