C. Long Beautiful Integer ------ thinking (a little difficult)

You are given an integer x of n digits a1,a2,…,an, which make up its decimal notation in order from left to right.

Also, you are given a positive integer k<n.

Let’s call integer b1,b2,…,bm beautiful if bi=bi+k for each i, such that 1≤i≤m−k.

You need to find the smallest beautiful integer y, such that y≥x.

Input
The first line of input contains two integers n,k (2≤n≤200000,1≤k<n): the number of digits in x and k.

The next line of input contains n digits a1,a2,…,an (a1≠0, 0≤ai≤9): digits of x.

Output
In the first line print one integer m: the number of digits in y.

In the next line print m digits b1,b2,…,bm (b1≠0, 0≤bi≤9): digits of y.

Examples
inputCopy

3 2
353
outputCopy
3
353
inputCopy
4 2
1234
outputCopy
4
1313

The meaning of problems: Given a sequence of a length of n, a value of x, let you construct a sequence of b satisfies b [i] = b [i + k], the value of y, y> = x, and y minimum.

Analysis: for n bits 99 ... 999 must be optimal, so the length of the determined positive or y n!
We can give the k-1 bits +, thus can form the minimum optimal solution and> = x. but before that we will have two things to occur.
The first is the optimal solution in itself.
The second is that we repeat the previous k bits, whether resulting y> = x such as greater is the answer we need.
The third is beginning to talk about, but also subdivided two kinds.
1) The first digit is 9 k-1, this time we want to produce +1 carries. Need to deal with it
2) the k-1 bits are not 9, we will repeat the previous k bits.

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10000;
string s;
int a[N],b[N],c[N],n,k;
int main()
{
	cin>>n>>k;
	cin>>s;
	for(int i=0;i<n;i++) a[i]=s[i]-'0';
	int f=1;
	for(int i=0;i<n-k;i++) //检查本身是否存在正确性 
	{
		if(a[i]!=a[i+k])
		{
			f=0;
			break;
		}
	}
	if(f==1)
	{
		cout<<n<<endl;
		cout<<s<<endl;
		return 0;
	}
	for(int i=0;i<n;i++) b[i]=a[i];      //重复前k位,是否能构成>=x 
	for(int i=k;i<n;i++) b[i]=b[i-k];
	 f=1;
	for(int  i=0;i<n;i++)
	{
		if(a[i]==b[i]) continue; //相等跳过 
		if(a[i]>b[i] ) f=0; //得到比原来的更小了不行 
		if(a[i]<b[i]) break;//得到比原来的大,就可以了。因为后继一定满足 
	}
	if(f==1)
	{
		cout<<n<<endl;
		for(int i=0;i<n;i++) cout<<b[i];
		cout<<endl;
		return 0;
	 } 
	 for(int i=k-1;i>=0;i--) //从第k-1位+1,这样会构成最优解就是最小值的,如果是9肯定产生进位,我们先跳过,等遇到不是9的情况,再给后面赋值0 
	 {
	 	if(a[i]==9) continue;
	 	a[i]=a[i]+1;
	 	for(int j=i+1;j<=k-1;j++) a[j]=0;
	 	for(int j=k;j<n;j++) a[j]=a[j-k];
	 	cout<<n<<endl;
	 	for(int j=0;j<n;j++) cout<<a[j];
	 	cout<<endl;
	 	return 0;
	 }
}
Published 309 original articles · won praise 6 · views 5263

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/104076282