Hud 1598 find the most comfortable road[枚举 + 并查集]

来源:互联网 发布:淘宝 内容质量分 优质 编辑:程序博客网 时间:2024/06/13 20:33

题目链接:acm.hdu.edu.cn/showproblem.php?pid=1598

题目的意思很是简单。找一条路径,最大速度和最小速度的差值最小。。结点  n <= 200,边m <= 1000。。

根据数据范围,我们可以看出来。。

枚举边的最大值和最小值。。求解答案就可以了。。固定最小值,然后求解满足条件的最大值的最小值。。

判断满足条件的最大值的最小值就是判断连通性就可以。也就是并查集判连通性。。

我们可以发现,有些问题就是根据其数据的大小来找出来其突破口。。

Code:

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <cmath>using namespace std;const int N = 1004;const int INF = 0x3f3f3f3f;struct path{    int x, y;    int v;}p[N];int father[N];int n, m;bool cmp(path a, path b){    if(a.v < b.v) return true;    return false;}void Init(){    for(int i = 1; i <= n; i ++){        father[i] = i;    }}int find(int x){    if(x != father[x]) father[x] = find(father[x]);    return father[x];}void Union(int x, int y){    int a = find(x);    int b = find(y);    if(a != b) father[a] = b;}int main(){    while(~scanf("%d %d", &n, &m)){        for(int i = 0; i < m; i ++){            scanf("%d %d %d", &p[i].x, &p[i].y, &p[i].v);        }        sort(p, p + m, cmp);        int q, st, end;        scanf("%d", &q);        while(q --){            scanf("%d %d", &st, &end);            int ans = INF;            for(int i = 0; i < m; i ++){                Init();                for(int j = i; j < m; j ++){                    Union(p[j].x, p[j].y);                    if(find(st) == find(end)){                        ans = min(ans, p[j].v - p[i].v);                    }                }            }            if(ans == INF) puts("-1");            else printf("%d\n", ans);        }    }    return 0;}


0 0
原创粉丝点击