Conquer a New Region
Time Limit: 5 Seconds
Memory Limit: 32768 KB
The wheel of the history rolling forward, our king conquered a new region in a distant continent.
There are N towns (numbered from 1 to N) in this region connected by several roads. It's confirmed that there is exact one route between any two towns. Traffic is important while controlled colonies are far away from the local country. We define the capacity
C(i, j) of a road indicating it is allowed to transport at most C(i, j) goods between town i and town j if there is a road between them. And for a route between i and j, we define a value S(i, j) indicating the maximum traffic capacity between i and j which
is equal to the minimum capacity of the roads on the route.
Our king wants to select a center town to restore his war-resources in which the total traffic capacities from the center to the other N - 1 towns is maximized. Now, you, the best programmer in the kingdom, should help our king to select this center.
Input
There are multiple test cases.
The first line of each case contains an integer N. (1 ≤ N ≤ 200,000)
The next N - 1 lines each contains three integers a, b, c indicating there is a road between town a and town b whose capacity is c. (1 ≤ a, b ≤ N, 1 ≤ c ≤ 100,000)
Output
For each test case, output an integer indicating the total traffic capacity of the chosen center town.
Sample Input
41 2 22 4 12 3 141 2 12 4 12 3 1
Sample Output
43
這題用並查集來做,確實,很好啊,當時一看題,就有一種網路流的感覺,一直坑在那,其實,我們可以發現,這題是一個樹,那麼兩點之間只能有一條路,也就是這一個重要性質,我們就可以用並查集,我們從大到小排一下序,對於兩個集合a,b我們有兩種合并方式,我們只要比較是a到b,還是b到a大,我們只要以那種最大的方式合并,就可以得到最大值了!因為,兩點之間,只有一條邊啊!#include <iostream>#include <stdio.h>#include <algorithm>#include <string.h>using namespace std;#define MAXN 200050struct node { int s,e,c; bool operator <(node a)const{return c>a.c;}}edge[MAXN];long long sum[MAXN];int no[MAXN],father[MAXN];bool cmp(node a,node b){ return a<b;}int find(int x){ if(father[x]!=x) father[x]=find(father[x]); return father[x];}int main(){ int n,i; long long tempa,tempb; while(scanf("%d",&n)!=EOF) { for(i=0;i<=n;i++) { no[i]=1,sum[i]=0,father[i]=i; } for(i=1;i<=n-1;i++) { scanf("%d%d%d",&edge[i].s,&edge[i].e,&edge[i].c); } sort(edge+1,edge+n,cmp); for(i=1;i<=n-1;i++) { int a=find(edge[i].s); int b=find(edge[i].e); if(a!=b) { tempa=(long long )edge[i].c*no[b]+sum[a]; tempb=(long long )edge[i].c*no[a]+sum[b]; if(tempa>tempb) { father[b]=a,sum[a]=tempa,no[a]+=no[b]; } else { father[a]=b,sum[b]=tempb,no[b]+=no[a]; } } } int a=find(1); printf("%lld\n",sum[a]); } return 0;}