zoukankan      html  css  js  c++  java
  • 洛谷P3367 【模板】并查集

     1 /*
     2 并查集(树实现)
     3 路径压缩、按秩合并
     4 使用前调用init()
     5 find(x) 查找x的根节点(路径压缩)
     6 Union(x,y) 启发式合并 
     7 */ 
     8 #include<bits/stdc++.h>
     9 using namespace std;
    10 const int size=100005;//集合大小 
    11 int n,m;//n--元素个数 m--查询次数 
    12 struct node{
    13     int fa,cnt,val;//父节点、自己及子树元素个数(仅当其为根节点始有意义)、元素的值 
    14 }Set[size];
    15 inline int find(int x) {return Set[x].fa==x?x:(Set[x].fa=find(Set[x].fa));}//路径压缩 
    16 inline void Union(int x,int y)
    17 {
    18     x=find(x),y=find(y);if(x==y) return;
    19     if(Set[x].cnt>Set[y].cnt) {Set[y].fa=x;Set[x].cnt+=Set[y].cnt;}//按秩合并 
    20     else {Set[x].fa=y;Set[y].cnt+=Set[x].cnt;}
    21 }
    22 inline void init() {for(int i=1;i<=n;i++) Set[i].fa=Set[i].val=i,Set[i].cnt=1;}//初始化 
    23 int main()
    24 {
    25     scanf("%d%d",&n,&m);
    26     init();
    27     for(int i=1,x,y,z;i<=m;i++)
    28     {
    29         scanf("%d%d%d",&x,&y,&z);
    30         if(x==1) Union(y,z);
    31         if(x==2)
    32         {
    33             if(find(y)==find(z)) printf("Y
    ");
    34             else printf("N
    ");
    35         }
    36     }
    37     return 0;
    38 }
  • 相关阅读:
    MySQL:解决脏读问题
    MySQL:隔离性问题(脏读)&回滚演示
    MySQL: Mysql 事务隔离级别
    MySQL:数据库事务
    GRE Vocabulary:sedulous
    MySQL:SQL约束
    GRE Vocabulary:pall
    MySQL:DQL操作单表
    MySQL: DQL 查询表中数据
    MySQL:DML操作 表中数据
  • 原文地址:https://www.cnblogs.com/yu-xing/p/10203381.html
Copyright © 2011-2022 走看看