BZOJ 1060: [ZJOI2007]时态同步

Description

一个有根树,你只能进行增加操作,问你将所有叶节点到根的路径权值相同至少需要增加几次.

Sol

我也不知道该叫什么算法...

反正就是记录一下到子节点到当前节点的最大距离统计答案就可以了.

Code

/**************************************************************
    Problem: 1060
    User: BeiYu
    Language: C++
    Result: Accepted
    Time:960 ms
    Memory:19660 kb
****************************************************************/
 
#include <cstdio>
#include <utility>
#include <vector>
#include <iostream>
using namespace std;
 
#define mpr make_pair
#define _x first
#define _y second
typedef pair< int,int > pr;
const int N = 500005;
 
int n,rt;
int f[N];
vector< pr > g[N];
long long ans;
 
inline int in(int x=0,char ch=getchar()){ while(ch>'9' || ch<'0') ch=getchar();
    while(ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();return x; }
void DP(int u,int fa){
    f[u]=0;
    for(int i=0,lim=g[u].size(),v;i<lim;i++) if((v=g[u][i]._x)!=fa)
        DP(v,u),f[u]=max(f[u],f[v]+g[u][i]._y);
    for(int i=0,lim=g[u].size(),v;i<lim;i++) if((v=g[u][i]._x)!=fa) ans+=f[u]-(f[v]+g[u][i]._y);
}
int main(){
    n=in(),rt=in();
    for(int i=1,u,v,w;i<n;i++){
        u=in(),v=in(),w=in();
        g[u].push_back(mpr(v,w));
        g[v].push_back(mpr(u,w));
    }
    DP(rt,0);
    cout<<ans<<endl;
    return 0;
}

  

posted @ 2016-11-29 15:00  北北北北屿  阅读(129)  评论(0编辑  收藏  举报