zoukankan      html  css  js  c++  java
  • P3370 【模板】字符串哈希【字符串哈希】

    题目

    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);
    }
  • 相关阅读:
    Codeforces Round #277 (Div. 2)
    Topcoder SRM 637 (Div.2)
    【转】大素数判断和素因子分解【miller-rabin和Pollard_rho算法】
    【网络流#5】UVA 11082 最大流
    【网络流#4】UVA 753 最大流
    Codeforces Round #274 (Div. 2)
    【网络流#3】hdu 1532
    【网络流#2】hdu 1533
    【网络流#1】hdu 3549
    Codeforces Round #273 (Div. 2)
  • 原文地址:https://www.cnblogs.com/Jason66661010/p/13205074.html
Copyright © 2011-2022 走看看