Discretization-unordered_map

Learn about the usage of unordered_map. I saw this thing for the first time before the Shanghai regional game. I saw that I was as confident as the map usage and felt that it could be used. However, I got stuck on the field. Now roll over and learn about orz. Need to use this thing.

It is easy to understand discretization for those who have learned hash. It is nothing more than when the data is too large to open such a large array, but in fact there is a lot of wasted space in the middle, then it can be mapped to another array.

The previously commonly used C++ discretization is

// a[i] 为初始数组,下标范围为 [1, n]
// len 为离散化后数组的有效长度
std::sort(a + 1, a + 1 + n);

len = std::unique(a + 1, a + n + 1) - a - 1;
// 离散化整个数组的同时求出离散化后本质不同数的个数。
std::lower_bound(a + 1, a + len + 1, x) - a;  // 查询 x 离散化后对应的编号

And unordered_map is a data structure that implements a hash table internally. Its search efficiency is O(1).

So let’s go to a basic application example: https://ac.nowcoder.com/acm/contest/5158/H

Insert picture description here

Obviously and check the collection, but 1e9, so big and sure to discretize, then use this unordered_map to replace the pre array in the collection and check it is OK

#include<bits/stdc++.h>
using namespace std;
unordered_map<int ,int > pre;

int find(int a)
{
    
    
    if(pre[a] == 0)
        return a;
    else
        return pre[a] = find(pre[a]); 
}

void Union(int a,int b){
    
    
    int m = find(a);
    int n = find(b);
    pre[m] = n;
    return ;
}

int main()
{
    
    
    cin.tie(0),ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--) {
    
    
        pre.clear();
        int flag = 1;
        int n,a,b,c;
        cin >> n;
        for(int i = 0 ;i < n; i++) {
    
    
            cin>>a>>b>>c;
            int m = find(a);
            int n = find(b);
            if(c == 1 ){
    
    
                if( m!=n && a !=m &&b != n){
    
    
                    flag = 0;
                    break;
                }
                else 
                    Union(a,b);
            }
            else{
    
    
                if( m == n){
    
    
                    flag = 0;
                    break;
                }      
            }
        }
        if(flag == 0)
            cout<<"NO"<<endl;
        else
            cout<<"YES"<<endl;
    }
    system("pause");
    return 0;
}

Unfinished, continue to finish the test, continue to write

Guess you like

Origin blog.csdn.net/u011612364/article/details/112206374