1. 程式人生 > >【洛谷】P1551 親戚 並查集

【洛谷】P1551 親戚 並查集

連結:https://www.luogu.org/problemnew/show/P1551


import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt(),
            m = in.nextInt(),
            p = in.nextInt();
        UnionFind uf = new
UnionFind(n+1); Integer[] arr = uf.arr; for (int i = 0; i < m; i++) { int a = in.nextInt(); int b = in.nextInt(); uf.union(a, b); } for (int i = 0; i < p; i++) { int a = in.nextInt(), b = in.nextInt(
); if (uf.findRoot(arr[a]) == uf.findRoot(arr[b])) System.out.println("Yes"); else System.out.println("No"); } } class UnionFind { Integer[] arr; public UnionFind(int size) { this.arr = new Integer[size]; for (int i = 1; i <
arr.length; i++) arr[i] = new Integer(i); } public int findRoot(int i) { while (i != arr[i]) i = arr[i]; return i; } public void union(int a, int b) { a = findRoot(a); b = findRoot(b); arr[a] = b; } }