码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-06-28 22:37:23      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:nod   scanf   www   span   哈希   names   字符串   alt   loading   

题目

https://www.luogu.com.cn/problem/P3370

技术图片

 

 思路

大致的方法就是先自己预定一个base基值,将字符串的每一位与base相乘,解决冲突的方法就是使用自然溢出、双哈希等

代码

自然溢出

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
#define ull unsigned long long
ull  base = 131;
ull list[20000];
int answer = 0,n;
long long a[20000];
int hashsssss(string a)
{
    ull ans = 0;
    for (int i = 0; i < a.length(); i++)
    {
        ans = ans * base+(ull)a[i];
    }
    return ans & 0x7fffffff;
}
int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        string temp;
        cin >> temp;
        a[i] = hashsssss(temp);
    }
    sort(a, a + n);
    int count = 1;
    for (int i = 0; i < n - 1; i++)
        if (a[i] != a[i + 1])count++;
    printf("%d", count);
}

 

双哈希

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
#define ull unsigned long long
ull  base = 131;
ull mod1 = 192837423;
ull mod2 = 192348236;
struct node
{
    ull x;
    ull y;
}a[20000];
int answer = 0, n;
bool cmp(struct node &a, struct node &b)
{
    if (a.x == b.x)return a.y > b.y;
    else return a.x > b.x;
}
int hashsssss(string a)
{
    ull ans = 0;
    for (int i = 0; i < a.length(); i++)
    {
        ans = ans * base + (ull)a[i]%mod1;
    }
    return ans;
}
int hashsssss2(string a)
{
    ull ans = 0;
    for (int i = 0; i < a.length(); i++)
    {
        ans = ans * base + (ull)a[i] % mod2;
    }
    return ans;
}

int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        string temp;
        cin >> temp;
        a[i].x = hashsssss(temp);
        a[i].y = hashsssss2(temp);
    }
    sort(a, a + n,cmp);
    int count = 1;
    for (int i = 0; i < n - 1; i++)
        if (a[i].x != a[i + 1].x|| a[i].y != a[i + 1].y)count++;
    printf("%d", count);
}

 

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

标签:nod   scanf   www   span   哈希   names   字符串   alt   loading   

原文地址:https://www.cnblogs.com/Jason66661010/p/13205074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!