zoukankan      html  css  js  c++  java
  • 【洛谷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,好爽 

  • 相关阅读:
    纯虚函数和抽象类
    继承和多态
    C++运算符重载
    构造函数
    C++对c中函数的拓展,函数重载
    c++ c的拓展
    linux终端下常用快捷键
    SEED-DVS6467_SDK的交叉编译环境搭建问题
    Linux内核编译
    Python简单爬虫记录
  • 原文地址:https://www.cnblogs.com/Elfish/p/9879513.html
Copyright © 2011-2022 走看看