poj 2236 Wireless Network(并查集)

思路:简单并查集,当两个点距离<=d则建立连接。

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

#define MAXN 1024

int fa[MAXN];

int x[MAXN],y[MAXN];
bool repaired[MAXN];

int set_find(int d)
{
    if(fa[d]<0)return d;
    return fa[d]=set_find(fa[d]);
}

void set_join(int x,int y)
{
    x=set_find(x);
    y=set_find(y);
    if(x!=y)fa[x]=y;
}

int main()
{

    int N,d;
    char str[3];
    int p,q;

    while(~scanf("%d%d",&N,&d))
    {

        memset(fa,-1,sizeof(fa));
        memset(repaired,false,sizeof(repaired));

        for(int i=1; i<=N; ++i)
        {
            scanf("%d%d",&x[i],&y[i]);
        }

        while(~scanf("%1s",str))
        {
            if(str[0]=='O')
            {
                scanf("%d",&p);
                repaired[p]=true;
                for(int i=1; i<=N; ++i)
                {
                    if(repaired[i]&& ((x[p]-x[i])*(x[p]-x[i])+(y[p]-y[i])*(y[p]-y[i])<=d*d) )
                    {
                        set_join(p,i);
                    }
                }
            }
            else
            {
                scanf("%d%d",&p,&q);
                p=set_find(p);
                q=set_find(q);
                if(p==q)
                {
                    printf("SUCCESS\n");
                }
                else
                {
                    printf("FAIL\n");
                }
            }
        }
    }
    return 0;
}


你可能感兴趣的:(poj 2236 Wireless Network(并查集))