Beautiful Now
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 4513 Accepted Submission(s): 457
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
Statistic | Submit | Clarifications | Back
题目大意:给出一个不超过10e9的数,要求交换k次后求出最小值和最大值。两个问题相互独立,自己可以和自己交换。
解题思路:我们尝试了一下贪心,发现对于许多情况都无法解决,索性来了一个暴力的搜索。就是如果当前位后边有比它小的
我们就交换这两个数字,然后用这个数字重新去搜。找最大的和最小的方法一样。最后就是交换次数的控制,因为我感觉这个如果我们每次都交换两个数的话,在不超过数字长度的情况下一定能搜到最小的,所以就取搜的次数最小的那个。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define LL long long
int cnt=1;
int mm=0x3f3f3f3f;
int ma=-1;
int ans[15];
int ans1[15];
void dfs(int k)
{
if(k==0)return ;
dfs(k/10);
ans[cnt++]=k%10;
}
void dfs1(int k)
{
if(k==0)return ;
dfs1(k/10);
ans1[cnt++]=k%10;
}
int cal()
{
int sum=0;
for(int i=1;i<cnt;i++)
{
sum=sum*10+ans[i];
}
return sum;
}
int cal1()
{
int sum=0;
for(int i=1;i<cnt;i++)
{
sum=sum*10+ans1[i];
}
return sum;
}
void dfsmin(int k,int step,int ci)
{
//cout<<k<<" "<<step<<" "<<ci<<endl;
mm=min(k,mm);
if(step>min(ci,cnt))return ;
for(int i=step+1;i<cnt;i++)
{
if(step==1&&ans[i]==0)continue;
if(ans[i]<ans[step])
{
swap(ans[i],ans[step]);
int tmp=cal();
dfsmin(tmp,step+1,ci);
swap(ans[i],ans[step]);
}
}
dfsmin(k,step+1,ci+=1);
}
void dfsmax(int k,int step,int ci)
{
ma=max(k,ma);
if(step>min(ci,cnt))return ;
for(int i=step+1;i<cnt;i++)
{
if(step==1&&ans1[i]==0)continue;
if(ans1[i]>ans1[step])
{
swap(ans1[i],ans1[step]);
int tmp=cal1();
dfsmax(tmp,step+1,ci);
swap(ans1[i],ans1[step]);
}
}
dfsmax(k,step+1,ci+=1);
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n,ci;
cin>>n>>ci;
dfs(n);
cnt=1;
dfs1(n);
dfsmin(n,1,ci);
cout<<mm;
dfsmax(n,1,ci);
cout<<" "<<ma<<endl;
cnt=1;
mm=0x3f3f3f3f;
ma=-1;
}
}