kruskal实现~~
1 #include<iostream> 2 #include<cmath> 3 #include<algorithm> 4 #include<cstdio> 5 using namespace std; 6 #define maxn 760 7 int par[maxn]; 8 int n,m; 9 int len; 10 int cnt; 11 struct node 12 { 13 int x; 14 int y; 15 double w;//!!!可以不开方 16 }; 17 node e[maxn * (maxn - 1) / 2]; 18 int cmp(const node &a , const node &b) 19 { 20 return a.w < b.w; 21 }; 22 void init() 23 { 24 for(int i = 1; i <= n+5; i++) 25 par[i] = i; 26 len = 0; 27 cnt = 0; 28 } 29 int Find(int x) 30 { 31 int k,j,r; 32 r = x; 33 while(par[r] != r) 34 r = par[r]; 35 k = x; 36 while(k != r) 37 { 38 j = par[k]; 39 par[k] = r; 40 k = j; 41 } 42 return r; 43 } 44 int Merge(int x,int y) 45 { 46 int a = Find(x); 47 int b = Find(y); 48 if(a != b) 49 { 50 par[a] = par[b]; 51 return 1; 52 } 53 return 0; 54 } 55 void input() 56 { 57 int u,v; 58 for(int i = 0; i < n; i++) 59 cin>>e[i].x>>e[i].y>>e[i].w; 60 } 61 62 void make() 63 { 64 sort(e,e+n,cmp); 65 for(int i = 0; i < n; i++) 66 { 67 if(Merge(e[i].x,e[i].y)) 68 { 69 len += e[i].w; 70 cnt++; 71 } 72 73 } 74 } 75 int main() 76 { 77 freopen("input.txt","r",stdin); 78 while(cin>>n>>m && n) 79 { 80 init(); 81 input(); 82 make(); 83 if(cnt < m-1) cout<<"?"<<endl; //不能单纯n<m-1 84 else cout<<len<<endl; 85 } 86 87 return 0; 88 }