比赛 20160412 评测结果 AAAAAAAAAA
题目名称 饭堂 最终得分 100
用户昵称 Fmuckss 运行时间 0.039 s
代码语言 C++ 内存使用 0.50 MiB
提交时间 2016-04-12 10:55:35
显示代码纯文本
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1e4+10;
const int inf = 1e9;
int n, k;
int a[maxn];

struct cost {
	int c, tar, fix;//优先级为如果要把数改小或不变为1,改大为3 
	cost () { c = tar = fix = 0; }
	bool operator < (const cost &b) const {
		if(fix != b.fix) return c == b.c ? fix < b.fix : c < b.c; //优先级越小越靠前 
		if(fix == 1) return c == b.c ? tar < b.tar : c < b.c;//改小的位置约考前越优 
		if(fix == 3) return c == b.c ? tar > b.tar : c < b.c;//改大的越靠后越优 
	}
}cs[maxn];

struct sol {
	int num[maxn], c;
	sol() { memset(num, 0, sizeof(num)); c = 0; }
	bool operator < (const sol &b) const {
		if(c == b.c) {
			for(int i = 1; i <= n; i++) {
				if(num[i] < b.num[i]) return true;
				if(num[i] > b.num[i]) return false;
			}
		}
		return c < b.c;
	} 
}s;


void read() {
	scanf("%d %d", &n, &k);
	char tmp = getchar();
	while(tmp < '0' || tmp > '9') tmp = getchar();
	for(int i = 1; i <= n; i++) {
		a[i] = tmp - '0';
		tmp = getchar();
	} 
}
void solve() {
	s.c = inf;
	for(int i = 0 ; i <= 9; i++) {
		sol tmp;
		for(int j = 1; j <= n; j++) {
			if(a[j] >= i) {
				cs[j].c = a[j]-i;
				cs[j].fix = 1;
			} else {
				cs[j].c = i-a[j];
				cs[j].fix = 3;
			}
			cs[j].tar = j;
		}
		sort(cs+1, cs+1+n);
		int cnt = 0;
		for(int j = 1; j <= n; j++) {
			if(cnt < k) {
				tmp.c += cs[j].c;
				tmp.num[cs[j].tar] = i;
				cnt++;
			}
			else tmp.num[cs[j].tar] = a[cs[j].tar];
		}
		if(tmp < s) s = tmp;
	}
	printf("%d\n", s.c);
	for(int i = 1; i <= n; i++) {
		printf("%d", s.num[i]);
	}
}
int main() {
	freopen("fancy.in", "r", stdin);
	freopen("fancy.out", "w", stdout);
	read();
	solve();
	return 0;
}