Long Beautiful Integer
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.
先做的C题,过的时候只有几百个人,所以排名挺高的,可是万万没想到,当还有6分钟比赛结束时,被hack了,哭了!!!
这道题就是一道贪心题,我们枚举位置 i (0<= i <=k-1),让 i + k 位置的数字都等于 i 位置数字,这是第一步;
第二步比较改变后的字符串和原字符串的大小,如果大,那么输出答案就行;
如果小,我们只要增大 k-1 这个位置的数字就行,问题就出在这里,当 k-1 位置的数字为 9
时,我们肯定不能增大,所以我们要找到 k-1—0 不为 9 的位置,把其位置的数加 1 就行。
坑点来了,当我们找到一个不为 9 的位置,让其位置的数加 1 时,它后面到 k-1 的位置的数可以直接变为 0 。唉
代码:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=100100;
const int M=1000100;
const LL mod=998244353;
int n,k;
string s;
int main(){
ios::sync_with_stdio(false);
cin>>n>>k;
cin>>s;
string c=s;
int l=c.length();
for(int i=0;i<k;i++){
for(int j=i+k;j<l;j+=k){
c[j]=c[i];
}
}
if(c>=s){
cout<<n<<endl;
cout<<c<<endl;
}
else{
cout<<n<<endl;
int g=k-1;
for(int i=k-1;i>=0;i--){
if(c[i]!='9'){
g=i;
break;
}
}
for(int i=g;i<l;i+=k){
c[i]=c[i]+1;
}
if(g!=k-1){
for(int i=g+1;i<k;i++){
c[i]='0';
for(int j=i+k;j<l;j+=k){
c[j]='0';
}
}
}
cout<<c<<endl;
}
return 0;
}