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)]);

    }
}

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/83099264
new