zoukankan      html  css  js  c++  java
  • hiho_1066_并查集

    题目大意

        给出N个操作,每个操作可能为两种类型之一: 
    1. 认定两个人属于同一个组织 
    2. 查询两个人是否是同一个组织

        要求对于每个操作类型2,给出结果,即查询的两个人是否属于同一个组织。其中,任何人都可以通过名字唯一确定。

    分析

        简单的并查集操作,直接使用哈希表存储名字字符串作为并查集树,而不用整数数组。unordered_map.

    实现

    #include<iostream>
    #include<string.h>
    #include<iostream>
    #include<queue>
    #include<unordered_map>
    #include<string>
    using namespace std;
    unordered_map<string, string> root; //存放并查集树节点,以及对应的根
    string GetRoot(string node){
    	if (node == root[node])
    		return node;
    	return root[node] = GetRoot(root[node]);
    }
    void Union(string person1, string person2){
    	string p1 = GetRoot(person1);
    	string p2 = GetRoot(person2);
    	root[p2] = p1;
    }
    bool SameRoot(string person1, string person2){
    	string p1 = GetRoot(person1);
    	string p2 = GetRoot(person2);
    	return p1 == p2;
    }
    int main(){
    	int n, op;
    	string person1, person2;
    	cin >> n;
    	while (n--){
    		cin >> op >> person1 >> person2;
    		if (root.find(person1) == root.end()){
    			root[person1] = person1;
    		}
    		if (root.find(person2) == root.end()){
    			root[person2] = person2;
    		}
    
    		if (op == 0){
    			Union(person1, person2);
    		}
    		else{
    			if (SameRoot(person1, person2))
    				printf("yes
    ");
    			else
    				printf("no
    ");
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    Leetcode: Longest Absolute File Path
    Leetcode: Mini Parser
    Leetcode: First Unique Character in a String
    Leetcode: Lexicographical Numbers
    Leetcode: Shuffle an Array
    Leetcode: Ransom Note
    Leetcode: Linked List Random Node
    Socket网络编程--聊天程序(7)
    Socket网络编程--聊天程序(6)
    Socket网络编程--聊天程序(5)
  • 原文地址:https://www.cnblogs.com/gtarcoder/p/5539563.html
Copyright © 2011-2022 走看看