Day55--图论--107. 寻找存在的路径(卡码网)

Day55--图论--107. 寻找存在的路径(卡码网)

今天学习并查集。先过一遍并查集理论基础。再做下面这一道模板题,就可以结束了。体量不多,但是理解并查集,并使用好,不容易。

后续再找相关的题目来做,更新在下方。

107. 寻找存在的路径(卡码网)

方法:并查集

思路:

建立并查集类,完成isSame,find和join三个方法。

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

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        Disjoint dj = new Disjoint(n);
        for (int i = 0; i < m; i++) {
            int from = in.nextInt();
            int to = in.nextInt();
            dj.join(from, to);
        }
        int source = in.nextInt();
        int destination = in.nextInt();
        if (dj.isSame(source, destination)) {
            System.out.println(1);
        } else {
            System.out.println(0);
        }
    }
}

class Disjoint {
    private int[] father;

    public Disjoint(int n) {
        father = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            father[i] = i;
        }
    }

    public void join(int a, int b) {
        int root1 = find(a);
        int root2 = find(b);
        if (root1 == root2) {
            return;
        }
        father[root2] = root1;
    }

    public boolean isSame(int a, int b) {
        int root1 = find(a);
        int root2 = find(b);
        return root1 == root2;
    }

    public int find(int a) {
        if (a == father[a]) {
            return a;
        } else {
            // return find(father[a]);
            return father[a] = find(father[a]);
        }
    }
}

推荐题目

来自@灵艾山茶府:常用数据结构(前缀和/差分/栈/队列/堆/字典树/并查集/树状数组/线段树)链接中可以搜到并查集相关题目。实际上,可以用并查集做的题目,用其他方法也可以做。

相关推荐
hansang_IR3 天前
【题解】洛谷 P1477 [NOI2008] 假面舞会 [思维 + 图论]
c++·算法·图论·思维
天选之女wow3 天前
【代码随想录算法训练营——Day59】图论——47.参加科学大会、94.城市间货物运输I
算法·图论
叫我龙翔3 天前
【数据结构】从零开始认识图论 --- 单源/多源最短路算法
数据结构·算法·图论
天选之女wow4 天前
【代码随想录算法训练营——Day61】图论——97.小明逛公园、127.骑士的攻击
算法·图论
天选之女wow5 天前
【代码随想录算法训练营——Day60】图论——94.城市间货物运输I、95.城市间货物运输II、96.城市间货物运输III
android·算法·图论
foundbug9996 天前
基于超像素和基于图论的图像分割方法
图论
CodeWizard~7 天前
AtCoder Beginner Contest 430赛后补题
c++·算法·图论
天选之女wow8 天前
【代码随想录算法训练营——Day58】图论——117.软件构建、47. 参加科学大会
算法·图论
earthzhang20219 天前
【2051】【例3.1】偶数
开发语言·数据结构·算法·青少年编程·图论
apcipot_rain9 天前
CSP集训错题集 第八周 主题:基础图论
算法·图论