題目背景
奶牛愛乾草
題目描述
Bessie 計劃調查N (2 <= N <= 2,000)個農場的乾草情況,它從1號農場出發。農場之間總共有M (1 <= M <= 10,000)條雙向道路,所有道路的總長度不超過1,000,000,000。有些農場之間存在着多條道路,所有的農場之間都是連通的。
Bessie希望計算出該圖中最小生成樹中的最長邊的長度。
輸入輸出格式
輸入格式:
兩個整數N和M。
接下來M行,每行三個用空格隔開的整數A_i, B_i和L_i,表示A_i和 B_i之間有一條道路長度爲L_i。
輸出格式:
一個整數,表示最小生成樹中的最長邊的長度。
輸入輸出樣例
輸入樣例
3 3
1 2 23
2 3 1000
1 3 43
輸出樣例
43
sx模板題。
代碼如下
#include<iostream>
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
const int size = 2001000;
int f[size];
int find(int x)
{
if(f[x] == x)
return x;
return f[x] = find(f[x]);
}
int n,m;
struct dc
{
int f,t;
ll d;
}l[size];
bool cmp(dc a,dc b)
{
return a.d < b.d;
}
int tot = 0;
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1 ; i <= n ; f[i] = i , i ++);
for(int i = 1 ; i <= m ; i ++)
{
int f,t;
ll d;
scanf("%d%d%lld",&l[i].f,&l[i].t,&l[i].d);
}
sort(l+1,l+m+1,cmp);
ll ans = 0;
for(int i = 1 ; i <= m ; i ++)
{
int x = find(l[i].f);
int y = find(l[i].t);
if(x != y)
{
f[x] = y;
ans = l[i].d;
}
}
cout<<ans;
return 0;
}