bzoj 2435: [Noi2011]道路修建 树上 dp

时间:2023-03-08 18:34:11

2435: [Noi2011]道路修建

Time Limit: 20 Sec

Memory Limit: 256 MB

题目连接

http://www.lydsy.com/JudgeOnline/problem.php?id=2435

Description

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

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

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

题意

题解:

树形dp,直接dfs就好了,姿势不优美的dp会被卡爆栈……

本是傻逼题,相煎何太急

代码:

//qscqesze
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
#include <stack>
typedef long long ll;
using namespace std;
//freopen("D.in","r",stdin);
//freopen("D.out","w",stdout);
#define sspeed ios_base::sync_with_stdio(0);cin.tie(0)
#define test freopen("test.txt","r",stdin)
#define maxn 1500005
#define mod 10007
#define eps 1e-9
int Num;
char CH[];
const int inf=0x3f3f3f3f;
const ll infll = 0x3f3f3f3f3f3f3f3fLL;
inline ll read()
{
ll x=,f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-')f=-;ch=getchar();}
while(ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
inline void P(int x)
{
Num=;if(!x){putchar('');puts("");return;}
while(x>)CH[++Num]=x%,x/=;
while(Num)putchar(CH[Num--]+);
puts("");
}
//**************************************************************************************
struct node
{
int x,y;
};
ll ans;
vector<node> e[maxn];
int vis[maxn];
int size[maxn];
int n;
int a,b,c;
void dfs(int u)
{
size[u]=;
node kiss;
for(int i=;i<e[u].size();i++)
if(!vis[(kiss=e[u][i]).x]){
vis[kiss.x]=;
dfs(kiss.x);
size[u]+=size[kiss.x];
ans+=(ll)abs(n-size[kiss.x]-size[kiss.x])*kiss.y;
}
}
int main()
{
//test;
n=read();
for(int i=;i<n;i++)
{
a=read(),b=read(),c=read();
e[a].push_back((node){b,c});
e[b].push_back((node){a,c});
}
vis[n]=;
dfs(n);
cout<<ans<<endl; }