Topic link: HDU1598 find the most comfortable road
Question: Ask the minimum value of mx-mn on all paths of xy;
Analysis: Enumerate each edge as the minimum edge of the minimum spanning tree, and update the answer until xy is connected. Use the current-minimum edge to update. It may happen that the useless edge is included in the answer, but the answer will be changed to a smaller value later, so Does not affect
#include<bits/stdc++.h>
#define pb push_back
using namespace std;
typedef long long ll;
const int maxn=2e5+7;
const int mod=1e9+7;
const int INF=0x7f7f7f7f;
int n,m,u,v,pre[maxn];
struct node{int x,y,z;} p[maxn];
bool cmp(node a,node b) {return a.z<b.z;}
int find(int x) {return (x==pre[x])?x:pre[x]=find(pre[x]);}
void merge(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx!=fy) pre[fx]=fy;
}
int check(int x)
{
int cnt=0;
for(int i=0;i<=n;i++) pre[i]=i;
for(int i=x;i<=m;i++)
{
int xx=p[i].x,yy=p[i].y;
merge(xx,yy);
if(find(u)==find(v)) return p[i].z-p[x].z;
}
return INF;
}
void rua()
{
for(int i=1;i<=m;i++)scanf("%d%d%d",&p[i].x,&p[i].y,&p[i].z);
sort(p+1,p+1+m,cmp);
int q;scanf("%d",&q);
while(q--)
{
int ans=INF;
scanf("%d%d",&u,&v);
for(int i=1;i<=m;i++) ans=min(ans,check(i));
if(ans==INF) ans=-1;
printf("%d\n",ans);
}
}
int main()
{
while(~scanf("%d%d",&n,&m)) rua();
return 0;
}