接下来Q行每行有2个正整数Start,End, 表示寻路的起终点。
Output 每一个寻路要求打印一行,仅输出一个非负整数表示最佳路线的舒适度最快速与最低速的差。假设起点和终点不能到达。那么输出-1。 Sample Input 4 4 1 2 2 2 3 4 1 4 1 3 4 2 2 1 3 1 2 Sample Output 1 0暴力寻找每已排好序的边 的最小生成树。起点和终点在最小生成树里就更新答案。
#include <stdio.h> #include <string.h> #include <algorithm> #include <math.h> #include <iostream> #include <string> #include <map> #include <stack> #define lson o<<1, l, m #define rson o<<1|1, m+1, r using namespace std; typedef long long LL; const int maxn = 105; const int MAX = 0x3f3f3f3f; const int mod = 1000000007; int n, m, q, fa[205]; struct C { int v, w, num; } ed[1005]; int Find(int x) { return x == fa[x] ? x : fa[x] = Find(fa[x]); } bool cmp(C x, C y) { return x.num < y.num; } int main() { while(~scanf("%d%d", &n, &m)) { for(int i = 0; i < m; i++) scanf("%d%d%d", &ed[i].v, &ed[i].w, &ed[i].num); sort(ed, ed + m, cmp); scanf("%d", &q); while(q--) { int st, en, ans = MAX; scanf("%d%d", &st, &en); for(int k = 0; k < m; k++) { for(int i = 1; i <= n; i++) fa[i] = i; for(int i = k; i < m; i++) { int px = Find(ed[i].v), py = Find(ed[i].w); if(px != py) fa[px] = py; if(Find(st) == Find(en)) { ans = min(ans, ed[i].num - ed[k].num); break; } } } if(ans == MAX) printf("-1\n"); else printf("%d\n", ans); } } return 0; } 版权声明:本文博主原创文章。博客,未经同意不得转载。
转载于:https://www.cnblogs.com/bhlsheji/p/4810194.html