Codeforces #506 A. Many Equal Substrings

A. Many Equal Substrings

time limit per test: 1 second
memory limit per test: 256 megabytes
input: standard input
output: standard output

You are given a string t consisting of n lowercase Latin letters and an integer number k.

Let's define a substring of some string s with indices from l to r as s[l…r].

Your task is to construct such string s of minimum possible length that there are exactly k positions i such that s[i…i+n−1]=t. In other words, your task is to construct such string s of minimum possible length that there are exactly k substrings of ss equal to t.

It is guaranteed that the answer is always unique.

Input

The first line of the input contains two integers n and k (1≤n,k≤50) — the length of the string t and the number of substrings.

The second line of the input contains the string t consisting of exactly n lowercase Latin letters.

Output

Print such string s of minimum possible length that there are exactly k substrings of s equal to t.

It is guaranteed that the answer is always unique.

Examples

input

3 4
aba

output

ababababa

input

3 2
cat

output

catcat

概述

    给定子字符串,构造包含k个该子字符串的最短字符串。

思路

    作为div 3的第一道题自然相当随意,数据量极小,O(k*n^3)也能过的样子,可以说有思路就没有问题,事实上我也看到有大佬迭代遍历AC这道题。

    不过当我初步推理这道题时,我马上联想到KMP算法。直觉告诉我这就是这道题的最优解法,而且可以利用现成代码。接下来我就讲一讲这道题关于KMP的解法~

    还不理解KMP算法的话...出门左转见度娘~

    首先想到,最傻的方法就是把k个t串起来,必然保证有k个t;

    如何使字符串长度更短?

    假设有某种办法,那么随着总长度缩短,必然造成相邻的子字符串相互重叠,但不会完全重合或存在包含关系。换句话说,我们只需要使子字符串之间重合部分最长,就得到了最短的目标字符串。

    而每个子字符串是相等的,也就是求子字符串自己头和尾的最长重合部分

    例如子字符串t="abcab",“ab”就是t的最长重合部分。比如k=2时,s="abcabcab"。

    讲到这里熟悉KMP的朋友们就会发现,这正是KMP实现的核心思想,KMP初始化fail/next数组就保存着这样的信息。于是我们借用KMP的初始化函数,顿时这道题只剩下简单的处理。

    注意重合部分不能是子字符串本身,例如t="aaa"时最多只能重合"aa"。

代码

#include<bits\stdc++.h> 
using namespace std; 

string r,s;
int fail[100]{0};
void make_fail(){
	for(int i=1,j=0;s[i];i++){
		while(j && s[i]!=s[j]) j=fail[j-1];
		if(s[i]==s[j])fail[i]=++j;
		else fail[i]=0;
	}
}

int main(){
	int n,k;
	cin>>n>>k;
	cin>>s;
	make_fail();
	int p=n-fail[n-1];
	if(p==0) p=1;
	for(int i=0;i<k-1;i++)
		r.append(s.substr(0,p));
	r.append(s);
	cout<<r;
	return 0;
}

http://www.cnblogs.com/hizcard/  转载请注明出处 

猜你喜欢

转载自blog.csdn.net/hizcard/article/details/82082087