D D - Om Nom and Necklace

来源:互联网 发布:湖南省地质测绘院 知乎 编辑:程序博客网 时间:2024/06/09 19:32

官方题解(讲的非常详细)

This task is to determine whether a string is in the form of ABABA... ABA for each prefixes of a given string S

For a prefix P, let's split it into some blocks, just like P = SSSS... SSSST, which T is a prefix of S. Obviously, if we use KMP algorithm, we can do it in linear time, and the length ofS will be minimal. There are only two cases :T = S, T ≠ S.

  1. T = S. When T = S, P = SSS... S. Assume thatS appears R times. Consider "ABABAB....ABABA", the lastA must be a suffix of P, and it must be like SS... S, so A will be like SS... SS, and so will B. By greedy algorithm, the length ofA will be minimal, so it will be SSS... S, where S appears times. AndB will be SSS...S, where S appears times. So we just need to check whether.
  2. T ≠ S . When T ≠ S, the strategy is similar to T = S. A will be like "SS...ST", and its length will be minimal. At last we just need to check whether .

The total time complexity is O(n).

AC代码

#include <queue>#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;const int MAX = 1000010;int n, k;char s[MAX];int next[MAX];void make_next(){int i = 0, j = -1;next[0] = -1;while(i < n){if(j == -1 || s[i] == s[j]){i++, j++;next[i] = j;}else j = next[j];}}int main(){scanf("%d%d", &n, &k);scanf("%s", s);make_next();for(int i=1; i<=n; i++){int cur = i - next[i];int L = i % cur;int cnt = i / cur;if(L  == 0){if(cnt / k - cnt % k >= 0) printf("1");else printf("0");}else{if(cnt / k - cnt % k > 0) printf("1");else printf("0");}}puts("");}


0 0
原创粉丝点击