【HDU - 6351】Beautiful Now 【暴力DFS + 剪枝】

Problem Description
Anton has a positive integer n n , however, it quite looks like a mess, so he wants to make it beautiful after k k swaps of digits.
Let the decimal representation of n n as (x1x2xm)10 ( x 1 x 2 ⋯ x m ) 10 satisfying that 1x19,0xi9(2im) 1 ≤ x 1 ≤ 9 , 0 ≤ x i ≤ 9 ( 2 ≤ i ≤ m ) , which means n=mi=1xi10mi n = ∑ i = 1 m x i 10 m − i In each swap, Anton can select two digits xi and xj (1ijm) ( 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
题意: 给一个数字x,问最多交换k次的任意两个位数的情况下,最大和最小的x(不能够有前导零)
分析: 发现贪心贪不动,只能考虑dfs爆搜,很容易想到 n! n ! 的暴力做法,但是会T,这里要进行剪枝,如果是找最大,那么肯定比它大的才有交换的意义,最小同理。
代码

#include 
using namespace std;

typedef long long ll;
typedef unsigned long long ull;

const int N = (int)1e5 + 11;
const int M = (int)15e6 + 11;
const int MOD = (int)1e9 + 7;
const int INF = (int) 0x3f3f3f3f;

string mx, mn;
void find_mx(string s, int st, int k){
    if(mx < s) mx = s;
    if(k == 0 || st == s.size()) return ;
    char ma = s[st];
    for(int i = st + 1; i < s.size(); i++) ma = max(ma,  s[i]);
    if(ma == s[st]) find_mx(s, st + 1, k);
    else {
        for(int i = st + 1; i < s.size(); i++) {
            if(ma == s[i]){
                swap(s[i], s[st]);
                find_mx(s, st + 1, k - 1);
                swap(s[i], s[st]);
            }
        }
    }
}

void find_mn(string s, int st, int k){
    if(mn > s) mn = s;
    if(k == 0 || st == s.size()) return ;
    char mi = s[st];
    for(int i = st + 1; i < s.size(); i++) {
        if(st == 0 && s[i] == '0') continue; // 前导零去掉
        mi = min(mi,  s[i]);
    }
    if(mi == s[st]) find_mn(s, st + 1, k);
    else {
        for(int i = st + 1; i < s.size(); i++) {
            if(mi == s[i]){
                swap(s[i], s[st]);
                find_mn(s, st + 1, k - 1);
                swap(s[i], s[st]);
            }
        }
    }
}

int main(){
    int _;for(scanf("%d", &_); _; _--){
        string s; int k; cin>>s >>k;
        mx = "0000000000", mn = "9999999999";
        find_mx(s, 0, k);
        find_mn(s, 0, k);
        cout<" "<"\n";
    }
return 0;
}

你可能感兴趣的:(DFS,+,BFS)