Conquer a New Region(並查集加維護根節點)
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
4 1 2 2 2 4 1 2 3 1 4 1 2 1 2 4 1 2 3 1
Sample Output
4 3
現在有N個城市,N-1條線段構成的樹。C(i,j)表示如果城市i和城市j之間有一條線段,那麼他們之間路的容量。S(i,j)表示從i到j的路徑(一條路徑 由 首尾相連的多條線段構成)的容量,其等於從i到j的路徑經過的連續的所有線段中的最小線段容量。現在要找一個城市,使得它到其他N-1個點的S值之和最大。
先按邊權由大到小排序,用並查集維護根節點,最後讓所有點位於同一連通分量即可
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 30005
int father[maxn];
int num[maxn];
int find(int x)
{
if(father[x]!=x)
father[x]=find(father[x]);
return father[x];
}
void unionn(int x,int y)
{
int fa=find(x);
int fb=find(y);
if(fa!=fb)
{father[fb]=fa;
num[fa]+=num[fb];
}
}
int main()
{
int n,m,k;
while(~scanf("%d%d",&n,&m))
{
if(n==0&&m==0)
break;
for(int i=0;i<=n;i++)
{father[i]=i;
num[i]=1;
}
while(m--)
{
int k,u,v;
scanf("%d%d",&k,&u);
for(int i=1;i<=k-1;i++)
{
scanf("%d",&v);
unionn(u,v);
}
}
printf("%d\n",num[find(0)]);
}
}