CodeForces - 1029A Many Equal Substrings

原题目链接CodeForces - 1029A


分类

CodeForces KMP


题意

这题是给一个长度为n的字符串 要拼成一个新串使得原来的串在新串中出现k次,用kmp预处理一下首尾的相同前后缀长度,然后就行了

Sample Input

3 4
aba
3 2
cat

Sample Output

ababababa
catcat

代码

31ms

/**
 * Author: GatesMa
 * Email: [email protected]
 * Todo: ACM Training
 * Date:2018/11/4
 */
#include <iostream>
#include <algorithm>
#include <string.h>
#include <stdio.h>
using namespace std;
const int maxn = 111;

char s[maxn];
int next[maxn];
void getNext()
{
    int len = strlen(s);
    int j = 0, k = -1;
    next[0] = -1;
    while (j < len)
    {
        if (k == -1 || s[j] == s[k])
        {
            j++;
            k++;
            next[j] = k;
        }
        else
        {
            k = next[k];
        }
    }
}
int main()
{
    int n, k;
    scanf("%d %d", &n, &k);
    scanf("%s", s);
    getNext();
    int cnt = next[n];
    if (cnt == 0)
    {
        for (int i = 0; i < k; i++)
        {
            printf("%s", s);
        }
        printf("\n");
    }
    else
    {
        printf("%s", s);
        for (int i = 0; i < k - 1; i++)
        {
            printf("%s", s + cnt);
        }
        printf("\n");
    }
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40456064/article/details/84143464