4 4 1 2 2 2 3 4 1 4 1 3 4 2 2 1 3 1 2
1 0
数据比较弱,暴力枚举+并查集就过了。
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define inf 0x3f3f3f3f using namespace std; struct node { int a,b,c; }; node map[1100]; int cmp(node s1,node s2){ return s1.c < s2.c; } int per[220]; int n,m; int find(int x){ if(per[x] == -1) return x; return per[x] = find(per[x]); } int main (){ while(scanf("%d %d", &n, &m)!=EOF){ for(int i = 1; i <= m; ++i) scanf("%d %d %d", &map[i].a, &map[i].b, &map[i].c); sort(map + 1, map + 1 + m, cmp); int Q; scanf("%d", &Q); int st,ed; while(Q--){ int MIN = inf; scanf("%d %d",&st, &ed); for(int i = 1; i <= m; ++i){ //枚举最小边,再从小到大一直加大于等于这个最小边的其他边,直到起点跟终点属于同一个集合为止,然后用最大边-最小边的差 memset(per, -1, sizeof(per)); for(int j = i; j <= m; ++j){ int fa = find(map[j].a); int fb = find(map[j].b); if(fa != fb) per[fb] = fa; if(find(st) == find(ed)){ MIN = min(MIN, map[j].c - map[i].c); break; } } } if(MIN == inf) printf("-1\n"); else printf("%d\n", MIN); } } return 0; }