java io流快读 + 并查集

例题:
1249. 亲戚

本题考查并查集

并查集

一般不用优化

static int find(int x) {
    
    
		if(p[x] != x) p[x] = find(p[x]);// 如果自己不是老大,就找老大
		return p[x];// 老大登场
	}

Scanner 和 System.out.print()的输入输出很慢, 不然TLE。这里io流输入输出怎么定义,要记住

以本题为例

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class Main {
    
    
	static int N = 20005;
	static int M = 100005;
	static int n,m,t;
	static int []p = new int [M];
	static int find(int x) {
    
    
		if(p[x] != x) p[x] = find(p[x]);
		return p[x];
	}
    public static void main(String[] args) throws IOException {
    
    
        //Scanner sc = new Scanner(System.in);
    	BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wt = new PrintWriter(new OutputStreamWriter(System.out));
        String[] str1 = re.readLine().split(" ");
        n = Integer.parseInt(str1[0]);
        m = Integer.parseInt(str1[1]);
        for(int i = 1; i <= n; i ++) p[i] = i;
        for(int i = 1; i <= m; i ++) {
    
    
        	String[] str2 = re.readLine().split(" ");
        	int a = Integer.parseInt(str2[0]);
        	int b = Integer.parseInt(str2[1]);
        	p[find(a)] = find(b);
        }
        String[] str3 = re.readLine().split(" ");
        int t = Integer.parseInt(str3[0]);
        for(int i =  0; i < t; i ++) {
    
    
        	String[] str4 = re.readLine().split(" ");
        	int c = Integer.parseInt(str4[0]);
        	int d = Integer.parseInt(str4[1]);
        	if(find(c) == find(d))
        	wt.println("Yes");
        	else wt.println("No");
        }
        
        wt.flush();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_52237775/article/details/129390905
今日推荐