Codeforce915C
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.
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.
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
4940
题意:给两个数a和b,可以打乱a每位数的顺序组成一个新的数c,
求满足c<=b的最大,保证结果一定存在。
分析:先求出a的每位数字,然后排个序,再dfs。
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; int A[100],B[100],C[100],alen,blen; int vis[30],ans[30],K=-1; int cmp(int x,int y) {return x>y;} int f(int a[],long long x) { int len=0; while(x) { a[len++]=x%10; x/=10; } return len; } int dfs(int k)//k为当前构造到第k位数 { if(k==alen) return 1; int last=-1;//前一个数 for(int i=0;i<alen;i++) { if(last==A[i]) continue; if(vis[i]==0&&A[i]<=B[k]) { if(k==0&&A[i]==0) continue; vis[i]=1; ans[k]=A[i]; last=A[i]; if(A[i]<B[k]) { K=k; return 1; } if(dfs(k+1)) return 1; vis[i]=0; } } return 0; } int main() { long long a,b; scanf("%lld%lld",&a,&b); alen=f(A,a); blen=f(C,b); for(int i=0;i<blen;i++) B[i]=C[blen-i-1]; sort(A,A+alen,cmp);//排序 if(alen<blen) { for(int i=0;i<alen;i++) printf("%d",A[i]); printf("\n"); } else//alen==blen { dfs(0); if(K>=0) { for(int i=0;i<=K;i++) printf("%d",ans[i]); for(int i=0;i<alen;i++) if(!vis[i]) printf("%d",A[i]); } else { for(int i=0;i<alen;i++) printf("%d",ans[i]); } printf("\n"); } return 0; }
作者:ACRykl —— O ever youthful,O ever weeping!
出处:http://www.cnblogs.com/ACRykl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。