HDU - 4300 Clairewd’s message ( HASH/ex_kmp

本文介绍了一种使用Hash算法破解密码的方法。通过将密文转换为明文并对比字符串的前后缀,找出最长匹配长度,从而实现密码的还原。代码中详细展示了如何初始化参数、构建Hash值、比较前后缀等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

一道hash水题 给出两端序列,其中第一段为hash序列, 第二段前面为对应的密码值,后面为真值但是可能不全,需要我们补全

题解:

直接暴力HASH, 将所有的密文都翻译为明文, 比较原来的字符串的后缀和翻译后的前缀的最长匹配长度

#include <bits/stdc++.h>

using namespace std;

#define CLR(a,b) memset(a,(b),sizeof(a))
#define ll long long
#define ls o<<1
#define rs o<<1|1
#define pb push_back
typedef unsigned long long ull;

const int MAXN = (int)1e5+10;
const ull base = (ull)229;
char s[MAXN], t[30];
int c[30];
ull hash1[MAXN], hash2[MAXN];
ull p[MAXN];
void init() {
    p[0] = 1;
    for(int i = 1; i <= MAXN; ++i) p[i] = p[i-1]*base;
}
ull get(int l, int r, ull g[]) {
    return g[r]-g[l-1]*p[r-l+1];
}

int main() {
    int T; cin >> T;
    while(T--) {
        init();
        CLR(s, 0); CLR(t, 0);
        scanf("%s%s",t, s+1);
        for(int i = 0; i < 26; ++i) {
            c[t[i]-'a'] = i;
        }
        int n = strlen(s+1);
        hash1[0] = hash2[0] = 0;
        for(int i = 1; i <= n; ++i) {
            hash1[i] = hash1[i-1]*base+(s[i]-'a');
            hash2[i] = hash2[i-1]*base+(c[s[i]-'a']);
        }
        int ans = n;
        for(int i = n; i < n*2; ++i) {
            if(i&1) continue;
            int tmp = i/2;
            int len = n-tmp;
            ull s1 = get(1, len, hash2);
            ull s2 = get(n+1-len, n, hash1);
            if(s1 == s2) {
                ans = tmp;
                break;
            }
        }
        for(int i = 1; i <= ans; ++i) cout << s[i];
        for(int i = 1; i <= ans; ++i) printf("%c",c[s[i]-'a']+'a');
        cout << "\n";
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值