POJ - 2031 Building a Space Station(Kruskal)

題目連接:

  https://vjudge.ppsucxtt.cn/problem/POJ-2031node

思路:

    直接用Kruskal算法,已有的邊直接提早用並查集維護,把後面Kruskal中加入的邊記錄到res數組中便可。

代碼:

#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iomanip>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

const int N = 800;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

struct node
{
    int l, r;
    double w;
    bool operator<(const node &u) const
    {
        return w < u.w;
    }
} a[N * N];

PII b[N];
vector<PII> res;
int n, m, idx, k;
int f[N];

int find(int x)
{
    if (x != f[x])
        f[x] = find(f[x]);
    return f[x];
}

void Kruskal()
{
    sort(a + 1, a + idx + 1);
    for (int i = 1; i <= idx; i++)
    {
        int f1 = find(a[i].l), f2 = find(a[i].r);
        if (f1 != f2)
        {
            PII t;
            t.first = a[i].l, t.second = a[i].r;
            res.push_back(t);
            k--;
            f[f1] = f2;
        }
        if (!k)
            break;
    }
}

int main()
{
    fastio;

    cin >> n;
    k = n;
    for (int i = 1; i <= n; i++)
        f[i] = i;
    for (int i = 1; i <= n; i++)
        cin >> b[i].first >> b[i].second;
    for (int i = 1; i <= n; i++)
        for (int j = i + 1; j <= n; j++)
        {
            a[++idx].l = i, a[idx].r = j;
            a[idx].w = sqrt((b[i].first - b[j].first) * (b[i].first - b[j].first) + (b[i].second - b[j].second) * (b[i].second - b[j].second));
        }
    cin >> m;
    for (int i = 1; i <= m; i++)
    {
        int l, r;
        cin >> l >> r;
        int f1 = find(l), f2 = find(r);
        if (f1 != f2)
        {
            k--;
            f[f1] = f2;
        }
    }
    if (!k)
        cout << "";
    else
    {
        Kruskal();
        sort(res.begin(), res.end());
        for (int i = 0; i < res.size(); i++)
            cout << res[i].first << ' ' << res[i].second << endl;
    }
    return 0;
}
相關文章
相關標籤/搜索