Coderforce 180d-name (construction + backtracking)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.