【POI每日题解 #3】 OKR-Periods of Words

题目链接

蒟蒻对kmp了解很浅

然鹅此题很裸

一个位置的i - next[i] 是它的“最小周期”

而“最大周期”就是一直向前找next

找到没有了

i - next[没有next的位置]就是该位置

记得每次要更新一下next 这样每次只用找前一个 实现O(1)的复杂度

总复杂度 O(n)

注:记得开long long哈 QAQ

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 const int N = 1e6 + 5;
 5 int len; 
 6 char str[N];
 7 int next[N];
 8 int main(){
 9     scanf("%d%s", &len, str);
10     int k = 0;
11     for(int i = 1; i < len; i++){
12         while(k > 0 && str[k] != str[i]) k = next[k];
13         if(str[k] == str[i]) k++;
14         next[i + 1] = k;
15     }
16     long long ans = 0;
17     for(int i = 1; i <= len; i++){
18         if(next[next[i]]) next[i] = next[next[i]]; 
19         ans += (long long)(i - (next[i] ? next[i] : i));
20     }
21     printf("%lld", ans);
22     return 0;    
23 }
View Code

猜你喜欢

转载自www.cnblogs.com/hjmmm/p/9190728.html