跳到正文

个人记录

【模板】双重哈希

NefeliOwO约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年8月16日
收录
2026年8月17日
更新
2026年11月17日
篇幅
约 2 分钟

版本

  1. v1当前

写的第一遍用高精模板打算莽大整数莽过去,试了一下会超时,还是回来用双重哈希比较实在一点

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

const int mod1 = 1e9 + 7;
const int mod2 = 998244353;

int NUM(char c)
{
	if(c >= '0' && c <= '9') return (c - '0');
	if(c >= 'a' && c <= 'z') return 10 + (c - 'a');
	if(c >= 'A' && c <= 'Z') return 36 + (c - 'A');
}

void Trans(string s,long long &calc1,long long &calc2)
{
	for(int i = 0;i<s.size();i++)
	{
		calc1 = (calc1 * 62) % mod1;
		calc1 = (calc1 + NUM(s[i])) % mod1;
		calc2 = (calc2 * 62) % mod2;
		calc2 = (calc2 + NUM(s[i])) % mod2;
    // 62是一共只有62个符号,如有需要可以扩大
	}
}

int main() 
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
	int T;
	long long ans = 0;
	cin >> T;
	map<pair<long long,long long>,int> p; // map映射两次取模结果数对,确保不重不漏
	for(int i = 0;i<T;i++)
	{
		string s;
		cin >> s;
		long long m1 = 0,m2 = 0;
		Trans(s,m1,m2); // 两个同步算,直接用引用读
		if(!p[{m1,m2}])
		{
			ans++;
			p[{m1,m2}] = 1;
		}
	}
	cout << ans << endl;
    return 0;
}
原文