字符串的哈希排序

#include <iostream>
#include<string>
#include<algorithm>
#include<cstring>
using namespace std;

const int MAXN=1e6+5;
int a[MAXN];
typedef unsigned long long ull;

int main()
{
    int n;
    cin>>n;
    int ans=0,tot=0;
    while(n--)
    {
        ull p=331;//取模数
        ull x=0;
        string ss;
        cin>>ss;
        for(int i=0;i<ss.size();i++)
            x=x*p+ss[i];
        a[++tot]=x;
    }
    sort(a+1,a+1+tot);
    cout<<unique(a+1,a+1+tot)-a-1<<endl;
    //输出不同字符串的个数

    //cout << "Hello world!" << endl;
    return 0;
}

优秀一点的

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#define lli long long int 
using namespace std;
const int MAXN=100001;
const long long int mod=212370440130137957;
int seed=27;
void read(int &n)
{
    char c='+';int x=0;bool flag=0;
    while(c<'0'||c>'9'){c=getchar();if(c=='-')flag=1;}
    while(c>='0'&&c<='9')x=x*10+c-48,c=getchar();
    n=flag==1?-x:x;
}
char a[MAXN];
map<int,bool>happen;
int tot=0;
int main()
{
    int n;
    read(n);
    for(int i=1;i<=n;i++)
    {
        long long base=1;
        scanf("%s",a);
        int la=strlen(a);
        for(int j=0;j<la;j++)
            base=(base*seed+(a[j]) )%mod;
        if(!happen[base])
            happen[base]=1,tot++;
    }
    printf("%d",tot);
    return 0;
}

大质数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值