【最小生成树】BZOJ1682[Usaco2005 Mar]-Out of Hay 干草危机
...最小生成树裸题,9月最后一天刷水刷水。
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 using namespace std; 5 const int MAXM=10000+50; 6 const int MAXN=2000+50; 7 struct Rec 8 { 9 int ori,des,len; 10 bool operator < (const Rec &x) const 11 { 12 return len<x.len; 13 } 14 }edge[MAXM]; 15 int par[MAXN],height[MAXN]; 16 int n,m; 17 int ans; 18 19 void initset() 20 { 21 for (int i=1;i<=n;i++) 22 { 23 par[i]=i; 24 height[i]=0; 25 } 26 } 27 28 int find(int x) 29 { 30 int r=x,temp; 31 while (par[r]!=r) r=par[r]; 32 while (x!=r) 33 { 34 temp=par[x]; 35 par[x]=r; 36 x=temp; 37 } 38 return (r); 39 } 40 41 void unionset(int fa,int fb) 42 { 43 if (height[fa]>=height[fb]) 44 { 45 par[fb]=fa; 46 if (height[fa]==height[fb]) height[fa]++; 47 } 48 else 49 par[fa]=fb; 50 } 51 52 void init() 53 { 54 scanf("%d%d",&n,&m); 55 for (int i=0;i<m;i++) 56 { 57 int u,v,w; 58 scanf("%d%d%d",&u,&v,&w); 59 edge[i].ori=u; 60 edge[i].des=v; 61 edge[i].len=w; 62 } 63 } 64 65 void solve() 66 { 67 sort(edge,edge+m); 68 initset(); 69 ans=0; 70 for (int i=0;i<m;i++) 71 { 72 int fa=find(edge[i].ori); 73 int fb=find(edge[i].des); 74 if (fa!=fb) 75 { 76 unionset(fa,fb); 77 ans=max(ans,edge[i].len); 78 } 79 } 80 printf("%d",ans); 81 } 82 83 int main() 84 { 85 init(); 86 solve(); 87 return 0; 88 }