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
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值