對邊做一個排序,然後對於每一個詢問,每次都去枚舉權值最小的邊,再做最小生成樹,一旦詢問中的點聯通了,我們就可以認爲在當前最小邊權值的情況下,舒適度最大的情況已經達到了。
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
#include<cmath>
using namespace std;
int fa[210],n,m,q;
struct node{
int x,y,w;
bool operator < (const node &n) const {return w<n.w;}
}edge[1010];
int find(int x)
{
if (fa[x]!=x) fa[x]=find(fa[x]);
return fa[x];
}
int join(int a,int b)
{
int ret=0;
int fx=find(a); int fy=find(b);
if (fx!=fy)
{
fa[fx]=fy;
ret=1;
}
return ret;
}
int main()
{
while (~scanf("%d%d",&n,&m))
{
for (int i=1; i<=m; i++)
{
scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].w);
}
sort(edge+1,edge+1+m);
scanf("%d",&q);
for (int i=1; i<=q; i++)
{
int a,b; scanf("%d%d",&a,&b);
int ans=1000000;
for (int j=1; j<=m; j++)
{
//cout<<"j="<<edge[j].w<<endl;
int tmp=-1;
for (int k=1; k<=n; k++)
{
fa[k]=k;
}
for (int k=j; k<=m; k++)
{
//cout<<"k="<<edge[k].w<<endl;
join(edge[k].x,edge[k].y);
//cout<<"1="<<edge[k].x<<" 2="<<edge[k].y<<endl;
if (find(a)==find(b))
{
tmp=edge[k].w-edge[j].w;
//cout<<"tmp="<<tmp<<endl;
break;
}
}
if (tmp!=-1) ans=min(ans,tmp);
}
if (ans==1000000) printf("-1\n");
else printf("%d\n",ans);
}
}
return 0;
}