• 【洛谷1131】 [ZJOI2007]时态同步


    树形结构的入门题,一遍DFS即可解决,注意答案开long long

    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    #define MAXN 500005
    using namespace std;
    int read(){
        char c=getchar();int x=0;
        while(c<'0'||c>'9')c=getchar();
        while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
        return x;
    }
    int pre[MAXN<<1],other[MAXN<<1],last[MAXN],cnt,N,root,p[MAXN];
    long long val[MAXN<<1],f[MAXN],ans;
    void connect(int x,int y,long long z){
        pre[++cnt]=last[x];
        other[cnt]=y,val[cnt]=z;
        last[x]=cnt;
    }
    void Dfs(int k){
        for(int i=last[k];i;i=pre[i])
            if(other[i]!=p[k]){p[other[i]]=k;Dfs(other[i]);}
        for(int i=last[k];i;i=pre[i])
            if(other[i]!=p[k])f[k]=max(f[k],val[i]+f[other[i]]);
        for(int i=last[k];i;i=pre[i])
            if(other[i]!=p[k])ans+=f[k]-(f[other[i]]+val[i]);
    }
    int main()
    {
        N=read(),root=read();
        for(int i=1;i<N;i++){
            int x=read(),y=read(),z=read();
            connect(x,y,z);connect(y,x,z);
        }
        Dfs(root);
        printf("%lld
    ",ans);
        return 0;
    }

    P.S.本来要在洛谷分类搜道树形dp题,结果这个好像不算dp,被我一遍A了233,好爽 

  • 相关阅读:
    PHP Context学习系列《十》
    学习php记录《九》
    学习php记录《八》
    php学习记录《七》
    换到新工作后
    学习php记录《六》
    学习php记录《五》
    学习php记录《四》
    学习php记录《三》
    html基础
  • 原文地址:https://www.cnblogs.com/Elfish/p/9879513.html
Copyright © 2020-2023  润新知