2435: [Noi2011]道路修建

普…普及组?
读完题以后我感觉我是不是读错题了….
然后发现真的是水题…
按题目所说的模拟就好了…
一遍dfs搞定
c++代码如下:

#include<bits/stdc++.h>
#define rep(i,x,y) for(register int i = x ; i <= y; ++ i)
#define repd(i,x,y) for(register int i = x ; i >= y; -- i)
using namespace std;
typedef long long ll ;
template<typename T>inline void read(T&x)
{
    char c;int sign = 1;x = 0;
    do { c = getchar(); if(c == '-') sign = -1; }while(!isdigit(c));
    do { x = x * 10 + c - '0'; c = getchar(); }while(isdigit(c));
    x *= sign;
}

const int N = 1e6+50,M = 2e6+50;
int n; 
int head[N],nxt[M],to[M],w[M],tot;

inline void add(int x,int y,int val)
{
    nxt[tot] = head[x];
    to[tot] = y;
    w[tot] = val;
    head[x] = tot++;
}

ll ans ;
int size[N];

void dfs(int x,int fa)
{
    size[x] = 1;
    for(register int i = head[x];~i;i=nxt[i])
        if(to[i] != fa){
            dfs(to[i],x);
            size[x] += size[to[i]];
            ans += 1ll*abs(n - size[to[i]]*2)*w[i];
    }
}

int main()
{
    memset(head,-1,sizeof head);
    read(n);
    int u ,v,w;
    rep(i,2,n)
    {
        read(u); read(v);read(w);
        add(u,v,w); add(v,u,w);
    }

    dfs(1,1);

    cout << ans << endl;
    return 0;
}
    原文作者:道路修建问题
    原文地址: https://blog.csdn.net/Tgotp/article/details/80202355
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞