洛谷 P3370 【模板】字符串哈希

传送门


解题思路

可以自己取一个大质数当做模数,或者直接利用unsigned long long的溢出。

进制也可以选择一个较小的质数,如13131或者15151等。

AC代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iomanip>
#include<vector>
#include<ctime>
#include<set>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
template<class T>inline void read(T &x)
{
    x=0;register char c=getchar();register bool f=0;
    while(!isdigit(c))f^=c=='-',c=getchar();
    while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
    if(f)x=-x;
}
template<class T>inline void print(T x)
{
    if(x<0)putchar('-'),x=-x;
    if(x>9)print(x/10);
    putchar('0'+x%10);
}
int n;
string s;
set<unsigned long long> ss;
int main(){
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=1;i<=n;i++){
		unsigned long long res=0;
		cin>>s;
		int len=s.length();
		for(int i=0;i<len;i++){
			res=res*13131+s[i];
		}
		ss.insert(res);
	}
	cout<<ss.size();
	return 0;
}
posted @ 2021-10-08 07:53  尹昱钦  阅读(44)  评论(0编辑  收藏  举报