G-Long Beautiful Integer CodeForces-1268A (greedy)

G - Long Beautiful Integer CodeForces - 1268A

Title link

Ideas

  • Topic: Give us a number n, from left to right, the number on each base is \ (ar [1], ar [2], ar [3] ... ar [n] \) , there is Gives us a k, k <n, let us construct an m-digit y such that y> = x, each bit on y is \ (br [1], b [2] ... br [m ] \) , Meet the requirements in this br sequence: \ (br [i] == br [i + k] \) where i + k <= m, ask us what is the smallest y that meets the requirements?
  • analysis:
  1. This problem is obviously, we can make the constructed y as small as possible when m is the same as n.
  2. When constructing this m-bit y, as long as we have constructed the first k bits, the remaining numbers are naturally determined, and in order to make this number as small as possible, we must make the first k bits of y equal to x The first k bits, so that because br [i + k] = br [i], then the remaining n-k bits of y are determined. At this time, we compare y and x. If y is greater than x, it will be output directly, otherwise we You need to fine-tune the first k bits of y. At this time, it is clear that the first k bits of y are the same as the first k bits of x, so as long as we increase y to any one of k bits, we will definitely get y> x, it is required to construct the smallest y, and this fine-tuning is from the kth position to the first position, and the judgment is started. If it is 9, it is changed to 0, otherwise it is +1 and then break, and the answer is obtained

Code

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
void fre() { freopen("A.txt","r",stdin), freopen("Ans.txt","w",stdout); }
#define ll long long 


int main()
{
    /* fre(); */
    int n, k;
    cin >> n >> k;
    string s;
    cin >> s;
    string str;
    for(int i = 0; i < k; i ++)
        str += s[i];
    for(int i = k; i < n; i ++)
        str += str[i - k];
    if(str >= s)
    {
        cout << n << endl << str << endl;
    }
    else
    {
        for(int i = k - 1; i >= 0; i --)
        {
            if(str[i] != '9')
            {
                str[i] ++;
                break;
            }
            else
                str[i] = '0';
        }
        for(int i = k; i < n; i ++)
            str[i] = str[i - k];
        cout << n << endl << str << endl;
    }

    return 0;
}

Guess you like

Origin www.cnblogs.com/lql-nyist/p/12732907.html