hdu1598 依旧并查集
809773 | asia2562219 | E | Accepted | 220 KB | 187 ms | C++ | 1786 B | 2012-11-11 12:34:27 |
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 #include <algorithm> 5 #include <iostream> 6 using namespace std; 7 #define MAXN 111111 8 int rank[222],father[222]; 9 int n,m,q; 10 int maxn,minn,ans; 11 struct node 12 { 13 int x,y,speed; 14 }edge[222*222]; 15 bool cmp(node n1,node n2) 16 { 17 return n1.speed > n2.speed; 18 } 19 int Find(int x) 20 { 21 if(father[x]!=x) 22 return father[x] = Find(father[x]); 23 return father[x]; 24 } 25 26 void Union(int x,int y) 27 { 28 if(x==y)return; 29 if(rank[x] > rank[y]) 30 father[y] = x; 31 else 32 { 33 if(rank[x]==rank[y]) 34 rank[y]++; 35 father[x] = y; 36 } 37 } 38 int main() 39 { 40 int i,j,x,y; 41 while(scanf("%d%d",&n,&m)!=EOF) 42 { 43 for(i=0;i<m;i++) 44 { 45 scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].speed); 46 } 47 sort(edge,edge+m,cmp); 48 scanf("%d",&q); 49 while(q--) 50 { 51 scanf("%d%d",&x,&y); 52 ans=11111111; 53 for(i=m-1;i>=0;i--) 54 { 55 for(j=0;j<=n;j++) 56 { 57 rank[j]=0; 58 father[j]=j; 59 } 60 bool flag=false; 61 int temp; 62 for(j=i;j>=0;j--) 63 { 64 Union(Find(edge[j].x),Find(edge[j].y)); 65 if(Find(x)==Find(y)) 66 { 67 flag=true; 68 temp=j; 69 break; 70 } 71 } 72 if(!flag)break; 73 if(ans>edge[temp].speed-edge[i].speed) 74 { 75 ans=edge[temp].speed-edge[i].speed; 76 } 77 } 78 79 if(ans==11111111)ans=-1; 80 printf("%d\n",ans); 81 } 82 83 } 84 return 0; 85 }
光棍节 下午活动去~~