2021年ACM竞赛班训练(十一) E题 调皮的摩尔

E题 调皮的摩尔

原题链接

算法: 字符串哈希

将一个字符串转化为整数存储,同时保证字符串不同,产生的数字不同。

注意点:

1. unsigned long long

unsigned long long (\(2^{64} - 1\)), 溢出自动取模

2. 哈希值的计算方法

已知字符串\(S\), 根据\(hash[r]\)\(hash[l]\) 计算子串\(l-r\)的哈希值:
\(hash[l - r] = hash[r] - hash[l] * p^{r -l + 1}\)

代码

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    unsigned long long ans = 0;

    string s;
    cin >> s;
    unsigned long long base = 1;
    for (int i = s.size() - 1; i >= 0; i -- ){
        if (s[i] >= 'a' && s[i] <= 'z')
            ans = ans + base * (unsigned long long)(s[i] - 'a');
        else{
            ans = ans + base * (unsigned long long)(s[i] - 'A');
        }
        base = base * 26;
    }

    cout << ans << endl;

    return 0;
}
posted @ 2021-06-05 15:55  lhqwd  阅读(63)  评论(0)    收藏  举报