生成树专题训练1

好长时间没碰电脑了,决定把简单的东西再过一遍,同时加深理解,提高认知,对其有更深的认识。
比较常用的应该改是kruscal了。
kruscal是用边做的,把边排序,然后按顺序加边,直到形成一棵树。
今天的例题是个简单题。
poj2485
就不翻译了,应该可以看懂。
显然是直接用最小生成树,然后再找边的时候,保存最后一次加的边的长度,即为最终答案。
代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct edge{
	int u,v,w;
};
int readInt(){
	int a=0;
	char c=getchar();
	for(;c<'0'||c>'9';c=getchar()){}
	for(;c>='0'&&c<='9';c=getchar()){
		a=a*10+c-'0';
	}
	return a;
}
int T;
int n;
edge e[250005];
int p[505];
int cnt;
int ans;
int cmp(edge a,edge b){
	return a.w<=b.w;
}
int find(int cur){
	return cur==p[cur]?p[cur]:find(p[cur]);
}
void work(){
	ans=0;
	for(int i=1;i<=n;i++){
		p[i]=i;
	}
	sort(e,e+cnt,cmp);
	for(int i=0;i<cnt;i++){
		int x=find(e[i].u),y=find(e[i].v);
		if(x!=y){
			ans=max(ans,e[i].w);
			p[x]=y;
		}
	}
}
int main(){
	T=readInt();
	while(T--){
		n=readInt();
		cnt=0;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				int w;
				w=readInt();
				if(j>i){
					e[cnt].w=w;
					e[cnt].u=i;
					e[cnt].v=j;
					cnt++;
				}
				
			}
		}
		work();
		printf("%d\n",ans);
		
	} 
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值