去你妹的并查集,没纠结死我!按速度排序,然后枚举所有的路,知道find(start) == find(end)结束。然后用最大值减去最小值,求其差,取差最小。
Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 1024;
const int inf = 0x6fffffff;
class node {
public:
int x, y, s;
friend bool operator < (node a, node b) {
return a.s < b.s;
}
}g[N];
int f[N];
int find(int x) {
int k, r, j;
r = k = x;
while(r != f[r]) r = f[r];
while(k != r) {j = f[k]; f[k] = r; k = j;}
return r;
}
int main() {
//freopen("data.in", "r", stdin);
int n, m, min, i, j, q;
int s, e, x, y;
while(~scanf("%d%d", &n, &m)) {
for(i = 0; i < m; i++) {
scanf("%d%d%d", &g[i].x, &g[i].y, &g[i].s);
}
sort(g, g+m);
scanf("%d", &q);
while(q--) {
scanf("%d%d", &s, &e);
for(min = inf, i = m-1; i >= 0; i--) {
for(j = 0; j <= n; j++) f[j] = j;
for(j = i; j >= 0; j--) {
x = find(g[j].x);
y = find(g[j].y);
if(x != y) f[x] = f[y];
if(find(s) == find(e)) break;
}
if(j >= 0 && min > g[i].s - g[j].s)
min = g[i].s - g[j].s;
}
if(min == inf) {printf("-1\n"); continue;}
printf("%d\n", min);
}
}
return 0;
}