codeforces 915 C. Permute Digits【DFS + 离散化】

C. Permute Digits

time limit per test1 second
memory limit per test256 megabytes

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.

123
222

213

3921
10000

9321

4940
5000

output

4940

#include<bits/stdc++.h>

using namespace std;

int vis[20];
int a2[22];
int len;
int res[22];
bool tag = false;

void dfs(int idx,bool flg) {
if(tag) return ;
if(idx == len) {
tag = true;return;
}
int t;
for(int i = 9;i >= 0;i--) {
if(vis[i] > 0) {
if(flg || i == a2[idx]) {
vis[i]--;
res[idx] = i;
dfs(idx+1,flg);
if(tag) return ;
vis[i]++;
} else if(i < a2[idx]) {
vis[i]--;
res[idx] = i;
dfs(idx+1,true);
if(tag) return ;
vis[i]++;
}
}
}
}

int main(){
ios_base::sync_with_stdio(0);
string s1,s2;cin>>s1>>s2;
if(s1.size() < s2.size()) {
sort(s1.rbegin(),s1.rend());
cout<<s1<<endl;
} else {
len = s1.size();
for(int i = 0;i < len;i++) {
vis[s1[i] - '0']++;
}

for(int i = 0;i < len;i++) {
a2[i] = s2[i] - '0';
}
dfs(0,false);
for(int i = 0;i < len;i++) {
cout<<res[i];
}cout<<endl;
}

return 0;
}
• 如有错误或遗漏，请私聊下UP，thx