poj 2236 - Wireless Network(并查集)

思路:

       并查集,假如两两都可以联通的所有的节点就加入到一个集合当中。最后查询只需查询他们是否在一个集合中即可。

代码如下:

const int M = 1005;
vector<int> g[M];
struct Point
{
    int x, y;
    int readPoint()
    {
        return scanf("%d%d", &x, &y);
    }
}point[M];
int flag[M], p[M];
int find(int x) { return p[x]==x?x:p[x]=find(p[x]); }
int dis(Point a, Point b){ return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y); }
char get_char(char &tmp)
{
    while(~scanf("%c", &tmp)) if(tmp=='O'||tmp=='S') return tmp;
    return -1;
}
int main()
{
    int n, d, a, b;
    scanf("%d%d", &n, &d);
    for(int i = 1; i <= n; ++i) point[i].readPoint();
    for(int i = 1; i <= n; ++i) p[i] = i;
    for(int i = 1; i <= n; ++i)
        for(int j = i+1; j <= n; ++j)
            if(dis(point[i],point[j]) <= d*d ) g[i].push_back(j), g[j].push_back(i);
    char o;
    int tmp;
    while(~get_char(o))
    {
        if(o=='O')
        {
            scanf("%d", &a);
            for(int i = 0; i < (int)g[a].size(); ++i)
            {
                tmp = g[a][i];
                if(flag[tmp])
                {
                    int x = find(a);
                    int y = find(tmp);
                    p[x] = y;
                }
            }
            flag[a] = 1;
        }
        else
        {
            scanf("%d%d", &a, &b);
            int x = find(a);
            int y = find(b);
            if(x==y) puts("SUCCESS");
            else puts("FAIL");
        }
    }
    return 0;
}


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