标签:hdu1598 find the most comfor 并查集
4 4 1 2 2 2 3 4 1 4 1 3 4 2 2 1 3 1 2
1 0
#include <cstdio> #include <algorithm> #define MAX 1010 #define INF 1000000000 using namespace std ; struct Node{ int x , y , s ; }edge[MAX]; bool cmp(const Node &a , const Node &b) { return a.s<b.s ; } int f[250] ; void init(int n) { for(int i = 0 ; i <= n ; ++i) { f[i] = i ; } } int find(int x) { int r = x ; while(r != f[r]) { r = f[r] ; } int temp ; while(x != f[x]) { temp = f[x] ; f[x] = r ; x = temp ; } return r ; } void join(int x, int y) { int fx = find(x) ; int fy = find(y) ; if(fx != fy) { f[fx] = fy ; } } int min(int a , int b) { return a>b?b:a ; } int main() { int n , m ; while(~scanf("%d%d",&n,&m)) { for(int i = 0 ; i < m ; ++i) { scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].s) ; } sort(edge,edge+m,cmp) ; int q ; scanf("%d",&q) ; while(q--) { int x , y ; scanf("%d%d",&x,&y) ; int ans = INF ; for(int i = 0 ; i < m ; ++i) { init(n) ; int t = INF ; for(int j = i ; j < m ; ++j) { join(edge[j].x,edge[j].y) ; if(find(x)==find(y)) { ans = min(ans,edge[j].s-edge[i].s) ; break ; } } } if(ans == INF) { puts("-1") ; } else { printf("%d\n",ans) ; } } } return 0 ; }
hdu 1598 find the most comfortable road 一开始把此题当做最短路。。后来发现不行。。并查集+枚举
标签:hdu1598 find the most comfor 并查集
原文地址:http://blog.csdn.net/lionel_d/article/details/44725371