首页 > 编程语言 >二分算法

二分算法

时间:2023-08-27 23:47:01浏览次数:26  
标签:二分 int 节点 算法 编号 集合 include find

  1. 将两个集合合并

  2. 询问两个元素是否在一个集合当中

基本原理:每个集合用一棵树表示,树根的编号就是整个集合的编号。每个节点储存它的父节点,p[x]表示x的父节点

判断树根(属于那个集合)if (p[x] == x)
求x的集合编号:while(p[x] != x) x = p[x];
合并两个集合:px是x的集合编号,py是y的集合编号。p[x] = y,(直接将一棵树插到另一颗树下面)

模板:

1
#include<iostream>
2
#include<algorithm>
3
using namespace std;
4
​
5
const int N = 1e5 + 10;
6
​
7
int n,m;
8
int p[N];
9
​
10
// 返回x的祖宗节点 + 路径优化
11
int find(int x) {
12
    if (p[x] != x) p[x] = find(p[x]);
13
    return p[x];
14
}
15
int main()
16
{
17
    cin >> n >> m;
18
    for (int i = 1; i <= n; i++) p[i] = i; // 初始化树根p[x] = x
19
​
20
    while (m--) {
21
        char op[2];
22
        int a, b;
23
        cin >> op >> a >> b;
24
        if (op[0] == 'M') p[find(a)] = find(b);
25
        else {
26
            if (find(a) == find(b)) cout << "Yes" << endl;
27
            else cout << "No" << endl;
28
        }
29
    }
30
    return 0;
31
}

标签:二分,int,节点,算法,编号,集合,include,find
From: https://www.cnblogs.com/-37-/p/17661128.html

相关文章