A. Many Equal Substrings
You are given a string tt consisting of nn lowercase Latin letters and an integer number kk.
Let's define a substring of some string ss with indices from ll to rr as s[l…r]s[l…r].
Your task is to construct such string ss of minimum possible length that there are exactly kkpositions ii such that s[i…i+n−1]=ts[i…i+n−1]=t. In other words, your task is to construct such string ss of minimum possible length that there are exactly kk substrings of ss equal to tt.
It is guaranteed that the answer is always unique.
Input
The first line of the input contains two integers nn and kk (1≤n,k≤501≤n,k≤50) — the length of the string tt and the number of substrings.
The second line of the input contains the string tt consisting of exactly nn lowercase Latin letters.
Output
Print such string ss of minimum possible length that there are exactly kk substrings of ss equal to tt.
It is guaranteed that the answer is always unique.
Examples
input 3 4 aba ababababa input 3 2 cat output catcat
題意:給定一個字符串,要求你構造出一個字符串,使得原串在新串中出現t次。
解法:暴力 || kmp next數組
考慮樣例中的aba,要使新串中出現2次,並不需要abaaba只需要ababa
會出現這樣的原因是由於aba存在相等的前綴和後綴。
所以我們需要找到最長的前綴和後綴相等的字符串長度。
只需要先輸出一遍原串,再輸出原串除了前綴的那部分即可
很自然的可以想到kmp的next數組。
自此又複習了一遍kmp的寫法。
由於數據比較小,所以也可以直接暴力求子串(用substr)
得解。
KMP思想:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <vector>
#define vi vector<int>
#define ll long long
#define P pair<int,int>
using namespace std;
const int maxn = 1e6 + 10;
int nxt[maxn];
void solve(string s)
{
int i = 0, j = 1;
while(j < s.length())
{
if(s[i] == s[j])
{
nxt[j] = i + 1;
i++;
j++;
continue;
}
else
{
if(i == 0)
{
nxt[j] = 0;
j++;
continue;
}
i = nxt[i - 1];
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
string s;
cin >> s;
solve(s);
cout << s;
string t = s.substr(nxt[s.length() - 1], s.length() - nxt[s.length() - 1]);
k--;
while(k--)
cout << t;
cout << endl;
return 0;
return 0;
}
暴力:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <vector>
#define vi vector<int>
#define ll long long
#define P pair<int,int>
using namespace std;
const int maxn = 1e6 + 10;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
string s;
cin >> s;
//solve(s);
int temp = 0;
for(int i = 1; i < s.length(); i++)
if(s.substr(0, i) == s.substr(s.length() - i, i))
temp = i;
cout << s;
k--;
while(k--)
cout << s.substr(temp);
cout << endl;
return 0;
}