LuoGu 2658 - 汽车拉力比赛(dsu)

## 题意 ##

图中任意两点的距离最小值不大于D,求D的最小值。

## 思路 ##

一开始是想二分的,不过后来据某同学大神说爆栈了。

题解给的思路是并查集,边排序一下,一直合并,直到全部并到一起。

忽然想起来这思路似曾相识啊。 ## 代码 ##

#include <stack>
#include <cstdio>
#include <list>
#include <cassert>
#include <set>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <queue>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#pragma comment(linker, "/STACK:102400000,102400000")
#include <string>
#include <map>
#include <cmath>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(p, num) memset(p, num, sizeof(p))
#define PB push_back
#define X first
#define Y second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define FOR(i, a, b) for (int i=(a); (i) < (b); (i)++)
#define FOOR(i, a, b) for (int i = (a); (i)<=(b); (i)++)
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
const int MAXN = 500*500+10;
const int MOD = 100000007;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
const int seed = 131;
int cases = 0;
typedef std::pair<int, int> pii;
 
struct EDGE
{
    int u, v, w;
    bool operator < (const EDGE &a) const
    {
        return w < a.w;
    }
};
 
vector<EDGE> edges;
int rnk[MAXN], fa[MAXN], n, m, mp[510][510], f[510][510];
 
void add_edge(int x, int y)
{
    for (int i = 0; i < 4; i++)
    {
        int xx = x + dir[i][0], yy = y + dir[i][1];
        if (!xx || !yy || xx > n || yy > m) continue;
        int u = (x-1)*m + y, v = (xx-1)*m + yy;
        edges.push_back((EDGE){u, v, abs(mp[x][y] - mp[xx][yy])});
    }
}
 
int find(int n)
{
    return fa[n] = n == fa[n] ? n : find(fa[n]);
}
 
int main()
{
    //ROP;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
        {
            scanf("%d", &mp[i][j]);
            fa[(i-1)*m+j] = (i-1)*m + j;
        }
    int all = 0;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
        {
            scanf("%d", &f[i][j]);
            add_edge(i, j);
            if (f[i][j] == 1)
            {
                all++;
                rnk[(i-1)*m+j] = 1;
            }
        }
    sort(edges.begin(), edges.end());
    int ans = 0;
    for (int i = 0; i < SZ(edges); i++)
    {
        EDGE e = edges[i];
        int u = e.u, v = e.v;
        int x = find(u), y = find(v);
        if (x == y) continue;
        fa[x] = y;
        ans = max(ans, e.w);
        rnk[y] += rnk[x];
        if (rnk[y] == all)
            break;
    }
    printf("%d\n", ans);
    return 0;
}

Powered by Jekyll and Theme by solid