D D - Om Nom and Necklace

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

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 of S will be minimal. There are only two cases : T = S, T ≠ S.

  1. T = S. When T = S, P = SSS... S. Assume that S appears R times. Consider "ABABAB....ABABA", the last A 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 of A will be minimal, so it will be SSS... S, where S appears times. And B 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值