[luogu2052 NOI2011] 道路修建 (樹形dp)
阿新 • • 發佈:2018-07-21
alt char 傳送門 -i clu con tin 這樣的 輸入
傳送門
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
1≤ai, bi≤n
0≤ci≤10^6
2≤n≤10^6
Solution
不能再水的樹形dp直接計算每條邊的貢獻
Code
//By Menteur_Hxy #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define F(i,a,b) for(register int i=(a);i<=(b);i++) #define E(i,u) for(register int i=head[u];i;i=nxt[i]) using namespace std; typedef long long LL; int read() { int x=0,f=1; char c=getchar(); while(!isdigit(c)) {if(c=='-')f=-f; c=getchar();} while(isdigit(c)) x=(x<<1)+(x<<3)+c-48,c=getchar(); return x*f; } const int N=1000010; int n,cnt; int nxt[N<<1],to[N<<1],w[N<<1],head[N],siz[N]; long long ans; void dfs(int u,int pre) { siz[u]=1; E(i,u) { int v=to[i]; if(v==pre) continue; dfs(v,u); ans+=(LL)abs(n-siz[v]*2)*w[i]; siz[u]+=siz[v]; } } #define add(a,b,c) nxt[++cnt]=head[a],to[cnt]=b,w[cnt]=c,head[a]=cnt #define ins(a,b,c) add(a,b,c),add(b,a,c) int main() { n=read(); F(i,1,n-1) { int a=read(),b=read(),c=read(); ins(a,b,c); } dfs(1,0); printf("%lld",ans); return 0; }
[luogu2052 NOI2011] 道路修建 (樹形dp)