Title: http://acm.hdu.edu.cn/showproblem.php?pid=1598
Https://zh.wikipedia.org/wiki/%E5%B9%B6%E6%9F%A5%E9%9B%86
Http://www.cnblogs.com/nanke/archive/2012/02/13/2350008.html
Think and find a way to use
For the road in question, sort by speed, so that if all the roads from route I to J are able to connect I and J, then there is a way, and the comfort of the road is the difference between the two. This way, as long as the enumeration starts at each road and finds the comfort of the road where the starting and ending points can be connected, you can find the answer.
Code:
1#include <iostream>2#include <algorithm>3 using namespacestd;4 structEdge5 {6 intu,v,w;7}e[1001];8 intf[201],n,m;9 BOOLcmp (Edge A,edge B)Ten { One returna.w<B.W; A } - voidInit () - { the for(intI=0; i<=n;i++) -f[i]=i; - } - intFindintx) + { - if(x==F[x]) + returnF[x]; Af[x]=find (F[x]); at returnF[x]; - } - voidUnion (intXinty) - { - intA=find (x); - intb=find (y); in if(a==b) - return; tof[a]=b; + } - intMain () the { * intQ; $ while(SCANF ("%d%d", &n,&m) = =2)Panax Notoginseng { - for(intI=0; i<m;i++) thescanf" %d%d%d",&e[i].u,&e[i].v,&E[I].W); +Sort (e,e+m,cmp); Ascanf"%d",&Q); the while(q--) + { - intx, y; $ intans=Int_max; $scanf"%d%d",&x,&y); - for(intI=0; i<m;i++) - { the init (); - intflag=0, k=0;Wuyi for(intj=i;j<m;j++) the { - //cout<<e[j].u<< ' <<e[j].v<<endl; Wu Union (E[J].U,E[J].V); - if(Find (x) = =find (y)) About { $flag=1; -k=J; - Break; - } A //cout<<find (x) << ' <<find (y) <<endl; + } the if(!flag) Break; -Ans=min (ans,e[k].w-E[I].W); $ } the if(ans==Int_max) theprintf"-1\n"); the Elseprintf"%d\n", ans); the } - } in return 0; the}
and check Set