暴力+贪心:
枚举变为K次0~9,每次都最小费用,最小字典序
最小字典序,贪心思路,同费用下,先大值变小值,从前往后边,再小值变大值,从后往前边。
注
:
\red{注:}
注:
string初始化 string s(S) 相当于赋值
string初始化 string s(L,‘9’) 相当于最大序
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<iostream>
#define MM(x) memset(x,0,sizeof(x))
#define INF 0x3f3f3f3f
using namespace std;
int N,K,L;
string S;
int cnt[15]; // 统计每个数字的数量
queue<pair<int,string> > q;
void solve(char key){
int need = K - cnt[key-'0'];
if(need <= 0){
q.push(make_pair(0,S));
return;
}
//cout<<key<<" need: "<<need<<endl;
string s(S);
char KeyUp = key + 1;
char KeyDown = key - 1;
int W = 0;
//cout<<"now:"<<key<<endl;
while(need){
//cout<<KeyUp<<" "<<KeyDown<<endl;
//cout<<"W:"<<W<<endl;
//cout<<"s:"<<s<<endl;
if(KeyUp <= '9'){
int w = abs(KeyUp - key);
for(int i=0; i<L && need;i++){
if(s[i] == KeyUp){
s[i] = key;
W += w;
need --;
}
}
if(need != 0) KeyUp++;
}
if(KeyDown >= '0'){
int w = abs(KeyDown - key);
for(int i=L-1;i>=0 && need ;i--){
if(s[i] == KeyDown){
s[i] = key;
W += w;
need --;
}
}
if(need != 0) KeyDown--;
}
}
//cout<<"W:"<<W<<endl;
//cout<<"s:"<<s<<endl;
//cout<<"\n\n\n"<<endl;
//cout<<W<<" "<<s<<endl;
q.push(make_pair(W,s));
}
int main(){
MM(cnt);
cin>>N>>K>>S;
L = S.length();
for(int i=0;i<L;i++) cnt[S[i]-'0'] ++;
//for(int i=0;i<10;i++) cout<<i<<" "<<cnt[i]<<endl;
for(int i=0;i<10;i++){
// 判断每个数字
solve(i + '0');
}
string ansS(L,'9');
int ansW = INF;
while(!q.empty()){
if(ansW > q.front().first){
ansW = q.front().first;
ansS = q.front().second;
}else if(ansW == q.front().first && ansS > q.front().second){
ansS = q.front().second;
}
q.pop();
}
cout<<ansW<<endl<<ansS<<endl;
return 0;
}