day 53 图论part5

文章目录

  • [卡码网 107. 寻找存在的路线](#卡码网 107. 寻找存在的路线)

卡码网 107. 寻找存在的路线

并查集基础题目,并查集的四种方法,初始化,每一个节点初始化指向自己,join方法,把两个节点加入到同一个集合中,isame方法,判断两个节点是否在同一个集合中,find方法,找到每一个节点的根节点,使用路径压缩。

java 复制代码
import java.util.*;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();
        DisJoint disjoint = new DisJoint(N + 1);
        for (int i = 0; i < M;i++) {
            int s = sc.nextInt();
            int t = sc.nextInt();
            disjoint.join(s, t);
        }
        if (disjoint.isSame(sc.nextInt(), sc.nextInt())) {
            System.out.println("1");
        }
        else {
            System.out.println("0"); 
        }

    }
}

class DisJoint {
        private int[] father;
        public DisJoint(int N) {
            father = new int[N];
            for (int i = 0; i < N; i++) {
                father[i] = i;
            }
        }
        public int find (int n) {
            return n == father[n] ? n : (father[n] = find(father[n]));
        }
        public boolean isSame(int n, int m) {
            n = find(n);
            m = find(m);
            return n == m;
        }
        public void join(int n, int m) {
            n = find(n);
            m = find(m);
            if (n == m) {
                return;
            }
            father[n] = m;
        }
    }
相关推荐
Gigavision2 小时前
基于BUAA-MIHR数据集的噪声解耦对比学习算法
人工智能·python·深度学习·算法
鹿角片ljp2 小时前
LeetCode 64:最小路径和复盘|二维 DP 与 ACM 模式完整写法
java·数据结构·算法
彧azz3 小时前
算法设计与分析:贪心与动态规划
数据结构·学习·算法·贪心算法·动态规划
泡海椒3 小时前
PDF 表格样式优化:jquick-pdf 边框、圆角、背景色
java·开发语言·pdf
Beyond_System|系统之外4 小时前
【学编程】Python基础编程题100道(21-60)
开发语言·python·算法
景熙55234 小时前
15.Java 8 Stream 流入门到实战
java·开发语言·数据结构
wno7045 小时前
Spring Security权限控制
java·python·spring
杨运交5 小时前
[071][验证码模块]基于Spring拦截器的验证码认证设计思想
java·后端·spring
Geek-Chow5 小时前
CountDownLatch in Java
java