牛客寒假算法基礎集訓營3 - J 處女座的比賽 字符串hash

題目鏈接

題意:根據所給的 hashhash 函數,對於題目所輸入的字符串,輸出與輸入字符串不同但是 hashhash 值相同的字符串。

思路:長度爲 1144 的字符串一共有 475254475254 種,足以把 [0,9982][0,9982] 中所有數都覆蓋至少 22 次。所以可以預處理這些字符串,每個hash值存下對應兩種不同的字符串即可。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
const int mod=9983;
int p, q, r, t;
int T, in_dex[26], mul[3];
string s;
int cnt[9983] = {};
string ans[9983][2];
inline int get_hash()
{
    int ans = 0, len = s.size();
    for (int i=1;i<=len;i++)
        ans = (ans * mul[i % 3] + in_dex[s[i - 1] - 'a']) % mod;
    return ans;
}
inline void add(char x)
{
    s += x;
    int hash = get_hash();
    if (cnt[hash] < 2)
    {
        ans[hash][cnt[hash]] = s;
        ++cnt[hash];
    }
}
int main()
{
    scanf("%d%d%d%d%d%d", &p, &q, &r, &t, &T);
    mul[0] = p, mul[1] = q, mul[2] = r;
    for (int i = 0; i < 26; i++)
        in_dex[i] = i * t + t;
    for (char i = 'a'; i <= 'z'; ++i)
    {
        s = "", add(i);
        for (char j = 'a'; j <= 'z'; ++j)
        {
            add(j);
            for (char k = 'a'; k <= 'z'; ++k)
            {
                add(k);
                for (char z = 'a'; z <= 'z'; ++z)
                    add(z), s.pop_back();
                s.pop_back();
            }
            s.pop_back();
        }
        s.pop_back();
    }
    int hash;
    while (T--)
    {
        cin >> s;
        hash = get_hash();
        if(s == ans[hash][0])
            cout << ans[hash][1];
        else
            cout << ans[hash][0];
        putchar('\n');
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章