POJ - 2236(并查集模板题)

并查集模板:

int get_par(int a)
{
    if (par[a] != a)
        par[a] = get_par(par[a]);
    return par[a];
}

int query(int a, int b)
{
    return get_par (a) == get_par (b);
}

void Merge(int a, int b)
{
    par[get_par(a)] = get_par(b);//要把a的根节点加到b的根节点
}

题目完整代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>

using namespace std;

const int maxn = 1010;
const int maxm = 1004010;

struct Edge
{
    int v, next;
    Edge(){}
    Edge(int vv, int nn) {
        v = vv;
        next = nn;
    }
};

struct Node
{
    int x;
    int y;
    Node(){}
    Node(int xx, int yy) {
        x = xx;
        y = yy;
    }
};

int d, n;
int cnt;
int par[maxn];
int head[maxn];
int vis[maxn];
Node node[maxn];
Edge e[maxm];

int IsConnected(Node a, Node b)
{
    double dis = (double)(a.x - b.x) * (a.x - b.x) + (double)(a.y - b.y) * (a.y - b.y);
    dis = sqrt (dis);
    if (dis <= d) {
        return 1;
    }
    return 0;
}

void Init()
{
    cnt = 1;
    memset (vis, 0, sizeof(vis));
    memset (head, -1, sizeof(head));
    for (int i = 1; i <= n; i++) {
        par[i] = i;
    }
}

int get_par(int a)
{
    if (par[a] != a)
        par[a] = get_par(par[a]);
    return par[a];
}

int query(int a, int b)
{
    return get_par (a) == get_par (b);
}

void Merge(int a, int b)
{
    par[get_par(a)] = get_par(b);//要把a的根节点加到b的根节点
}

void Add(int u, int v)
{
    e[cnt] = Edge(v, head[u]);
    head[u] = cnt++;
}

int main()
{
    #ifndef ONLINE_JUDGE
    freopen ("in.txt", "r", stdin);
    #endif // ONLINE_JUDGE
    scanf ("%d%d", &n, &d);
    Init ();
    for (int i = 1; i <= n; i++) {
        int x, y;
        scanf ("%d%d", &x, &y);
        node[i] = Node(x, y);
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j < i; j++) {
            if (IsConnected (node[i], node[j])) {
                Add (i, j);
                Add (j, i);
            }
        }
    }
    char c;
    getchar();
    while ((c = getchar()) != EOF) {
        if (c == 'S') {
            int a, b;
            scanf ("%d%d", &a, &b);
            if (!vis[a] || !vis[b] || !query (a, b)) {
                printf ("FAIL\n");
            } else {
                printf ("SUCCESS\n");
            }
        } else {
            int a;
            scanf ("%d", &a);
            vis[a] = 1;
            for (int i = head[a]; i != -1; i = e[i].next) {
                int v = e[i].v;
                if (vis[v] && !query (a, v)) {
                    Merge (v, a);
                }
            }
        }
        getchar();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值