Beautiful Now
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1837 Accepted Submission(s): 689
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
原先想的爆搜复杂度特别高,dfs里面是两重循环,每次都得从0开始再选择后面交换的,但发现dfs每一位,会减少很大的复杂度,
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
int MAX = -1,MIN = inf;
int n,k;
int len;
char node[12];
void Swap(char *a,char *b)
{
char t = *a;
*a = *b;
*b = t;
}
void dfs(int key,int pos,int num)
{
if(key == 0){
while(pos < len){
num = num * 10 + node[pos] - '0';
pos++;
}
MIN = min(MIN,num);
MAX = max(MAX,num);
return ;
}
if(pos == len - 1){
num = num * 10 + node[pos] - '0';
MIN = min(MIN,num);
MAX = max(MAX,num);
return ;
}
for(int i = pos;i < len;++i)
{
if(pos == 0 && node[i] == '0')
continue;
Swap(&node[pos],&node[i]);
dfs(key - 1,pos + 1,num * 10 + node[pos] - '0');
Swap(&node[pos],&node[i]);
}
dfs(key,pos + 1,num * 10 + node[pos] - '0');
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
MAX = -1;
MIN = inf;
getchar();
scanf("%s %d",node,&k);
len = strlen(node);
dfs(k,0,0);
printf("%d %d\n",MIN,MAX);
}
return 0;
}