题解 P3370 【【模板】字符串哈希】

· · 题解

一看其他题解都没有用这个,于是写个题解安利一下这个好东西。

STL的 <functional> 有这个东西

template<typename _Tp> struct std::hash{};

ta可以得到任意基本类型的hash值(返回类型为 size_t ),还包括但不限于 string,bitset,vector<bool> 等。

对于这道题,可以这么使用。

#include <bits/stdc++.h>
#include <functional>
using namespace std;

int n, cnt;
string str;
size_t val;
hash<string> hasher;
set<size_t> bot;

int main() {
    cin >> n;
    for(int i = 0;i < n;i++) {
        cin >> str;
        val = hasher(str);
        if(bot.count(val)) cnt++;
        else bot.insert(val);
    }
    cout << n - cnt;
    return 0;
}

ta资瓷以下类型

bool    char    signed char unsigned char   char8_t
char16_t    char32_t    wchar_t short   unsigned short
int unsigned int    long    long long   unsigned long
unsigned long long  float   double  long double void*
string u8string u16string u32string wstring
pmr::string pmr::u8string pmr::u16string
pmr::u32string pmr::wstring
error_code bitset unique_ptr shared_ptr type_index
vector<bool> thread::id optional variant string_view
wstring_view u8string_view u16string_view
u32string_view error_condition

参考资料: https://zh.cppreference.com/w/cpp/utility/hash