練習四 1001

概述:給你一些城鎮,以及各個鎮之間的距離,現在要修建道路,把這些鎮子穿起來,已知一些鎮子之間已經有了道路(即不用再修了),現在求施工的最短路徑。

思路:這是最小生成樹問題,我採用的是kruskal算法。

感想:“一些鎮子之間已經有了道路”這個條件比較難纏,想了一會才明白,只要另這些鎮子的距離爲0就可以,這樣就不會影響結果。

#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
const int N = 105;
int father[N];
int map[N][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;
	cin >> n;
	int ansa = n;
	for (int i = 0; i <= n; ++i)
		father[i] = i;
	for (int i = 0; i < n; ++i)
		for (int j = 0; j < n; ++j)
			cin >> map[i][j];
	int q;
	cin >> q;
	int temp1, temp2;
	for (int i = 0; i < q; ++i)
	{
		cin >> temp1 >> temp2;
		map[temp1 - 1][temp2 - 1] = 0;
	}
	int cnt = 0;
	for (int i = 0; i < n; ++i)
		for (int j = 0; j < n; ++j)
		{
			e[cnt].x = i;
			e[cnt].y = j;
			e[cnt].v = map[i][j];
			++cnt;
		}
		
	int ans = 0;
	sort(e, e + cnt, cmp);
	for (int i = 0; i < cnt; ++i)
	{
		int x = find(e[i].x);
		int y = find(e[i].y);
		if (x != y)
		{
			ans += e[i].v;
			father[x] = y;
			--ansa;
			if(ansa==1)
			{
				cout << ans << endl;
				return 0;
			}
				
		}
	}

}


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