BZOJ2435 [Noi2011]道路修建 【树形Dp 吧。。】

题目

在 W 星球上有 n 个国家。为了各自国家的经济发展,他们决定在各个国家
之间建设双向道路使得国家之间连通。但是每个国家的国王都很吝啬,他们只愿
意修建恰好 n – 1条双向道路。 每条道路的修建都要付出一定的费用, 这个费用等于道路长度乘以道路两端的国家个数之差的绝对值。例如,在下图中,虚线所示道路两端分别有 2 个、4个国家,如果该道路长度为 1,则费用为1×|2 – 4|=2。图中圆圈里的数字表示国家的编号。
这里写图片描述
由于国家的数量十分庞大,道路的建造方案有很多种,同时每种方案的修建
费用难以用人工计算,国王们决定找人设计一个软件,对于给定的建造方案,计
算出所需要的费用。请你帮助国王们设计一个这样的软件。

输入格式

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

输出格式

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

输入样例

6

1 2 1

1 3 1

1 4 2

6 3 1

5 2 1

输出样例

20

解释

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

0 ≤ci≤ 10^6

题解

dfs算算就好了【NOI题??】
要注意爆栈= =【蒟蒻爆了一次】
减少传参就好了【事实告诉我们1000000只传一参不会爆。】

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define Redge(u) for (int k = h[u]; k != -1; k = ed[k].nxt)
using namespace std;
const int maxn = 1000005,maxm = 2000005,INF = 1000000000;
inline int RD(){
    int out = 0,flag = 1; char c = getchar();
    while (c < 48 || c > 57) {if (c == '-') flag = -1; c = getchar();}
    while (c >= 48 && c <= 57) {out = (out << 1) + (out << 3) + c - '0'; c = getchar();}
    return out * flag;
}
int n,siz[maxn],fa[maxn];
int h[maxn],ne = 0;
struct EDGE{int to,nxt,w;}ed[maxm];
inline void build(int u,int v,int w){
    ed[ne] = (EDGE){v,h[u],w}; h[u] = ne++;
    ed[ne] = (EDGE){u,h[v],w}; h[v] = ne++;
}
LL ans = 0;
void dfs(int u){
    int to; siz[u] = 1;
    Redge(u) if ((to = ed[k].to) != fa[u]){
        fa[to] = u; dfs(to);
        ans += (LL)ed[k].w * abs(n - 2 * siz[to]);
        siz[u] += siz[to];
    }
}
int main(){
    memset(h,-1,sizeof(h));
    n = RD(); int a,b,w;
    REP(i,n - 1) a = RD(),b = RD(),w = RD(),build(a,b,w);
    dfs(1);
    cout<<ans<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/Mychael/p/8282737.html