标签:style blog class code java color
典型的最小生成树 然后求最大的一条边 附上链接
http://cstest.scu.edu.cn/soj/problem.action?id=4339
需要注意的是有可能有 "IMPOSSIBLE" 的情况
这里用一个flag标记 记录所并的节点 只有flag = n时才能成功 负责就 "IMPOSSIBLE"
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <string> 6 #include <iterator> 7 #include <algorithm> 8 #include <cstdlib> 9 #include <deque> 10 #include <queue> 11 #include <stack> 12 #include <map> 13 #include <vector> 14 #include <set> 15 #include <list> 16 using namespace std; 17 #define PI acos(-1.0) 18 #define INF 0x3f3f3f3f 19 #define MAX 1000005 20 #define MST(a,b) memset(a,b,sizeof(a)) 21 #define MOD 1000000007 22 #define EPS 1e-6 23 typedef long long LL; 24 typedef unsigned long long LLU; 25 int n,m; 26 int r[MAX],u[MAX],v[MAX],w[MAX],p[MAX]; 27 int cmp(const int i,const int j) { 28 return w[i] < w[j]; 29 } 30 int find(int x) { 31 return p[x] == x ? x : p[x] = find(p[x]); 32 } 33 int kruskal() { 34 int ans = 0; 35 for(int i = 0;i < n;i ++) 36 p[i] = i; 37 for(int i = 0;i < m;i ++) 38 r[i] = i; 39 sort(r,r + m,cmp); 40 int flag = 1; 41 for(int i = 0;i < m;i ++) { 42 int e = r[i]; 43 int x = find(u[e]); 44 int y = find(v[e]); 45 if(x != y) { 46 ans = max(ans,w[e]); 47 p[x] = y; 48 flag ++; 49 } 50 } 51 if(flag != n) 52 return 0; 53 return ans; 54 } 55 int main() { 56 while(scanf("%d%d",&n,&m) && (n || m)) { 57 for(int i = 0;i < m;i ++) { 58 int s,t,l; 59 scanf("%d%d%d",&s,&t,&l); 60 w[i]= l; 61 u[i] = s; 62 v[i] = t; 63 } 64 int ans = kruskal(); 65 if(ans) 66 printf("%d\n",ans); 67 else 68 printf("IMPOSSIBLE\n"); 69 } 70 return 0; 71 }
SOJ4339 Driving Range 最小生成树 kruskal算法,布布扣,bubuko.com
SOJ4339 Driving Range 最小生成树 kruskal算法
标签:style blog class code java color
原文地址:http://www.cnblogs.com/mitrenick/p/3707873.html