http://acm.fzu.edu.cn/problem.php?pid=2111
/*0ms,232KB*/
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int mx = 1005;
char s[mx];
deque<int> pos[10];
int main()
{
int t, n, m, i, maxpos, minval, beg;
scanf("%d", &t);
while (t--)
{
scanf("%s%d", s, &m);
n = strlen(s);
if (m)
{
///注意s没有前导0
for (i = 0; i < 10; ++i) pos[i].clear();
for (i = 0; i < n; ++i) pos[s[i] & 15].push_back(i);
///先把开头的那个数尽量换小,但不能用0换
for (i = 1; i < (s[0] & 15); ++i)
{
if (pos[i].size())
{
swap(s[0], s[pos[i].back()]);
--m;
break;
}
}
///然后就按一般的思路交换了
for (beg = 1; beg <= m; ++beg)
{
maxpos = 0, minval = 10;
for (i = n - 1; i > beg; --i)
{
if ((s[i] & 15) < minval)
{
minval = s[i] & 15;
maxpos = i;
}
}
for (i = beg; i < maxpos; ++i)
{
if ((s[i] & 15) > minval)
{
swap(s[i], s[maxpos]);
break;
}
}
if (i == maxpos) ++m;
}
}
puts(s);
}
return 0;
}