POJ 2395 Out of Hay(最小生成樹)

題解:

通過題意我們可以知道,在農場之間尋找最小生成樹,再來找樹中最大路的權值。

代碼如下:

#include <algorithm>
#include  <iostream>
#include   <cstdlib>
#include   <cstring>
#include    <cstdio>
#include    <string>
#include    <vector>
#include    <bitset>
#include     <stack>
#include     <cmath>
#include     <deque>
#include     <queue>
#include      <list>
#include       <set>
#include       <map>
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define line printf("---------------------------\n")
#define mem(a, b) memset(a, b, sizeof(a))
#define pi acos(-1)
using namespace std;
typedef long long ll;
const double eps = 1e-9;
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
const int maxn = 10000+10;

struct Edge {
	int u, v, l;
	friend bool operator < (Edge a, Edge b) {
		return a.l < b.l;
	}
}edge[maxn];
int f[maxn];

int find(int x) {
	if(f[x] == x) {
		return x;
	}
	return f[x] = find(f[x]);
}

int main() {
	int n, m;
	while(cin >> n >> m) {
		for(int i = 1; i <= n; i++) {
			f[i] = i;
		}
		for(int i = 0; i < m; i++) {
			scanf("%d %d %d", &edge[i].u, &edge[i].v, &edge[i].l);
		}
		sort(edge, edge + m);
		int ans = 0;
		for(int i = 0; i < m; i++) {
			int x = find(edge[i].u), y = find(edge[i].v);
			if(x == y) {
				continue;
			}
			f[x] = y;
			ans = max(ans, edge[i].l);
		}
		printf("%d\n", ans);
	}
}

 

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