CodeForces 533B

#include<cstdio>
#include<algorithm>
#define ll long long 
using namespace std;
const int N=1e5+10;
int h[N<<1],cnt,n,root,p;
ll dp[N<<1][2],v[N<<1];
struct edge{
    int v,nxt;
}e[N<<2];
inline void add(int a,int b)
{
    e[++cnt].v=b;
    e[cnt].nxt=h[a];
    h[a]=cnt;
} 
template <typename e> inline void read(e &x)
{
    x=0;int f=1;char ch=getchar();
    while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') {x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    x*=f;
}
void dfs(int u,int fa)
{
    dp[u][1]=-1ll<<62;
    for(int i=h[u];i;i=e[i].nxt)
    {
        int v=e[i].v;
        if(v==fa) continue;
        dfs(v,u);
        ll x1=dp[u][1],x0=dp[u][0];
        dp[u][0]=max(dp[v][1]+x1,dp[v][0]+x0);
        dp[u][1]=max(dp[v][1]+x0,dp[v][0]+x1);
    }
    dp[u][1]=max(dp[u][1],dp[u][0]+v[u]);
}
int main()
{
    read(n);register int i;
    for(i=1;i<=n;++i)
    {
        read(p);read(v[i]); 
        if(p==-1) root=i;
        add(i,p);add(p,i);
    }
    dfs(root,-1);
    printf("%lld",max(dp[root][0],dp[root][1]));
    return 0;
}

 

 blog

posted @ 2019-10-22 17:21  sooner  阅读(69)  评论(0编辑  收藏  举报