bzoj 2435: [Noi2011]道路修建 树上 dp
生活随笔
收集整理的這篇文章主要介紹了
bzoj 2435: [Noi2011]道路修建 树上 dp
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2435: [Noi2011]道路修建
Time Limit: 20 Sec
Memory Limit: 256 MB
題目連接
http://www.lydsy.com/JudgeOnline/problem.php?id=2435
Description
在 W 星球上有 n 個國家。為了各自國家的經濟發(fā)展,他們決定在各個國家
之間建設雙向道路使得國家之間連通。但是每個國家的國王都很吝嗇,他們只愿
意修建恰好 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
題意
?
題解:
樹形dp,直接dfs就好了,姿勢不優(yōu)美的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[20]; const int inf=0x3f3f3f3f; const ll infll = 0x3f3f3f3f3f3f3f3fLL; inline ll read() {ll x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f; } inline void P(int x) {Num=0;if(!x){putchar('0');puts("");return;}while(x>0)CH[++Num]=x%10,x/=10;while(Num)putchar(CH[Num--]+48);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]=1; node kiss; for(int i=0;i<e[u].size();i++) if(!vis[(kiss=e[u][i]).x]){ vis[kiss.x]=1; 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=1;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]=1;dfs(n);cout<<ans<<endl;}?
總結
以上是生活随笔為你收集整理的bzoj 2435: [Noi2011]道路修建 树上 dp的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Scala---For语句段
- 下一篇: Python学习(七) 流程控制if语句