洛谷 P2256 一中校运会之百米跑 Java

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

public class Main{

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    static TreeMap tm = new TreeMap<>();
    static HashSet hash = new HashSet<>();

    public static void main(String[] args) throws IOException {
        String[] S = br.readLine().split(" ");
        int N,M,K;
        N = Integer.parseInt(S[0]);
        M = Integer.parseInt(S[1]);
        for(int i = 0 ; i < N ; i++) {
            String str = br.readLine();
            tm.put(str, str);
            hash.add(str);
        }
        for(int i = 0 ; i < M ; i++) {
        	S = br.readLine().split(" ");
        	String s1 = S[0];
        	String s2 = S[1];
        	s1 = Find(s1);
        	s2 = Find(s2);
        	if(!(s1.equals(s2))) {
        		String temp = tm.get(s1);
        		temp = s2;
        		tm.put(s1,s2);
        	}
        }
        K = Integer.parseInt(br.readLine());
        for(int i = 0 ; i < K ; i++) {
        	S = br.readLine().split(" ");
        	String s1 = S[0];
        	String s2 = S[1];
        	if(!hash.contains(s1) || !hash.contains(s2)) {
        		out.write("No.\n");
        		continue;
        	}
        	if(Find(s1).equals(Find(s2))) {
        		out.write("Yes.\n");
        	}
        	else {
        		out.write("No.\n");
        	}
        }
        out.flush();
        out.close();
        br.close();
    }

    private static String Find(String str) {
        String temp;
        temp = tm.get(str);
        if(!(tm.get(str).equals(str))) {
            temp = Find(tm.get(str));
        }
        return temp;
    }
}

ps:这道题的测试点二似乎数据有误,在看了数据点二的数据之后,我试着用一个HashSet来进行判断是否存在某名成员,最后AC100了(一道简单的并查集)

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