杭电多校第五次 1002 Beautiful Now(dfs+贪心)

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

解析:将当前位与后面最小值交换为最优,但可能最小值有多个,比如 2311 交换两次 最小值为 1123 ,那么交换哪一个呢,我们dfs遍历一下所有最小值,然后求一个min,如果当前位是最小值,那么就不交换,由于最多交换9次所以复杂度不高。 求最大值同理
求最小值时不能将零换到首位

想到哪一步不会写了就暴力。。。0ms就过了。。

#include 
#define ll long long
#define mod 100003
using namespace std;
const int N=12;
string mi,mx;
int n;
void dfsmax(int x,string s,int k)
{

    mx=max(mx,s);
    if(k==0||x==n) return;
    char m=s[x];
    for(int i=x+1;iif(s[i]>m) m=s[i];
    }
    if(m==s[x])
    {
        dfsmax(x+1,s,k) ;
        return;
    }
    for(int i=x+1;iif(s[i]==m)
        {
            swap(s[x],s[i]);
            dfsmax(x+1,s,k-1);
            swap(s[x],s[i]);
        }
    }
}
void dfsmin(int x,string s,int k)
{
    mi=min(mi,s);
    if(k==0||x==n) return;
    char m=s[x];
    for(int i=x+1;iif(s[i]0||x==0&&s[i]!='0'))
            m=s[i];
    if(m==s[x])
    {
        dfsmin(x+1,s,k) ;
        return ;
    }
    for(int i=x+1;iif(s[i]==m)
        {
            swap(s[x],s[i]);
            dfsmin(x+1,s,k-1);
            swap(s[x],s[i]);
        }
    }
}
int main()
{
    #ifdef local
        freopen("D://rush.txt","r",stdin);
    #endif // local
    ios::sync_with_stdio(false),cin.tie(0);
    int t;
    cin>>t;
    while(t--)
    {
        string str;
        int k;
        cin>>str>>k;
        n=str.size();
        mx=str,mi=str;
        dfsmax(0,str,k);
        dfsmin(0,str,k);
        cout<' '<return 0;
}

你可能感兴趣的:(杂谈)