【POI每日題解 #3】 OKR-Periods of Words
阿新 • • 發佈:2018-06-16
lan img http class IT 鏈接 tdi names ID
題目鏈接
蒟蒻對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];View Code7 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 }
【POI每日題解 #3】 OKR-Periods of Words