Beautiful Now
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1930 Accepted Submission(s): 730
Problem Description
Anton has a positive integer n, however, it quite looks like a mess, so he wants to make it beautiful after k swaps of digits.
Let the decimal representation of n as (x1x2⋯xm)10 satisfying that 1≤x1≤9, 0≤xi≤9 (2≤i≤m), which means n=∑mi=1xi10m−i. In each swap, Anton can select two digits xi and xj (1≤i≤j≤m) and then swap them if the integer after this swap has no leading zero.
Could you please tell him the minimum integer and the maximum integer he can obtain after k swaps?
Input
The first line contains one integer T, indicating the number of test cases.
Each of the following T lines describes a test case and contains two space-separated integers n and k.
1≤T≤100, 1≤n,k≤109.
Output
For each test case, print in one line the minimum integer and the maximum integer which are separated by one space.
Sample Input
5
12 1
213 2
998244353 1
998244353 2
998244353 3
Sample Output
12 21
123 321
298944353 998544323
238944359 998544332
233944859 998544332
Source
2018 Multi-University Training Contest 5
#include <bits/stdc++.h>
using namespace std;
int a[20], b[20];
int len;
int Min, Max;
void dfs1(int s, int t, int k)
{
if (k == 0)
{
int sum = 0;
for (int i = 1; i <= len; i++)
sum = sum * 10 + a[i];
Min = min(Min, sum);
return;
}
for (int i = s; i <= len; i++)
{
int t = a[i];
for (int j = i; j <= len; j++)
{
if (i == 1 && a[j] == 0)
continue;
if (t > a[j])
t = a[j];
} /// 从当前位起往后最小的值
for (int j = i; j <= len; j++)
{
if (a[j] == t)
{
swap(a[i], a[j]); /// 交换一个满足条件的j
dfs1(i + 1, len, k - 1); /// 从i + 1开始到len交换k - 1次
swap(a[i], a[j]); /// 还原 交换下一个满足条件的j
}
}
}
}
void dfs2(int s, int t, int k)
{
if (k == 0)
{
int sum = 0;
for (int i = 1; i <= len; i++)
sum = sum * 10 + b[i];
Max = max(Max, sum);
return;
}
for (int i = s; i <= len; i++)
{
int t = b[i];
for (int j = i; j <= len; j++)
{
if (t < b[j])
t = b[j];
}
for (int j = i; j <= len; j++)
{
if (b[j] == t)
{
swap(b[i], b[j]);
dfs2(i + 1, len, k - 1);
swap(b[i], b[j]);
}
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("D:\\in.txt", "r", stdin);
#endif // ONLINE_JUDGE
int T;
scanf("%d", &T);
while (T--)
{
char ch[20]; int k;
scanf("%s %d", ch + 1, &k);
len = strlen(ch + 1);
for (int i = 1; i <= len; i++)
{
a[i] = ch[i] - '0';
b[i] = a[i];
}
/// 数组长度为len, 最多交换len - 1次可得最值
/// 如 len = 9, 234567891 交换8次得最小值123456789
if (k >= len - 1)
{
sort(a + 1, a + len + 1);
sort(b + 1, b + len + 1);
int t = 1;
while (a[t] == 0)
t++;
swap(a[t], a[1]);
for (int i = 1; i <= len; i++)
printf("%d", a[i]);
printf(" ");
for (int i = len; i >= 1; i--)
printf("%d", b[i]);
printf("\n");
continue;
}
Min = 0x7fffffff, Max = 0;
dfs1(1, len, k); /// 从1到len交换k次
dfs2(1, len, k);
printf("%d %d\n", Min, Max);
}
return 0;
}