【哈希,map】P3370 字符串哈希

链接

https://www.luogu.org/problemnew/show/P3370

大意

给定 n 个串求出一共有多少个本质不同的串

思路

m a p 或字符串哈希,本人用的是自然溢出法

m a p + s t r i n g 代码(996 m s

#include<iostream>
#include<string>
#include<map>
using namespace std;
string a;int n,ans;
map<string,bool>m;
int main()
{
    cin>>n;int ans=n;
    while(n--)
     {
        cin>>a;
        if(m[a]) ans--;else m[a]=true;
     }
    cout<<ans;
}

h a s h + c h a r 代码(108 m s )

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef unsigned long long ull;
ull base=131,a[10001];
int n,ans=1;
char s[10001];
inline ull hash(char *s)
{
    ull sum=0;
    for(register int i=0;i<strlen(s);i++) sum=sum*base+(ull)s[i];
    return sum&0x7fffffff;  
}
signed main()
{
    scanf("%d",&n);
    for(register int i=1;i<=n;i++)
    {
        scanf("%s",s);
        a[i]=hash(s);
    }
    sort(a+1,a+1+n);
    for(register int i=2;i<=n;i++) if(a[i]!=a[~-i]) ans++;
    printf("%d",ans);
}

猜你喜欢

转载自blog.csdn.net/xuxiayang/article/details/81741525