题解 | #DongDong认亲戚#

DongDong认亲戚

https://ac.nowcoder.com/acm/problem/23803

HashMap模拟并查集

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        sc.nextLine();
        String []name = sc.nextLine().split(" ");
        HashMap<String ,String >hashmap = new HashMap<String,String>();
        for(int i = 0;i<m;i++){
            int judge = sc.nextInt();
            String name1 = sc.next();
            String name2 = sc.next();
            if(judge==1){
                String str1 = name1;
                String str2 = name2;
                while (true) {
                    if(hashmap.get(str1)!=null){
                        str1 = hashmap.get(str1);
                    }else{
                        break;
                    }
                }
                while (true) {
                    if(hashmap.get(str2)!=null){
                        str2 = hashmap.get(str2);
                    }else{
                        break;
                    }
                }
                if(str1.equals(str2)){

                }else{
                   hashmap.put(str1, name2);
                }
            }else{
                String str1 = name1;
                String str2 = name2;
                while (true) {
                    if(hashmap.get(str1)!=null){
                        str1 = hashmap.get(str1);
                    }else{
                        break;
                    }
                }
                while (true) {
                    if(hashmap.get(str2)!=null){
                        str2 = hashmap.get(str2);
                    }else{
                        break;
                    }
                }
                if(str1.equals(str2)){
                    System.out.println(1);
                }else{
                    System.out.println(0);
                }
            }
        }

    }

}
全部评论

相关推荐

07-21 18:43
门头沟学院 Java
是暑期都招满了吗
ANEOY:今年感觉真是后端地狱级难度了,从暑期就是这样,前端需求非常大
点赞 评论 收藏
分享
07-19 13:28
长沙学院 Java
程序员小白条:你有面试就有希望,没面试自然就没希望,到时候就知道了,你问别人也没啥用处的
点赞 评论 收藏
分享
机械打工仔:有说的你怀疑一下就行了,直接问也太实诚了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务