并查集模板:
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();
}
}