Wall Game并查集

题目链接

题意 :
n组输入,每组输入三个数字,第一个数字代表操作类型, 第二三个数字代表坐标。
操作1:在整个图上添加点,并和相邻的点联通
操作2:查询这个点的整个联通的快,输出整个块的边的数量

思路 :
对于图上加点,可以给每个点的坐标离散化成序号,然后丢到并查集维护连通性。
对于输出联通块边的数量,维护一下每个集合内点的数量和重复边的数量,*6-v输出即可。

AC代码 :

#include <iostream>
#include <map>
#include <cstring>
#include <algorithm>
#include <math.h>
#include <utility>

#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;

typedef pair<int,int > PII;
const int N = 5e5 + 10;

int pre[N];
int num[N], rpp[N];

void init(int n){
    for (int i = 0; i <= n; i++)
        pre[i] = i;
}

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

void merge(int x, int y){
    int fx = find(x);
    int fy = find(y);
    if (fx != fy)
        pre[fx] = fy;
}

int cnt = 0;
map<PII, int> mp;
int dx[] = {1, 1, 0, 0, -1, -1};
int dy[] = {0, -1, -1, 1, 0, 1};

int main()
{
    IOS;
    int T;
    cin >> T;
    init(T + 1);
    while (T--)
    {
        int op, x, y;
        cin >> op >> x >> y;
        if (op == 1)
        {
            mp[(PII){x, y}] = ++cnt;
            num[cnt] = 1;
            rpp[cnt] = 0;
            for (int i = 0; i < 6; i++)
            { 
                int nx = x + dx[i], ny = y + dy[i];
                if (!mp.count((PII){nx, ny}))
                    continue;
                int old = find(mp[(PII){nx, ny}]); 
                if (old != cnt)
                {
                    pre[old] = cnt;
                    rpp[cnt] += rpp[old] + 2;
                    num[cnt] += num[old];
                }
                else
                {
                    rpp[cnt] += 2;
                }
            }
        }
        else
        {
            PII t = (PII){x, y};
            if (!mp.count(t))
                cout << 6 << "\n";
            else
            {
                int x = find(mp[t]);
                cout << num[x] * 6 - rpp[x] << "\n";
            }
        }
    }
    return 0;
}

/*
8
1 0 0
2 0 0
1 0 2
1 1 2
1 0 3
2 0 3
1 0 1
2 0 0
*/

相关文章

学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习...
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面...
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生...
Can’t connect to local MySQL server through socket \'/v...
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 ...
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服...