hdu1598

 
  
#include 
#include 
#include 
#include 

using namespace std;

const int M = 1005;
int Set[M];
struct node {

    int x;
    int y;
    int v;
};

node s[M];

int n, m;

bool cmp(node p1, node p2) {

    return p1.v < p2.v;
}

void init() {

    for(int i = 1; i <= n; i++) {

        Set[i] = i;
    }
}

int Find(int x) {

    return x == Set[x] ? x : Set[x] = Find(Set[x]);
}

int main()
{
   int a, b, d;
   int k, s1, e;

   while(scanf("%d%d", &n, &m) != EOF) {

        for(int i = 0; i < m; i++) {

            scanf("%d%d%d", &a, &b, &d);
             s[i].x = a;
             s[i].y = b;
             s[i].v = d;
        }
        sort(s, s+m, cmp);
        scanf("%d", &k);

        for(int z = 0; z < k; z++) {

            scanf("%d%d", &s1, &e);
            int maxn = 9999999;
            for(int i = 0; i < m; i++) {

                init();
                for(int j = i; j < m; j++) {

                    a = Find(s[j].x);
                    b = Find(s[j].y);
                    if(a != b) {

                        Set[a] = b;
                    }
                    if(Find(s1) == Find(e)) {

                        maxn = min(maxn, s[j].v - s[i].v);
                    }
                }
            }
            if(maxn == 9999999)
                printf("-1\n");
            else
                printf("%d\n", maxn);

        }
   }
    return 0;
}


 
  
 
 

你可能感兴趣的:(并查集)