題目1017:還是暢通工程(間接排序)

題目描述:
    某省調查鄉村交通狀況,得到的統計表中列出了任意兩村莊間的距離。省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可),並要求鋪設的公路總長度爲最小。請計算最小的公路總長度。
輸入:

    測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N ( < 100 );隨後的N(N-1)/2行對應村莊間的距離,每行給出一對正整數,分別是兩個村莊的編號,以及此兩村莊間的距離。爲簡單起見,村莊從1到N編號。
    當N爲0時,輸入結束,該用例不被處理。

輸出:

    對每個測試用例,在1行裏輸出最小的公路總長度。

樣例輸入:
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
樣例輸出:
3
5
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;


int f[1002],u[5000],v[5000],r[5000],w[5000];

int find(int a){
	return a == f[a] ? a : f[a] = find(f[a]);
}
int cmp(const int i,const int j){
	return w[i] < w[j];
}
int main()
{
	int n,m,a,b;
	while(cin >> n && n){
		int ans = 0;
		int m = n * (n - 1) / 2;
		for(int i = 1;i <= n;i++)
			f[i] = i;
		for(int i = 1;i <= m;i++)
			r[i] = i;
		for(int i = 1;i <= m;i++)
			scanf("%d %d %d",&u[i],&v[i],&w[i]);
		sort(r,r + m,cmp);
		for(int i = 1;i <= m;i++){
			int e = r[i];
			int x = find(u[e]);
			int y = find(v[e]);
			if(x != y){
				ans += w[e];
				f[x] = y;
			}
		}
		cout << ans << endl;
	}
	return 1;
}

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;

struct edge{
	int u,v,w;
};
int f[102];
edge e[5000];

int find(int a){	
	return a == f[a] ? a : f[a] = find(f[a]);
}
int cmp(const edge a,const edge b){
	return a.w < b.w;
}
int main()
{
	int n,m;
	while(cin >> n && n){
		int ans = 0;
		m = n * (n - 1) / 2;
		for(int i = 1;i <= n;i++)
			f[i] = i;
		for(int i = 1;i <= m;i++)
			scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].w);
		sort(e,e + m + 1,cmp);
		for(int i = 1;i <= m;i++){

			int x = find(e[i].u);
			int y = find(e[i].v);
			if(x != y){
				ans += e[i].w;
				f[x] = y;
			}
		}
		cout << ans << endl;
	}
	return 1;
}


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