题解 | #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);
                }
            }
        }

    }

}
全部评论

相关推荐

神哥不得了:神哥来啦~自我评价和校园经历的话可以直接删了,从大厂暑期的话应该没有什么太多问题,应该是能拿到很多大厂面试机会的,就是在面试的时候表示的好一点就行,可以在面试前先把高频top 50的八股多巩固几遍,千万不要看那些假高频八股,这两个项目的话问题不是很大,应该能够帮你找到大厂实习的,算法的话一定要刷起来,因为大厂有些还是比较看重算法的
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务