練習四 1004

概述:給你一些鎮子,和鎮子之間的距離,現在要修一條路,把所有鎮子連起來,求路的最短距離。

思路:最小生成樹問題,我採用的還是KRUSKAL是第一題的簡化版,詳情請看第一題。

感想:刷了第一題,再看這個題,感覺好簡單。

#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
const int N = 105;
int father[N];
int find(int x) 
{
	if (x != father[x])
		father[x] = find(father[x]);
	return father[x];
}
struct edge
{
	int x, y, v;
}e[N*(N - 1) / 2];
int cmp(edge e1, edge e2) 
{
	return e1.v<e2.v;
}

int main()
{
	//ifstream cin("aaa.txt");
	int n;
	while (cin >> n&&n)
	{
		for (int i = 0; i <= n; ++i)
			father[i] = i;
		n = n*(n - 1) / 2;
		for (int i = 0; i<n; i++)
			cin>>e[i].x>>e[i].y>>e[i].v;
		sort(e, e + n, cmp);
		int ans = 0;
		for (int i = 0; i < n; ++i)
		{
			int x = find(e[i].x);
			int y = find(e[i].y);
			if (x != y)
			{	
				ans += e[i].v;
				father[x] = y;	
			}
		}
		cout << ans << endl;
	}
	return 0;
}


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