【KMP】重复子串(ybtoj KMP-2)
生活随笔
收集整理的這篇文章主要介紹了
【KMP】重复子串(ybtoj KMP-2)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
正題
ybtoj KMP-2
題目大意
問你一個字符串最多由多少個相同的字符串組合而成
解題思路
如下圖,先用KMP求出nx數組,那么有1~nxn1\sim nx_n1~nxn?和(n?nxn)~n(n-nx_n)\sim n(n?nxn?)~n相匹配
不難推出1~(n?nxn)1\sim (n-nx_n)1~(n?nxn?)和nxn~nnx_n\sim nnxn?~n匹配,則nxn~nnx_n\sim nnxn?~n為最小的相同的字符串
如果(n?nxn)∣n(n-nx_n)\mid n(n?nxn?)∣n那么有解
代碼
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define ll long long #define N 1000100 using namespace std; int nx[N]; char str[N]; void gnx(char* s) {int n = strlen(s + 1);for (int i = 2, j = 0; i <= n; ++i) {while (s[i] != s[j + 1] && j) j = nx[j];if (s[i] == s[j + 1])j++;nx[i] = j;}return; } int main() {scanf("%s", str + 1);while (str[1] != '.') {gnx(str);int n = strlen(str + 1);nx[1] = 0;if (n % (n - nx[n]) == 0)//判斷是否有解printf("%d\n", n / (n - nx[n]));elseputs("1");scanf("%s", str + 1);}return 0; }總結
以上是生活随笔為你收集整理的【KMP】重复子串(ybtoj KMP-2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【LCT】城市旅行(luogu 4842
- 下一篇: 世界十大护肤品品牌是哪些