N个点M条边的无向连通图,每条边有一个权值,求该图的最小生成树。
Input
第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000) 
 第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)
Output
输出最小生成树的所有边的权值之和。
Sample Input
9 14 1 2 4 2 3 8 3 4 7 4 5 9 5 6 10 6 7 2 7 8 1 8 9 7 2 8 11 3 9 2 7 9 6 3 6 4 4 6 14 1 8 8
Sample Output
37
题意: 太简单不说啦!
题解:最小生成树模板题,详细请看代码。
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 50000+5;
int tree[MAX];
struct hh{ 
    int s;
	int e;
	int w;	
}a[MAX];
bool cmp(hh a, hh b){
	return a.w<b.w;
}
int find(int x){//看看是否已经连在一起
	return tree[x]==0? x:tree[x]=find(tree[x]);
}
int lianjie(int x,int y){//连接边
	int root1=find(x);
	int root2=find(y);
	if(root1!=root2){
		tree[root1]=root2;
		return 1;
	}
	return 0;
}
int main(){
	int n,m;
	cin >> n >> m;
	for (int i = 1; i <= n;i++) tree[i]=0;
	for (int i = 1; i <= m;i++){
		cin >> a[i].s >> a[i].e >> a[i].w;
	}
	sort(a+1,a+m+1,cmp);//按权值从小到大排序
	int sum=0;
	for(int i = 1; i <= m;i++){
		if(lianjie(a[i].s,a[i].e)) sum+=a[i].w;//如果没有连在一起加上该边权值
	}
	cout << sum << endl;
	return 0;	
}   

京公网安备 11010502036488号