链接:http://poj.org/problem?id=1861
最小生成树裸题,输出生成树的最长边、节点个数、节点坐标。另外OJ上样例输出时错的,4个点的最小生成树怎么可能4条边。。
主要是熟悉手写kruskal
#include<cstring> #include<string> #include<fstream> #include<iostream> #include<iomanip> #include<cstdio> #include<cctype> #include<algorithm> #include<queue> #include<map> #include<set> #include<vector> #include<stack> #include<ctime> #include<cstdlib> #include<functional> #include<cmath> using namespace std; #define PI acos(-1.0) #define MAXN 20010 #define eps 1e-7 #define INF 0x7FFFFFFF #define seed 131 #define ll long long #define ull unsigned ll #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 struct node{ int u,v,dis; }edge[MAXN]; int father[1010],point[1010][2]; int n,m,ans,sum; bool cmp(node x,node y){ return x.dis<y.dis; } int find(int x){ int t = x; while(t!=father[t]){ t = father[t]; } int k = x; while(k!=t){ int temp = father[k]; father[k] = t; k = temp; } return t; } void kruskal(){ int i,j=0; for(i=1;i<=n;i++) father[i] = i; for(i=0;i<m;i++){ int a = find(edge[i].u); int b = find(edge[i].v); if(a!=b){ father[a] = b; point[j][0] = edge[i].u; point[j][1] = edge[i].v; sum+=edge[i].dis; ans = edge[i].dis; j++; if(j>=n-1) break; } } } int main(){ int i,j; while(scanf("%d%d",&n,&m)!=EOF){ sum = 0; for(i=0;i<m;i++){ scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].dis); } sort(edge,edge+m,cmp); kruskal(); printf("%d\n%d\n",ans,n-1); for(i=0;i<n-1;i++){ printf("%d %d\n",point[i][0],point[i][1]); } } return 0; }
POJ1861&ZOJ1542--Network【最小生成树】
时间: 2024-10-19 05:00:13