1. 程式人生 > 其它 >Codeforces Round #689 (Div. 2), based on Zed Code Competition 2020題解

Codeforces Round #689 (Div. 2), based on Zed Code Competition 2020題解

技術標籤:演算法

題目連結https://codeforces.com/contest/1461

A. String Generation

題目

One fall day Joe got bored because he couldn’t find himself something interesting to do. Marty suggested Joe to generate a string of length n to entertain him somehow. It didn’t seem particularly difficult, but Joe’s generated string had to follow these rules:

the string may only contain characters ‘a’, ‘b’, or ‘c’;
the maximum length of a substring of this string that is a palindrome does not exceed k.

A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. For example, strings “a”, “bc”, “abc” are substrings of a string “abc”, while strings “ac”, “ba”, “cba” are not.

在這裡插入圖片描述

A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, strings “abccba”, “abbba”, “aba”, “abacaba”, “a”, and “bacab” are palindromes, while strings “abcbba”, “abb”, and “ab” are not.

Now Joe wants to find any correct string. Help him! It can be proven that the answer always exists under the given constraints.

Input
Each test contains one or more test cases. The first line contains the number of test cases t (1≤t≤10).

The only line of each test case contains two integers n and k (1≤k≤n≤1000) — the required string length and the maximum length of a palindrome substring, respectively.

Output
For each test case, print any string that satisfies the conditions from the problem statement. If there are multiple correct answers, you can print any one of them. It can be proven that the answer always exists under the given constraints.

題意

構建一個僅有‘a’,‘b’,'c’組成的長度為n的字串,使得其最大的迴文子串長度為k(從左往右讀和從右往左讀是同樣的),tip:注意子串和子序列的區別,子串是連續的,子序列可以是不連續的

思路

我們可以設想最簡單的方法讓前k個全為a,這樣就滿足有k長度的迴文子串了,關鍵是要保證這個是最大的。我很自然想到,後面全都用bcbc…這樣會不會成立,但我發現bcb時產生了一個長度為3的迴文子串,那麼怎麼樣才能避免呢,兩個字元不可避免的會產生迴文子串,我想到可以把a加進來,aaaa…aabcabca…

程式碼

#include<bits/stdc++.h>
typedef long long ll;
 
using namespace std;
 
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,k;
        cin>>n>>k;
        for(int i=0;i<k;++i)
        cout<<"a";
        for(int i=0;i<n-k;++i)
        {
            char c='a'+(1+i)%3;
            cout<<c;
        }
        cout<<endl;
    }
    getchar();
    getchar();
}