BZOJ 2435: [Noi2011]道路修建 树形DP

版权声明:https://blog.csdn.net/huashuimu2003 https://blog.csdn.net/huashuimu2003/article/details/89764443

title

BZOJ 2435
LUOGU 2052
JYOJ 1308
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

Day2

analysis

我们可以对这棵树进行 d f s dfs 计算出每个点的 s i z e size ,然后就知道这条边的贡献为 a b s ( n 2 s i z e [ y ] ) w [ i ] abs(n-2*size[y])*w[i] ,其中 y y 为这条边的儿子。

所以说,这道题有负于 N O I NOI 的大名。。

code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+3;

template<typename T>inline void read(T &x)
{
    x=0;
    T f=1, ch=getchar();
    while (!isdigit(ch) && ch^'-') ch=getchar();
    if (ch=='-') f=-1, ch=getchar();
    while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
    x*=f;
}

int ver[maxn<<1],edge[maxn<<1],Next[maxn<<1],head[maxn],len;
inline void add(int x,int y,int z)
{
    ver[++len]=y,edge[len]=z,Next[len]=head[x],head[x]=len;	
}
int siz[maxn],n;
ll ans;
inline void dfs(int x,int fa)
{
    siz[x]=1;
    for (int i=head[x]; i; i=Next[i])
    {
        int y=ver[i];
        if (y==fa) continue;
        dfs(y,x);
        siz[x]+=siz[y];
        ans+=(ll)abs(n-siz[y]*2)*edge[i];
    }
}

int main()
{
    read(n);
    for (int i=1; i<n; ++i)
    {
        int x,y,z;
        read(x);read(y);read(z);
        add(x,y,z);add(y,x,z);
    }
    dfs(1,1);
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/huashuimu2003/article/details/89764443