find the most comfortable road
/*********
题目:HDU1598 find the most comfortable road (枚举+kk或并查集)
题意:求最小差值(中文题)
思路:将边集进行排序,然后枚举所有从小到大的边,求一个最小的差值,如果图不连通,则-1
*********/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
const int maxn = 205;
const int maxm = 1005;
int n,m;
int father[maxn];
struct node
{
int u,v,w;
bool operator <(const node& a)const{
return w<a.w;
}
}edge[maxm];
int Find(int x)
{
if(father[x]==x) return father[x];
return father[x]=Find(father[x]);
}
void Union(int x,int y)
{
int fa=Find(x);
int fb=Find(y);
if(fa!=fb) father[fa]=fb;
}
int main()
{
while(~scanf("%d%d",&n,&m)){
for(int i=0;i<m;i++){
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
}
sort(edge,edge+m);
int q;
scanf("%d",&q);
while(q--){
int s,e,ans=inf;
scanf("%d%d",&s,&e);
for(int i=0;i<m;i++){
for(int j=0;j<=n;j++) father[j]=j;
for(int j=i;j<m;j++){
Union(edge[j].u,edge[j].v);
if(Find(s)==Find(e)){
ans=min(ans,edge[j].w-edge[i].w);
break;
}
}
}
printf("%d\n",ans==inf?-1:ans);
}
}
return 0;
}