51nod:1212 無向圖最小生成樹

基準時間限制:1 秒 空間限制:131072 KB 分值: 0 難度:基礎題
收藏
關注
取消關注
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
輸出最小生成樹的所有邊的權值之和。
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
Output示例

37


解題思路:用克魯斯卡爾算法就行(很久沒寫了,有點生-,-)


代碼如下:

#include <cstdio>
#include <algorithm>
using namespace std;
int fa[1010];
struct node
{
	int u,v,power;
}bian[50010];
bool cmp(struct node a,struct node b)
{
	return a.power<b.power;
}
int find(int x)
{
	int r=x;
	while(r!=fa[r])
	{
		r=fa[r];
	}
	return r;
}
int main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	{
		fa[i]=i;
	}
	for(int i=0;i<m;i++)
	{
		int s,e,w;
		scanf("%d%d%d",&s,&e,&w);
		bian[i].u=s;
		bian[i].v=e;
		bian[i].power=w;
	}
	sort(bian,bian+m,cmp);
	int sum=0;
	for(int i=0;i<m;i++)
	{
		int s,e,w;
		s=bian[i].u;
		e=bian[i].v;
		w=bian[i].power;
		int fx=find(s),fy=find(e);
		if(fx!=fy)
		{
			fa[fx]=fy;//很久沒寫這裏剛開始寫成了fa[s]=e;。。。這樣寫錯的話原來的s就與之前的集合斷了聯繫,畫個圖就明白了 
			sum=sum+w;
		}
	}
	printf("%d\n",sum);
	return 0;
} 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章