洛谷 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<String,String> tm = new TreeMap<>();
    static HashSet<String> 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了(一道简单的并查集)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值