Beautiful Now

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  . 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?

输入

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.

输出

For each test case, print in one line the minimum integer and the maximum integer which are separated by one space.

样例输入

5
12 1
213 2
998244353 1
998244353 2
998244353 3

样例输出

12 21
123 321
298944353 998544323
238944359 998544332
233944859 998544332

暴搜,具体看注释:
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
ll maxim=0,minum=1e10;
int indexx=0;
ll a[15]={0};
ll b[15]={0};
ll k;
ll sum=0;
void dfs1(int now,int cnt)//搜最大值
{
    if(cnt==k||now==indexx-1)//如果已交换,或者到了第N位
    {   ll temp=0;
        for(int i=0;i<indexx;i++)
        {
            temp=temp*10+a[i];
        }
        maxim=max(maxim,temp);
        return;
    }
    dfs1(now+1,cnt);//不交换这一位
    for(int i=now+1;i<indexx;i++)
    {
        if(a[now]<a[i])//贪心一下,当前这一位如果比下一位小,必然交换。不加貌似也能过
        {   swap(a[i],a[now]);
            dfs1(now+1,cnt+1);
            swap(a[i],a[now]);
        }
    }
}
void dfs2(int now,int cnt)//同理
{
    if(cnt==k||now==indexx-1)
    {
        ll temp=0;
        for(int i=0;i<indexx;i++)
        {
            temp=temp*10+a[i];
        }
        minum=min(minum,temp);
        return;
    }
    dfs2(now+1,cnt);
    for(int i=now+1;i<indexx;i++)
    {   if(now==0&&a[i]==0) continue;
        if(a[i]<a[now])
        {   swap(a[i],a[now]);
            dfs2(now+1,cnt+1);
            swap(a[i],a[now]);
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        ll x,i;
        indexx=0;
        maxim=0;
        minum=1e10;
        memset(a,0,sizeof(a));
        cin>>x>>k;
        while(x>0)
        {
            b[indexx++]=x%10;
            x/=10;
        }
        for(i=0;i<indexx;i++)//交换一下位置
        {
            a[i]=b[indexx-1-i];
        }
        //if(k>=index) k=index;
        dfs1(0,0);
        dfs2(0,0);
        cout<<minum<<" "<<maxim<<endl;
    }
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/zyf3855923/p/9439255.html