寻找最大数(三)
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
2
-
描述
-
给出一个整数N,每次可以移动2个相邻数位上的数字,最多移动K次,得到一个新的整数。
求这个新的整数的最大值是多少。
-
输入
-
多组测试数据。
每组测试数据占一行,每行有两个数N和K (1 ≤ N≤ 10^18; 0 ≤ K ≤ 100).
输出
- 每组测试数据的输出占一行,输出移动后得到的新的整数的最大值。 样例输入
-
1990 1 100 0 9090000078001234 6
样例输出
-
9190 100 9907000008001234
-
多组测试数据。
比如N=1234 k=3,head(数组下标)初始值为0,先找出[ a[head] , a[head+3] ]中的最大值,若该最大值不为a[head],将该最大值交换到head处,此时k=0结束,最大值为4123;
再比如N=1234 k=5,head(数组下标)初始值为0,先找出[ a[head] , a[head+3] ](因为a[head+5]超出了数组,将其改为数组最后一位元素)中的最大值,若该最大值不为a[head],将该最大值交换到head处,此时k=2,head=1,找出[ a[head] , a[head+2] ] (要判断a[head+2]有无超出数组,有则判断至数组最后一位即可)最大值,若该最大值不为a[head],将该最大值交换到head处,此时k=0,退出,结果为4312。
# include <stdio.h>
# include <string.h>
int main()
{
int pos, len, temp, imax, head, tail, i, j, n;
char s[20];
while(scanf("%s%d",&s,&n) != EOF)
{
imax = head = 0;
len = strlen(s);
while(1)
{
imax = 0;
if(!n || head==len)
break;
tail = head+n;
if(tail >= len)
tail = len-1;
for(i=tail; i>=head; --i)//寻找head到tail的最大值位置,若不在head处,将最大值交换到head处。
{
if(s[i]>=imax)
{
pos = i;
imax = s[i];
}
}
if(pos != head)
{
temp = s[pos];
for(j=pos; j>head; --j)
{
s[j] = s[j-1];
--n;
}
s[head] = temp;
}
++head;
}
printf("%s\n",s);
}
return 0;
}