4 4 1 2 2 2 3 4 1 4 1 3 4 2 2 1 3 1 2
1 0
分析:先按照速度从小到大排序,然后从当前i开始到n建立并查集,直到初始和目的形成连接,然后与ans比较
代码:
/*hdoj 1598*/ #include <stdio.h> #include <string.h> #include <algorithm> #define M 1005 #define INF 0x3f3f3f3f using namespace std; struct node{ int from, to, sp; }s[M]; int fat[M], n, m; int f(int x){ if(fat[x] != x) fat[x] = f(fat[x]); return fat[x]; } int cmp(node a, node b){ return a.sp<b.sp; } int main(){ int i, a, b, c, j, q; while(scanf("%d%d", &n, &m) == 2){ for(i = 0; i < m; i ++) scanf("%d%d%d", &s[i].from, &s[i].to, &s[i].sp); sort(s, s+m, cmp); scanf("%d", &q); while(q --){ int ans = INF; scanf("%d%d", &a, &b); for(i = 0; i < m; i ++){ for(j = 1; j <= n; j ++) fat[j] = j; for(j = i; j < m; j ++){ int x = f(s[j].from); int y = f(s[j].to); if(x!=y) fat[x] = y; if(f(a) == f(b)){ ans = min(ans, s[j].sp-s[i].sp); break; } } } if(ans == INF) printf("-1\n"); else printf("%d\n", ans); } } return 0; }
hdoj 1598 find the most comfortable road 【并查集】+【暴力枚举】
原文:http://blog.csdn.net/shengweisong/article/details/41056839