P3370-[模板]字符串哈希【hash】

正题

评测记录:https://www.luogu.org/recordnew/lists?uid=52918&pid=P3370


大意

输出若干个字符串,求输入的字符串的总个数。


解题思路

就是用hash表就好了。


code

#include<cstdio>
#include<iostream>
#include<string>
#define p 30001
using namespace std;
int n,ans;
string s,hash[p];
int hashmath(string x)//哈希函数
{
    int ans=0;
    for (int i=0;i<x.size();i++)
    {
        ans=(ans+x[i])%p;
    }
    return ans%p;
}
int locate(string x)//寻找插入位置
{
    int wz=hashmath(x);
    int i=0;
    while (i<p && hash[(wz+i)%p]!=x && hash[(wz+i)%p]!="")
      i++;
    return (wz+i)%p;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        cin>>s;
        int wz=locate(s);
        if(hash[wz]!=s){
          hash[wz]=s;
          ans++;
        }//有新字符串
    }
    printf("%d",ans);
}

猜你喜欢

转载自blog.csdn.net/Mr_wuyongcong/article/details/81743831
今日推荐