The main idea: to s,t two strings, the characters in s are re-assembled to construct a new string with the smallest dictionary order but larger than T.
Title Analysis: First count the number of letters in S, and then from the left end of T to the right end of each of the new string to construct the letter. This process is achieved by backtracking, because the dictionary order can be stopped immediately when it is larger than T, so it doesn't actually take much time.
The code is as follows:
# include<iostream># include<string># include<algorithm># include<cstdio># include< vector># include<cstring>using namespace Std;int n,m;int vis[5005];string p,q;int cnt[26];int ans[5005];int Isbigger () {for (int i=1;i<=ans[0]&&i-1<m;++i) {if (ans[i]<q[i-1]-' a ') return-1; if (ans[i]>q[i-1]-' a ') return 1; } if (ans[0]==m) return 0; else if (ans[0]>m) return 1; else return-1;} BOOL Dfs (int i) {int k=isbigger (); if (k>0) return true; if (i>=m) {if (k>0) return true; else if (k==0) return n>m; else if (k<0) return false; } for (char c=q[i];c<= ' z '; ++c) {if (cnt[c-' a ']==0) continue; --cnt[c-' a ']; ans[++ans[0]]=c-' a '; if (Dfs (i+1)) return true; --ans[0]; ++cnt[c-' a ']; } return false;} int main () {//while (cin>>p>>q) {cin>>p>>q; N=p.size (); M=q.size (); memset (Cnt,0,siZeof (CNT)); for (int i=0;i<n;++i) ++cnt[p[i]-' a ']; ans[0]=0; if (!dfs (0)) printf (" -1\n"); else{for (int i=1;i<=ans[0];++i) cout<< (char) (ans[i]+ ' a '); for (int i=0;i<26;++i) for (int j=0;j<cnt[i];++j) cout<< (char) (i+ ' a '); cout<<endl; }//} return 0;}
Coderforce 180d-name (construction + backtracking)