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
这份代码是参考后发现的最容易理解且最简单的代码,思路明确。
#include<stdio.h>
#include<string>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int Hash[20];
int vis[20];
int n,k;
bool check() //检查交换次数
{
fill(vis,vis+n,0);
int sw=0;
for(int i=0;i<n;i++)
{
if(vis[i])continue;
int x=0;
while(vis[i]==0)
{
x++;
vis[i]=1;
i=Hash[i];
}
sw+=x-1;
if(sw>k)
return false;//为了不超时这里不符合条件的要提前退出
}
return true;
}
int main()
{
char s[20];
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s%d",s,&k);
n=strlen(s);
for(int i=0;i<n;i++)
{
Hash[i]=i;
}
int Min=1e9+7;
int Max=0;
do{
if(s[Hash[0]]!='0'&&check())//不能有前导0,且交换次数等于k;
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum*10+s[Hash[i]]-'0';
}
if(sum<Min)
{
Min=sum;
}
if(sum>Max)
{
Max=sum;
}
}
}while(next_permutation(Hash,Hash+n));//全排列
printf("%d %d\n",Min,Max);
}
}