bzoj2435: [Noi2011]道路修建

傻叉树形dp。。

#include<cstdio>
#include<cstring>
#include<cctype>
#include<algorithm>
using namespace std;
#define rep(i,s,t) for(int i=s;i<=t;i++)
#define dwn(i,s,t) for(int i=s;i>=t;i--)
#define clr(x,c) memset(x,c,sizeof(x))
#define qwq(x) for(edge *o=head[x];o;o=o->next)
#define ll long long
int read(){
    int x=0;char c=getchar();
    while(!isdigit(c)) c=getchar();
    while(isdigit(c)) x=x*10+c-'0',c=getchar();
    return x;
}
const int nmax=1e6+5;
const int inf=0x7f7f7f7f;
struct edge{
    int to,dist;edge *next;
};
edge es[nmax<<1],*pt=es,*head[nmax];
void add(int u,int v,int d){
    pt->to=v;pt->dist=d;pt->next=head[u];head[u]=pt++;
    pt->to=u;pt->dist=d;pt->next=head[v];head[v]=pt++;
}
ll ans=0;int n;
int dfs(int x,int fa){
    int cnt=1;
    qwq(x) if(o->to!=fa){
        int tmp=dfs(o->to,x);
        cnt+=tmp;ans+=(ll)abs(n-tmp-tmp)*o->dist;
    }
    return cnt;
}
int main(){
    n=read();int u,v,d;
    rep(i,1,n-1){
        u=read(),v=read(),d=read(),add(u,v,d);
    }
    dfs(1,0);
    printf("%lld
",ans);
    return 0;
}

  

2435: [Noi2011]道路修建

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 3426  Solved: 1129
[Submit][Status][Discuss]

Description

在 W 星球上有 n 个国家。为了各自国家的经济发展,他们决定在各个国家
之间建设双向道路使得国家之间连通。但是每个国家的国王都很吝啬,他们只愿
意修建恰好 n – 1条双向道路。 每条道路的修建都要付出一定的费用, 这个费用等于道路长度乘以道路两端的国家个数之差的绝对值。例如,在下图中,虚线所示道路两端分别有 2 个、4个国家,如果该道路长度为 1,则费用为1×|2 – 4|=2。图中圆圈里的数字表示国家的编号。


由于国家的数量十分庞大,道路的建造方案有很多种,同时每种方案的修建
费用难以用人工计算,国王们决定找人设计一个软件,对于给定的建造方案,计
算出所需要的费用。请你帮助国王们设计一个这样的软件。

Input


输入的第一行包含一个整数n,表示 W 星球上的国家的数量,国家从 1到n
编号。接下来 n – 1行描述道路建设情况,其中第 i 行包含三个整数ai、bi和ci,表
示第i 条双向道路修建在 ai与bi两个国家之间,长度为ci。

Output

输出一个整数,表示修建所有道路所需要的总费用。

Sample Input


6
1 2 1
1 3 1
1 4 2
6 3 1
5 2 1

Sample Output


20

HINT



n = 1,000,000 1≤ai, bi≤n 

0 ≤ci≤ 10^6

 

Source

[Submit][Status][Discuss]
原文地址:https://www.cnblogs.com/fighting-to-the-end/p/5858141.html