3.12周赛 E

来源:互联网 发布:淘宝不申请售后就退款 编辑:程序博客网 时间:2024/06/02 05:03

题目链接:http://codeforces.com/problemset/problem/118/C

比赛的时候没有看,赛后听了下李大神的讲解,因为那时候还没有看题,对于他说的遍历0-9每个数字有点不懂。搜了下题解。

参考题解链接:http://www.xuebuyuan.com/1552825.html

就是对于0-9 ,从此时的这个数开始向两边找,意思就是将比他大一,比他小一的数换成他直到所需要相同的位数达到(要注意的就是比他大的数要从前往后开始换,比他小的数要从最后面往前面换,这样能保证对于当前数字来说的字典序最小),记录下花费,与最小花费比较,如果更小就拷贝这组到minstr,如果一样在比较下字典序。。这样遍历望以后就产生了花费最小,且字典序最小的序列。。。

代码:

 

#include<iostream>#include<cstdio>#include<cstring>#define INF 1000000000;using namespace std;char s[100010],minstr[100010],ss[100010];int count[10];int main (){int n,k;while(cin >> n >> k){int ans;int min = INF;memset(s,'\0',sizeof(s));memset(count,0,sizeof(count));for(int i = 0;i < n;i++){cin >> s[i];count[s[i]-'0']++;}for(int i = 0;i < 10;i++){int t = k;if(count[i] >= t){min = 0;strcpy(minstr,s);break;}else{strcpy(ss,s);t -= count[i];  //剩几位ans = 0;for(int l=i-1,r=i+1;t;r++,l--){if(t&&r<10&&count[r]){int temp = (count[r]>t?t:count[r]);t -= temp;ans += temp*(r-i);//int a = 0;for(int j = 0;j < n&&temp;j++){if(ss[j]-'0' == r){temp--;//a++;ss[j] = i+'0';}//if(a == temp)break;}}if(t&&l>=0&&count[l]){int temp = (count[l]>t?t:count[l]);t -= temp;ans += temp*(i-l);//int a = 0;for(int j = n-1;j>=0&&temp;j--){if(ss[j]-'0' == l){temp--;//a++;ss[j] = i+'0';}//if(a == temp) break;}}} }if(min > ans){min = ans;strcpy(minstr,ss);}else if(min == ans){if(strcmp(minstr,ss)>0)strcpy(minstr,ss);}}printf("%d\n%s\n",min,minstr);}return 0;}


0 0
原创粉丝点击