Beautiful Now
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
T otal Submission(s): 1719 Accepted Submission(s): 646
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
Recommend
chendu | We have carefully selected several similar problems for you: 6361 6360 6359 6358 6357
题意:每次交换两个数字(可以自己交换自己),最多交换k次,问交换后的最大最小值是多少。
每次找出当前序列中的所有的最小值,与最大数位交换,如果最大数位是最小值则开始下一位,最大值同理。
多校的时候一开始忽略了自己交换自己的情况,写的很复杂,后来修改了之后又遗漏了交换后要枚举最小值所在的不同位置,思路是对的,很可惜最后没有A掉这道题。
#include<bits/stdc++.h>
using namespace std;
char n[20],ans[20],s[20];
int k,T,len,tp;
void dfs(int now,int lef)
{
if(now>=len||lef==0)
{if(strcmp(ans,s)>0) strcpy(ans,s);return;}
int temp=now;
for(int i=now;i<=len;i++)
if(s[temp]>s[i]) temp=i;
if(temp==now)
dfs(now+1,lef);
else
{
for(int i=now;i<=len;i++)
{
if(s[i]==s[temp])
{
swap(s[i],s[now]);
dfs(now+1,lef-1);
swap(s[i],s[now]);
}
}
}
}
void dfsmax(int now,int lef)
{
if(now>=len||lef==0)
{if(strcmp(ans,s)<0) strcpy(ans,s);return;}
int temp=now;
for(int i=now;i<=len;i++)
if(s[temp]<s[i]) temp=i;
if(temp==now)
dfsmax(now+1,lef);
else
{
for(int i=now;i<=len;i++)
{
if(s[i]==s[temp])
{
swap(s[i],s[now]);
dfsmax(now+1,lef-1);
swap(s[i],s[now]);
}
}
}
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%[^ ] %d",n,&k);
len=strlen(n+1);
strcpy(ans,n);
strcpy(s,n);
{//最小值
tp=1;
for(int i=1;i<=len;i++)
if(n[i]<n[tp]&&n[i]!='0')
tp=i;
if(tp==1)
dfs(2,k);
else
{
for(int i=1;i<=len;i++)
if(s[i]==s[tp])
{
swap(s[i],s[1]);
dfs(2,k-1);
swap(s[i],s[1]);
}
}
printf("%s ",ans+1);
}
{//最大值
strcpy(ans,n);
dfsmax(1,k);
printf("%s\n",ans+1);
}
}
return 0;
}