洛谷 P3367 【模板】并查集 Java

import java.io.*;
import java.util.*;

public class Main{

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    static int[] P;

    public static void main(String[] args) throws IOException {
        int M,N;
        String[] STR = br.readLine().split(" ");
        M = Integer.parseInt(STR[0]);
        N = Integer.parseInt(STR[1]);
        P = new int[M+1];
        for(int i = 0 ; i < P.length ; i++){
            P[i] = i;
        }
        for(int i = 0 ; i < N ; i++){
            STR = br.readLine().split(" ");
            int x = Integer.parseInt(STR[0]);
            int y = Integer.parseInt(STR[1]);
            int z = Integer.parseInt(STR[2]);
            if(x == 1){
                Merge(y , z);
            }
            else{
                Search(y , z);
            }
        }
        out.flush();
        out.close();
        br.close();
    }

    public static int Find(int x){
        if(x != P[x]){
            P[x] = Find(P[x]);
        }
        return P[x];
    }

    public static void Merge(int x , int y){
        P[Find(x)] = P[Find(y)];
    }

    public static void Search(int x , int y) throws IOException {
        if(Find(x) != Find(y)){
            out.write("N\n");
        }
        else{
            out.write("Y\n");
        }
    }
}

你可能感兴趣的:(洛谷刷题之旅,java,算法,数据结构)