UVA 10457 - Magic Car(并查集)

题目链接:点击打开链接

思路:

由于M只有1000, 我们可以从小到大枚举最小边, 用并查集维护连接情况, 当s和t连接时, 这时的边就是最大边。 复杂度O(m^2)

细节参见代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <ctime>
#include <bitset>
#include <cstdlib>
#include <cmath>
#include <set>
#include <list>
#include <deque>
#include <map>
#include <queue>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
typedef long double ld;
const double eps = 1e-6;
const double PI = acos(-1);
const int mod = 1000000000 + 7;
const int INF = 0x3f3f3f3f;
const ll INF64 = ll(1e18);
const int maxn = 1000 + 10;
int T,n,m,k,u,v,s, t, p[maxn];
struct node {
    int a, b, c;
    node(int a=0, int b=0, int c=0):a(a), b(b), c(c) {}
    bool operator < (const node& rhs) const {
        return c < rhs.c;
    }
}a[maxn];
int _find(int x) { return p[x] == x ? x : p[x] = _find(p[x]); }
int main() {
    while(~scanf("%d%d",&n, &m)) {
        for(int i = 0; i < m; i++) {
            scanf("%d%d%d", &a[i].a, &a[i].b, &a[i].c);
        }
        sort(a, a+m);
        scanf("%d%d", &v, &u);
        scanf("%d", &k);
        while(k--) {
            scanf("%d%d", &s, &t);
            int ans = INF;
            for(int i = 0; i < m; i++) {
                for(int j = 1; j <= n; j++) p[j] = j;
                for(int j = i; j < m; j++) {
                    int x = _find(a[j].a);
                    int y = _find(a[j].b);
                    if(x != y) {
                        p[x] = y;
                        x = _find(s);
                        y = _find(t);
                        if(x == y) {
                            ans = min(ans, a[j].c - a[i].c);
                            break;
                        }
                    }
                }
            }
            printf("%d\n", ans + u + v);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值