cf Permute Digits(dfs)

C. Permute Digits

You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.

It is allowed to leave a as it is.

Input

The first line contains integer a (1 ≤ a ≤ 1018). The second line contains integer b (1 ≤ b ≤ 1018). Numbers don't have leading zeroes. It is guaranteed that answer exists.

Output

Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists.

The number in the output should have exactly the same length as number a. It should be a permutation of digits of a.

Examples
input
Copy
123
222
output
Copy
213
input
Copy
3921
10000
output
Copy
9321
input
Copy
4940
5000
output
Copy
4940


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;

int f, la, lb, vis[11];
char a[20], b[20], ans[20];

void dfs(int dep, int flag)//参数:当前位,结果当前位是否比 b小 ,dep是搜索深度
{
    if (f == 1) return; //如果已经找到结果则退出 
    if (dep == la)
    { //找到结果,将标志 f=1,并退出 
        f = 1;
        return;
    }
    for (int i = 9; i >= 0; i--)
    { //从大到小扫描数字 
        if (vis[i])//如果有可用数字 ,数组中0~9出现的次数不为零
        {
            if (flag || b[dep] == i + '0')//如果已经出现某一位比 b小的或这当前位相等 
            {
                vis[i]--;
                ans[dep] = i + '0'; //记录结果 
                dfs(dep + 1, flag); //处理下一个位置 
                if (f) return; //如果找到结果则退出 
                vis[i]++; //回溯时还原,重新处理当前位 
            }
            else if (b[dep]>i + '0')
            { //结果的当前位比 b小 
                vis[i]--;
                ans[dep] = i + '0'; //记录结果 
                dfs(dep + 1, 1); //处理下一位,并将 flag=1 
                if (f) return; //如果找到结果则退出 
                               //vis[i]++; //由于这个分支只可能进入一次,不还原也可以 
            }
        }
    }
}
int main()
{
    int i;
    while (cin >> a >> b)
    {
        la = strlen(a);
        lb = strlen(b);
        if (la<lb)
        { //当位数不同时 
            sort(a, a + la);
            for (i = la - 1; i >= 0; i--)
                cout << a[i];
            cout << endl;
        }
        else
        { //当位数相同时 
            f = 0;
            memset(vis, 0, sizeof(vis));
            for (i = 0; i<la; i++)
                vis[a[i] - '0']++; //统计 a中每个数出现的次数 
            dfs(0, 0); //深搜 
            for (i = 0; i<la; i++)
                cout << ans[i];
            cout << endl;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/-citywall123/p/9511612.html