[CF][dfs]Permute Digits
Permute Digits
Description
You are given two positive integer numbers aa and bb. Permute (change order) of the digits of aato construct maximal number (without leading zeros) not exceeding bb.
It is allowed to leave aa as it is.
Input
The first line contains an integer aa (1≤a≤10181≤a≤1018).
The second line contains an integer bb (1≤b≤10181≤b≤1018).
Numbers don't contain leading zeroes. You can assume that answer exists.
Output
One line with a number, your answer.
Examples
Input
123
222
Output
213
正确解法:
如果a的位数小于b的话就从大到小输出就好
如果等于的话,前面要跟b相等或者小于,如果前面一位小于的话后面就可以弄大的。
如果一直相等的话,就弄小于等于的。
1 #include<iostream> 2 #include<cstdio> 3 #include<string> 4 #include<cstring> 5 #include<map> 6 #include<set> 7 #include<algorithm> 8 #include<cmath> 9 #include<cstdlib> 10 using namespace std; 11 char s1[30], s2[30]; 12 int a[30], b[30], c[30],len1,len2,flag,ff=0; 13 void dfs(int id) 14 { 15 if(ff==1) return ; 16 if(id==len2) 17 { 18 for(int i=0;i<len2;i++) 19 printf("%d",c[i]); 20 printf("\n"); 21 ff=1; 22 } 23 if( id!=0 && c[id-1]<b[id-1] ) 24 flag=1; 25 for(int i=9;i>=0;i--) 26 { 27 if(a[i]) 28 { 29 if(flag) 30 { 31 a[i]--; 32 c[id]=i; 33 dfs(id+1); 34 a[i]++; 35 } 36 else if(i<=b[id]) 37 { 38 a[i]--; 39 c[id]=i; 40 dfs(id+1); 41 a[i]++; 42 } 43 } 44 } 45 } 46 int main() 47 { 48 gets(s1); 49 gets(s2); 50 len1=strlen(s1),len2=strlen(s2); 51 for(int i=0;i<len1;i++) 52 a[s1[i]-'0']++; 53 if(len1<len2) 54 { 55 for(int i=9;i>=0;i--) 56 while(a[i]--) 57 printf("%d",i); 58 printf("\n"); 59 return 0; 60 } 61 for(int i=0;i<len2;i++) 62 b[i]=s2[i]-'0'; 63 dfs(0); 64 return 0; 65 }
在网上抄的的答案
1 #include<bits/stdc++.h> 2 using namespace std; 3 char a[20],b[20],c[20]; 4 int main() 5 { 6 int m; 7 while(cin>>a>>b) 8 { 9 m=strlen(a); 10 sort(a,a+m); 11 if(m<strlen(b)) 12 { 13 for(int i=m-1; i>=0; i--) 14 cout<<a[i]; 15 return 0; 16 } 17 strcpy(c,a); 18 for(int i=0; i<m; i++) 19 { 20 strcpy(a,c); 21 for(int j=i; j<m; j++) 22 { 23 swap(a[i],a[j]); 24 if(strcmp(a,b)!=1) 25 strcpy(c,a); 26 } 27 } 28 puts(a); 29 } 30 return 0; 31 }
No matter how you feel, get up , dress up , show up ,and never give up.