洛谷 P3367 【模板】并查集

这篇文章介绍了使用C++编写的并查集模板代码,处理合并和查找操作,但未提及具体的优化策略。主要涉及数据结构和图算法在单元集合问题中的应用。
摘要由CSDN通过智能技术生成

并没有什么所谓的思路,这里提供一个模板,这里的合并和查找并没有进行优化。

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<cmath> 
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<deque>
#include <iomanip>
#include<sstream>
#include<numeric>
#include<map>
#include<limits.h>
#include<unordered_map>
#include<set>
#define int long long
#define MAX 11000
#define inf 0x3f3f3f3f
#define _for(i,a,b) for(int i=a;i<(b);i++)
using namespace std;
typedef pair<int, int> PII;
int n, m;
int counts;
int dx[] = { 0,1,0,-1};
int dy[] = { 1,0,-1,0 };
int f[MAX];
int find(int x) {
    if (f[x] == x)
        return x;
    else
        return f[x]=find(f[x]);
}
void unit(int x, int y) {
    int s1 = find(x);
    f[s1] = find(y);
}
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        f[i] = i;
    while (m--) {
        int x, y, z;
        cin >> z >> x >> y;
        if (z == 1) {
            unit(x, y);
        }
        else if (z == 2) {
            int s1 = find(x);
            int s2 = find(y);
            if (s1 == s2) {
                cout << "Y" << endl;

            }
            else
                cout << "N" << endl;
        }

    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值