#A. 道路修建
题意:
生成树,满足最大边权减最小边权最小(n ≤ m ≤ 5000)
分析:
排序后1 ~ n-m-1每个边作为最小值,跑一边最小生成树就行
细节:
无
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll n,m,dis[1000000],vis[1000000],fa[1000000];
ll head[1000000],tot;
struct od{
ll x;
ll y;
ll z;
}sr[1000000];
struct nood{
ll v;
ll w;
ll nxt;
}es[1000000];
//void adde(ll x,ll y,ll w){
// es[++tot].v=y,es[tot].w=w,es[tot].nxt=head[x],head[x]=tot;
// es[++tot].v=x;es[tot].w=w;es[tot].nxt=head[y],head[y]=tot;
//}
bool cmp(od x,od y){
return x.z<y.z;
}
ll find(ll x){
if(fa[x]==x){
return x;
}
else{
return fa[x]=find(fa[x]);
}
}
void ad(ll x,ll y){
ll xx=find(x);
ll yy=find(y);
if(xx!=yy){
fa[xx]=yy;
}
}
ll kru(ll st){
ll ma=0;
ll mi=1e18;
ll cnt=0;
for(int i=st;i<=m;i++){
ll ru=sr[i].x;
ll rv=sr[i].y;
if(find(ru)!=find(rv)){//没有回路
ad(ru,rv);
ma=max(ma,sr[i].z);
mi=min(mi,sr[i].z);
cnt++;
}
if(cnt==n-1){
//cout<<ma<<"*"<<mi<<endl;
return ma-mi;
}
}
return 1e18;
}
int main(){
cin>>n>>m;
for(int i=1;i<=m;i++){
cin>>sr[i].x>>sr[i].y>>sr[i].z;
}
sort(sr+1,sr+m+1,cmp);
ll anss=1e18;
for(int i=1;i<=m-n+1;i++){
for(int j=1;j<=n;j++){
fa[j]=j;
dis[j]=1e18;
vis[j]=0;
}
anss=min(anss,kru(i));
}
cout<<anss;
}
标签:head,sr,ll,tot,修建,道路,1000000,es
From: https://www.cnblogs.com/Misty-post/p/18434310