【BZOJ3555】字符串Hash

本文介绍了一个基于字符串哈希的匹配算法实现,通过预处理提高字符串比较效率,利用快速排序进行优化,最终输出所有匹配子串的数量。文章详细记录了从算法设计到调试过程中遇到的问题及解决方案。

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

#include <cstdio>
#include <cstring>
#include <algorithm>

const int MAXL = 200 + 5;
const int MAXN = 3e4 + 5;
const int BASE = 131;

unsigned long long base[MAXL], hash[MAXN];
char s[MAXN][MAXL];
int n, len;
unsigned long long a[MAXN];

inline void prepare()
{
    base[0] = 1;
    for (int i = 1; i <= len; i++) base[i] = base[i - 1] * BASE;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= len; j++) hash[i] = hash[i] * BASE + s[i][j];
}

int main()
{
    scanf("%d %d %*d", &n, &len);

    for (int i = 1; i <= n; i++)
    {
        scanf("%s", s[i] + 1);
    }

    prepare();

    int ans = 0;
    for (int j = 1; j <= len; j++)
    {
        for (int i = 1; i <= n; i++)
        {
            a[i] = hash[i] - s[i][j] * base[len - j];
        }

        std::sort(a + 1, a + n + 1);

        int cnt = 1;
        for (int i = 2; i <= n; i++)
        {
            if (a[i] == a[i - 1])
            {
                ans += cnt;
                cnt++;
            }
            else
            {
                cnt = 1;
            }
        }
    }

    printf("%d\n", ans);
    return 0;
}

这道题我一定得写!!!!
我把a数组定义成int了!!!!WA了好几个小时!!!!
!!!!!!气炸肺!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值