# 【ZCMU1469】修路(最小生成树)

PS:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <cmath>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define mp make_pair
#define lowbit(x) (x)&(-x)
typedef long long LL;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int maxn = 10000 + 10;
int n,m;
struct Edge{
int u,v,w;
bool operator<(const Edge &a)const;
}edge[maxn];
int pre[500 + 10];
bool Edge::operator<(const Edge &a)const
{
return w < a.w;
}
int findr(int x)
{
if(pre[x] == x)return pre[x];
else return pre[x] = findr(pre[x]);
}
int Kruskal(int s)
{
for( int i = 1; i <= n; i++ )pre[i] = i;
int mx = 0,cnt = 0;
for( int i = s; i < m; i++ ){
int u = edge[i].u,v = edge[i].v,w = edge[i].w;
u = findr(u),v = findr(v);
if(u == v)continue;
pre[u] = v;
cnt++;
mx = max(mx,w);
}
return cnt == n-1 ? mx - edge[s].w: -1;
}
int main()
{
while(~scanf("%d%d",&n,&m)){
for( int i = 0; i < m; i++ ){
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
}
sort(edge,edge+m);
int ans = INF;
int r = m - n + 1;
for( int i = 0; i <= r; i++ ){
int ret = Kruskal(i);
if(ret == -1)continue;
ans = min(ans,ret);
}
printf("%d\n",ans == INF ? -1 : ans);
}
return 0;
}



• 本文已收录于以下专栏：

举报原因： 您举报文章：【ZCMU1469】修路(最小生成树) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)