zoukankan      html  css  js  c++  java
  • 洛谷 1131 [ZJOI2007]时态同步——树形dp

    题目:https://www.luogu.org/problemnew/show/P1131

    因为越高,调节一个影响到的越多,所以底下只要把子树间的差异消除了就行了,与其他部分的差异由更高的边调节。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #define ll long long
    using namespace std;
    const int N=5e5+5;
    int n,rt,hd[N],xnt,to[N<<1],nxt[N<<1],w[N<<1];
    ll ans,dis[N<<1];
    int rdn()
    {
        int ret=0,fx=1;char ch=getchar();
        while(ch>'9'||ch<'0'){if(ch=='-')fx=0; ch=getchar();}
        while(ch>='0'&&ch<='9') ret=(ret<<3)+(ret<<1)+ch-'0',ch=getchar();
        return fx?ret:-ret;
    }
    void add(int x,int y,int z)
    {
        to[++xnt]=y; nxt[xnt]=hd[x]; hd[x]=xnt; w[xnt]=z;
        to[++xnt]=x; nxt[xnt]=hd[y]; hd[y]=xnt; w[xnt]=z;
    }
    void dfs(int cr,int fa)
    {
        for(int i=hd[cr],v;i;i=nxt[i])
            if((v=to[i])!=fa)
            {
                dfs(v,cr);
                dis[cr]=max(dis[cr],dis[v]+w[i]);
            }
        for(int i=hd[cr],v;i;i=nxt[i])
            if((v=to[i])!=fa)
                ans+=dis[cr]-(dis[v]+w[i]);
    }
    int main()
    {
        n=rdn(); rt=rdn();
        for(int i=1,u,v,z;i<n;i++)
        {
            u=rdn(); v=rdn(); z=rdn(); add(u,v,z);
        }
        dfs(rt,0);
        printf("%lld
    ",ans);
        return 0;
    }
  • 相关阅读:
    EOJ二月月赛补题
    cf401d
    cf628d
    cf55d
    HDU 6148 Valley Number
    洛谷 P3413 SAC#1
    洛谷 P4127[AHOI2009]同类分布
    洛谷 P2602 [ZJOI2010]数字计数
    bzoj 3679
    函数和循环闭包的理解
  • 原文地址:https://www.cnblogs.com/Narh/p/9675645.html
Copyright © 2011-2022 走看看