畅通工程【浙江大学】★

牛客网题目链接

并查集入门

版本1

#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstdio>
#include <cctype>
#include <unordered_map>
#include <map>
using namespace std;
const int N = 105;
typedef pair<int, string> PII;
int root[N];
int find(int x){
	if(x != root[x]) root[x] = find(root[x]);
	return root[x];
}
struct road{
	int u, v, w;
	bool operator < (const road a)const{
		return w < a.w;
	}
}E[N];
int main() {
	int n, m;
	while(cin>>n>>m){
		if(!n) break;
		for(int i = 1; i <= m; i++){
			root[i] = i;
		}
		int cnt = 1, w = 0;
		for(int i = 0; i < n; i++){
			cin>>E[i].u>>E[i].v>>E[i].w;
		}
		sort(E, E + n);
		for(int i = 0; i < n; i++){
			int a = find(E[i].u);
			int b = find(E[i].v);
			if(a != b){
				root[b] = a;
				w += E[i].w;
				cnt++;
			}
		}
		if(cnt != m){
			cout<<"?"<<endl;
		}else cout<<w<<endl;
	}
	return 0;
}

版本2

以前写的代码

#include<cstdio>
#include<algorithm>
#define N 105
using namespace std;
struct edge{
	int u,v;
	int cost;
	bool operator < (const edge &b)const{
	    return cost < b.cost;
	}
}E[N]; 
int father[N];
int findFather(int x){
	if(x == father[x]) return x;
	else{
		int tp = findFather(father[x]);
		father[x] = tp;
		return tp;
	}
}
int main(){
	int n,m;
	while(scanf("%d",&n) != EOF&& n != 0){
		scanf("%d",&m);
		for(int i = 1;i <= n;i++){
			scanf("%d%d%d",&E[i].u,&E[i].v,&E[i].cost);
		}
	int path = 0,num_edge = 0;
	for(int i = 1;i <= m;i++){
		father[i] = i;
	}
	sort(E+1,E+n+1);
	for(int i = 1;i <= n;i++){
		int faU = findFather(E[i].u);
	    int faV = findFather(E[i].v);
	    if(faU != faV){
	    	father[faU] = faV;
	    	path += E[i].cost;
	    	num_edge++;
		}	    
	}
	if(num_edge != m-1) printf("?\n");
	else printf("%d\n",path);
	}
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值