首页 > 代码库 > UVa1395图论之最小生成树
UVa1395图论之最小生成树
//除了套模版之外还有新的思想在其中:枚举。#include <iostream> #include <algorithm> #include <stdio.h> #include <math.h> #include <map> #include <set> #include <vector> #include <string> #include <cstring> #include <sstream> #include <queue> #include <stack> using namespace std; #define input freopen("input.txt","r",stdin) #define output freopen("output.txt","w",stdout) #define For1(i,a,b) for (i=a;i<b;i++) #define For2(i,a,b) for (i=a;i<=b;i++) #define Dec(i,a,b) for (i=a;i>b;i--) #define Dec2(i,a,b) for (i=a;i>=b;i--) #define Sca_d(x) scanf("%d",&x) #define Sca_s(x) scanf("%s",x) #define Sca_c(x) scanf("%c",&x) #define Sca_f(x) scanf("%f",&x) #define Sca_lf(x) scanf("%lf",&x) #define Sca_lu(x) scanf("%I64d",&u) #define Sca_ld(x) scanf("%I64d",&x) #define Fill(x,a) memset(x,a,sizeof(x)) #define inf 99999999 const int maxn=200; const int maxm=20000; int n,m; int p[maxn]; struct Edge { int u,v,w; }edge[maxm]; int find(int x) {return p[x]==x?x:p[x]=find(p[x]);} int cmp(const void *a,const void *b) { Edge *c=(Edge *)a; Edge *d=(Edge *)b; if (c->w!=d->w) return c->w - d->w; } int main() { //input; int i,j,k,l,r,x,y,check,ans; while(cin>>n>>m,m+n) { Fill(edge,0); For2(i,1,m) cin>>edge[i].u>>edge[i].v>>edge[i].w; ans=inf; qsort(edge+1,m,sizeof(edge[0]),cmp); For2(l,1,m)//l控制当前最小边 { int maxedge=0; int minedge=inf; For2(i,0,n) p[i]=i; r=l; check=0; while((check<n-1)&&(r<=m)) { int &u=edge[r].u; int &v=edge[r].v; x=find(u); y=find(v); if (x!=y) { p[x]=y; check++; maxedge=max(maxedge,edge[r].w); minedge=min(minedge,edge[r].w); } r++; } if (check==n-1) ans=min(ans,maxedge-minedge); } if (ans==inf) puts("-1"); else cout<<ans<<endl; } return 0; }
UVa1395图论之最小生成树
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。