http://codeforces.com/problemset/problem/915/C
Problem Description
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 ≤ 10^18). 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
123
222
output
213
input
3921
10000
output
9321
input
4940
5000
output
4940
思路
DFS
代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(const char& a, const char& b) { return a > b; }
bool found, mark;
int cnt[10], ans[100];
string a, b;
void f(int idx)
{
if (found)
return;
if (idx == a.size())
{
for (int i = 0; i < (int)a.size(); i++)
cout << ans[i];
cout << endl;
found = true;
}
else for (int i = 9; i >= 0; i--)
{
if (idx && ans[idx - 1] < b[idx - 1] - '0')
mark = true;
if (mark)
{
if (cnt[i])
{
cnt[i]--;
ans[idx] = i;
f(idx + 1);
cnt[i]++;
}
}
else if (cnt[i] && i <= b[idx] - '0')
{
cnt[i]--;
ans[idx] = i;
f(idx + 1);
cnt[i]++;
}
}
}
int main()
{
cin >> a >> b;
if (a == b)
{
cout << a;
return 0;
}
else if (a.size() < b.size())
{
sort(a.begin(), a.end(), cmp);
cout << a << endl;
return 0;
}
else
{
for (int i = 0; i < (int)a.size(); i++)
cnt[a[i] - '0']++;
f(0);
}
}
本文介绍CodeForces平台上的915C题目的解题思路及实现代码。该题目要求对给定的两个正整数a和b进行处理,通过改变a的数字排列顺序来构造一个不超过b的最大可能数字。文章详细解释了解决方案,并提供了一个使用深度优先搜索(DFS)算法的C++实现。
1566

被折叠的 条评论
为什么被折叠?



