HDU 6351 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

题意:给你一个数字字符串,让你交换k次,求字典序最小和字典序最大.
分析:
直接DFS暴力,但是贪心减枝才能过,mark一下这种减枝策略:比如求最小值,只和x位之后的最小数字交换,并不是全都暴力交换,最大值也是这样.

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <iostream>
#define rep(i, a, b) for(int i = a; i <= b; ++i)
using namespace std;

typedef long long LL;
int len;
string ans1, ans2;

inline void dfs1(string ch, int res, int x) {
    if(x == 1 && ch[0] == '0') return ;
    if(ch < ans1) ans1 = ch;
    if(!res || x == len) return ;
    dfs1(ch, res, x + 1);
    char str = '9';
    rep(i, x, len - 1) {//减枝才能过
        if(!x && ch[i] == '0') continue;//减枝时注意这个
        str = min(str, ch[i]);
    }
    rep(i, x, len - 1) {
        if(str != ch[i]) continue;
        swap(ch[x], ch[i]);
        dfs1(ch, res - 1, x + 1);
        swap(ch[x], ch[i]);
    }
}

inline void dfs2(string ch, int res, int x) {
    if(x == 1 && ch[0] == '0') return ;
    if(ch > ans2) ans2 = ch;
    if(!res || x == len) return ;
    dfs2(ch, res, x + 1);
    char str = '0';
    rep(i, x, len - 1) str = max(str, ch[i]);
    rep(i, x, len - 1) {
        if(str != ch[i]) continue;
        swap(ch[x], ch[i]);
        dfs2(ch, res - 1, x + 1);
        swap(ch[x], ch[i]);
    }
}

int main() {
    int T, k; string s;
    scanf("%d", &T);
    while(T--) {
        cin >> s >> k;
        len = s.length();
        ans1 = ""; ans1[len] = '\0';
        rep(i, 0, len - 1) ans1 += '9';
        dfs1(s, k, 0);
        ans2 = ""; ans2[len] = '\0';
        rep(i, 0, len - 1) ans2 += '0';
        dfs2(s, k, 0);
        cout << ans1 << ' ' << ans2 << endl;
    }
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值