我想,将速度做一次排序,最后就是多次并查集枚举答案。
因为在排完序之后,减去起点之后的就是本次旅游的最大起伏点,多次枚举求出最小值就是解。
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 205;
const int maxm = 1005;
const int INF = 0xfffffff;
#define min(a,b) ((a)<(b)?(a):(b))
int n,m,start,end;
int ans;
int father[maxn];
struct Edge
{
int st;
int en;
int speed;
}edge[maxm];
bool cmp(Edge x, Edge y )
{
return x.speed < y.speed ;
}
int finds(int x)
{
if(x==father[x]) return x;
else return finds(father[x]);
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=0;i<m;i++) scanf("%d%d%d",&edge[i].st , &edge[i].en , &edge[i].speed );
sort(edge,edge+m,cmp);
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&start,&end);
int mins = INF;
for(i=0;i<m;i++)
{
for(j=1;j<=n;j++) father[j] = j;
for(j=i;j<m;j++)
{
int fx = finds(edge[j].st);
int fy = finds(edge[j].en);
if(fx!=fy) father[fx] = fy;
if(finds(start) == finds(end))
{
mins = min(mins,edge[j].speed - edge[i].speed );
break;
}
}
}
if(mins == INF) printf("-1\n");
else printf("%d\n",mins);
}
}
return 0;
}