This problem is a template problem with the Kruskal algorithm in the minimal spanning tree.
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include < queue>using namespace Std;const int n=1002;const int m=15002;const int inf=1<<28;struct edge{int u,v,cost;} Es[m];int father[n],deep[n];int n,m;void Init () {for (int i=0;i<n;i++) {father[i]=i; deep[i]=0; }}int find_father (int x) {if (x!=father[x]) Father[x]=find_father (father[x]); return father[x];} BOOL _merge (int a,int b) {int x=find_father (a); int Y=find_father (b); if (x==y) return true; if (Deep[x]<deep[y]) father[x]=y; else {if (deep[x]==deep[y]) deep[x]++; Father[y]=x; } return false;} BOOL CMP (Edge A,edge b) {return a.cost<b.cost;} void Kruskal () {int cnt=0,_max=0; Queue<int> Q; Init (); for (int i=1;i<=m;i++) {if (!_merge (ES[I].U,ES[I].V)) {Cnt++,q.push (i); if (_max<es[i].cost) _Max=es[i].cost; } if (cnt==n-1) break; } printf ("%d\n", _max); int len=q.size (); printf ("%d\n", Len); for (int i=0;i<len;i++) {int Id=q.front (); Q.pop (); printf ("%d%d\n", ES[ID].U,ES[ID].V); }}int Main () {while (scanf ("%d%d", &n,&m)!=eof) {for (int i=1;i<=m;i++) scanf ("%d%d%d", &A Mp;es[i].u,&es[i].v,&es[i].cost); Sort (es+1,es+m+1,cmp); Kruskal (); } return 0;}
POJ 1861 Network