Codeforces 526D Om Nom and Necklace 循环节 kmp

本文介绍了一种利用KMP算法原理检查字符串是否能表示为特定形式的方法。通过对KMP算法的改进,实现了快速判断任意前缀是否符合给定模式的功能。

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

题目链接

题意

给定一个串 T ,对它的每一个前缀能否写成 A+B+A+B+...+B+A 的形式( k A k+1 B ,均可为空串)

思路

A+B+A+B+...+B+A 可以看做 AB+AB+AB+...+A ,即 k AB 1 A. 也就是判断这个串
能否被表示为 k 个循环节和另外一小段(可为空)的和
另外还有一种特殊情况,就是 A 为空,此时即该串
能否恰好被表示为 k+1 个循环节的和

// 其实想到第一步就 Orz 一切都顺了…。

于是求出 fail 数组,然后 ifail[i] 即为这一段中最小的循环节的长度,记为 cir . 显然, cir 的整数倍也是循环节,即 tcir 也是循环节。

要满足题意,则要求

itcir==k || ((tcir) | iitcir==k+1))

那么就可以直接根据 i,cir,t 的已知条件来 O(1) 算出是否存在这样的 t ,即 O(1) check

算法复杂度 O(n) .

Code

#include <bits/stdc++.h>
#define maxn 1000010
using namespace std;
int f[maxn], n, k;
char s[maxn];
typedef long long LL;
void getfail() {
    f[0] = f[1] = 0;
    for (int i = 1; i < n; ++i) {
        int j = f[i];
        while (j && s[i] != s[j]) j = f[j];
        f[i+1] = s[i] == s[j] ? j+1 : 0;
    }
}
bool check(int l, int cir) {
    int upp = l / k, down = l / (k+1) + 1;
    upp = upp / cir, down = ceil(1.0 * down / cir);
    return upp >= down || (l % (k+1) == 0 && (l / (k+1)) % cir == 0);
}
void work() {
    scanf("%s", s);
    getfail();
    for (int i = 1; i <= n; ++i) {
        int mincir = i - f[i], cir = mincir;
        printf("%d", check(i, cir));
    }
    printf("\n");
}
int main() {
    while (scanf("%d%d", &n, &k) != EOF) work();
    return 0;
}
### 关于 Codeforces 平台上的 KMP 算法练习题目 对于希望在 Codeforces 上找到有关 KMP (Knuth-Morris-Pratt) 字符串匹配算法的练习题目的选手来说,可以关注几个特定标签下的问题。通常这些题目会被标记为 "strings" 或者更具体地标记为 "string suffix structures"[^1]。 为了帮助更好地理解如何查找适合的练习题目,在此提供一段 Python 代码用于模拟访问 API 获取带有指定标签的问题列表: ```python import requests def fetch_problems(tag, platform="codeforces"): url = f"https://{platform}.com/api/problemset.problems?tags={tag}" response = requests.get(url) if response.status_code != 200: raise Exception(f"Failed to retrieve data from {platform}") json_data = response.json() problem_list = [] for index, item in enumerate(json_data['result']['problems']): name = item["name"] rating = item.get('rating', 'N/A') contest_id = item["contestId"] index = item["index"] problem_info = { "Name": name, "Rating": rating, "Link": f"{platform}.com/contest/{contest_id}/problem/{index}" } problem_list.append(problem_info) return problem_list[:5] # Example usage with the tag related to string processing or specifically KMP pattern matching. kmp_related_tag = "strings" fetched_problems = fetch_problems(kmp_related_tag) for prob in fetched_problems: print(prob) ``` 这段脚本会调用 Codeforces 的公开 API 来获取前五个与字符串处理相关的编程挑战链接,并打印出来供参考。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值