字符串hash(入门)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Let_life_stop/article/details/85596278

题目链接:https://www.luogu.org/problemnew/show/P3370

具体思路:我们可以将字符串的每一个字符转换成数字,然后比较的时候,直接比较这个字符串对应的hash值就可以了。

AC代码:

#include<iostream>
#include<stdio.h>
#include<iomanip>
#include<stack>
#include<algorithm>
#include<string>
#include<cstring>
#include<cmath>
using namespace std;
# define ll long long
# define ull unsigned long long
const int base=131;//一般比ascii码值大就可以了。
const int maxn = 1e4+100;
char str[maxn];
ll a[maxn];
ull Hash(char a[])
{
    int len=strlen(a);
    ull sum=0;
    for(int i=0; i<len; i++)
    {
        sum=sum*base+(ull)a[i];
    }
    return sum;
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
    {
        scanf("%s",str);
        a[i]=Hash(str);
    }
    sort(a+1,a+n+1);
    int ans=1;
    for(int i=2; i<=n; i++)
    {
        if(a[i]!=a[i-1])
            ans++;
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Let_life_stop/article/details/85596278