Idea: first sort all edges by z, and then enumerate them in sequence. During this period, we use and query the set for continuous merging,
It is used to determine whether the start and end can be connected. If yes, It is larger than the current ans;
If ans = inf, start and end cannot form a path.
**************************************** **************************************** **************************************** ********************
#include<algorithm>using namespace std;#define inf 99999999struct node{int x,y;int z;}a[5000];int pre[5000];int find(int k){if(k==pre[k])return k;return pre[k]=find(pre[k]);}int cmp(node a,node b){return a.z<b.z;}int main(){int n,m,t,start,end,f1,f2,ans,i,j;while(scanf("%d%d",&n,&m)!=EOF){for(i=0;i<m;i++)scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);sort(a,a+m,cmp);scanf("%d",&t);while(t--){scanf("%d%d",&start,&end);ans=inf;for(i=0;i<m;i++){for(j=1;j<=n;j++)pre[j]=j;for(j=i;j<m;j++){f1=find(a[j].x);f2=find(a[j].y);if(f1!=f2)pre[f1]=f2;f1=find(start);f2=find(end);if(f1==f2)break;}if(j>=m)break;if(a[j].z-a[i].z<ans)ans=a[j].z-a[i].z;}if(ans==inf)printf("-1\n");elseprintf("%d\n",ans);}}return 0;}