首页 > 其他分享 >代码高亮

代码高亮

时间:2022-12-27 00:11:16浏览次数:32  
标签:高亮 cout int 代码 find return 节点 op

#include<iostream>

using namespace std;

const int N = 1e5 + 10;

int n, m;
int p[N]; // 维护每个节点的父节点

int find(int x) { // 返回x的祖宗(根节点)+ 路径压缩
    if(p[x] != x) p[x] = find(p[x]); // 如果不是根节点,就递归往上找,同时压缩了路径
    return p[x]; // 路径压缩后,返回的是根节点
}

int main() {
    cin >> n >> m;
    
    // 初始化,根节点的父节点就是自己,最开始所有的节点都是根节点,等待合并的操作
    for(int i = 1; i <= n; i++) p[i] = i; 
    
    while(m--) {
        int a, b;
        char op[2];
        scanf("%s%d%d", op, &a, &b);
        
        if(op[0] == 'M') {
            p[find(a)] = find(b); // 合并
        }
        else { // 询问
            if(find(a) == find(b)) cout << "Yes" << endl;
            else cout << "No" << endl;
        }
    }
    
    return 0;
}

标签:高亮,cout,int,代码,find,return,节点,op
From: https://www.cnblogs.com/icbm/p/17007173.html

相关文章