zoj 3659 Conquer a New Region (经典并查集)

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
4
1 2 2
2 4 1
2 3 1
4
1 2 1
2 4 1
2 3 1
Sample Output
4
3
 
题意:
我们从大到小排一下序,对于两个集合a,b我们有两种合并方式,我们只要比较是a到b,还是b到a大,我们只要以那种最大的方式合并,就可以得到最大值了!
有1-N个城镇,有N-1条路将它们联通,也就是任何两个城镇之间有确定的一条路,每条路有它们的各自的通行量,从一个城镇到另一个城镇的通行量为连接的路段上的最小的那个量。(如1 2 2
	                                                      2 3 1,则1到3的最大通行量为1.)现在需要找一个中心城市,使这个城市到其他各个城市的通行量之和最大(traffic capacity最大)

分析:

按边排序,从大到小插入,(有一种最小生成树的赶脚。。)每条边将两个集合连起来,而新加的边是两个集合所有边的通行量最小的,那么两个集合中的通行量最小的边就是新加的那条,若是一个集合并到另一个集合,则并过来的那些城镇的通行量就是最小的新加的这个通行量,那么只要枚举两个集合是哪个并哪个的,并分别算出它们的通行量之和,选取更优的那种情况即可。

所以并查集只需要维护每个集合中元素的个数,和当前集合中的通行量之和即可,即cnt和sum数组。

#include 
    
    
     
     
#include 
     
     
      
      
#include 
      
      
       
         
using namespace std;

int fa[200010],cnt[200010];
long long sum[200010];

struct node{
	int u,v,w;
}edge[200010];

bool cmp(node a,node b)
{
	return a.w>b.w;
}

int find(int x)
{
	return x==fa[x]?x:fa[x]=find(fa[x]);
}

int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		for(int i=0;i<=n;i++)//刚开始写了
       
       
        
        <=n
		{
			fa[i]=i;
			cnt[i]=1;
			sum[i]=0;
		}
		for(int i=0;i
        
        
          ans) { ans=bbb; } } else//不然,则取aaa,将x并到y上 { fa[x]=y; cnt[y]+=cnt[x]; sum[y]=aaa; if(aaa>ans) { ans=aaa; } } } } printf("%lld\n",ans); } return 0; } 
        
       
       
      
      
     
     
    
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值