寒假集訓 Day 7 E題 CodeForces 915C Permute Digits

CodeForces 915C Permute Digits

題目大意:

給兩個數a,b,對 a 的各個位置的數字重新排列,找出比 b 小的最大排列。題目保證輸入有結果。

解題思路:

  • 用頭文件 sstream 的 stringstream 得到 a,b 的字符形式和數字形式
  • 由a ,b的字符長度分情況討論
    1. a.size() < b.size() ,將 a 的最大排列輸出。
    2. a.size() == b.size() ,從第一個數字開始判斷,儘可能使新排列相應位置數字與 b 相同, 但不得不出現第一不同之後(即新排列在之後必然小於 b ),將剩餘的數字按最大排列輸出。

AC代碼:

#include<cstdio>
#include<iostream>
#include<queue>
#include<string>
#include<cmath>
#include<algorithm>
#include<limits.h>
#include<sstream>
#define rep(i,l,p) for(int i=l; i<=p; i++)
#define drep(i,p,l) for(int i=p; i>=l; i--)
using namespace std;
typedef long long ll;
ll a,b;
int len;
bool flag;
string s1,s2,ans;
int numa[11];
void dfs(int x){
    //cout << flag <<"dfs" << endl;
    if ( flag == true ) return ;
    if ( x == s2.size() ){
        flag = true;
        //cout << ans.size() << endl;
        return;
    }
    else if ( flag == false){
        int maxn = s2[x] - '0';
        //cout << maxn << "maxn" << endl;
        drep(i,maxn,0){
            if ( numa[i] > 0 && (s2[x] - '0' > i) ){
                numa[i]--;
                flag = true;
                //cout <<"x:" <<x <<"\t"<< i << endl;
                //cout << "ok" << endl;
                ans += char('0'+ i);
            //  cout << ans << endl;
                return;
            }else if (numa[i] > 0){
                numa[i]--;
                ans += char('0' + i);
                dfs(x+1);
                if ( flag == true) return;
                ans.erase(--ans.end());
                numa[i]++;
            }
        }
    }
    return ;

}
void ini(){
    rep(i,0,9) numa[i] = 0;
    ans = "";
}
int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);

    while(cin >> s1 >> s2){
        ini();
        //cout << s1 << endl << s2 << endl;
        stringstream s1in(s1),s2in(s2);
        s1in >> a; s2in >> b;
        rep(i,0,s1.size()-1){
            numa[s1[i]-'0']++;
        }
        //cout << numa[0]<<"\t"<< numa[1]<<endl;
        if ( s1.size() < s2.size() ){
            drep(i,9,0){
                while( numa[i] > 0 ) {
                    ans += char('0'+i);
                    numa[i]--;
                }
            }
            while( ans.size() > 1 && *ans.begin() == '0' ) ans.erase(ans.begin());
            cout << ans << endl;
        }else {
            flag = false;
            len = s1.size();
            dfs(0);

            drep(i,9,0){
                while( numa[i] > 0 ) {
                    ans += char('0'+i);
                    numa[i]--;
                }
            }
            while( ans.size() > 1 && *ans.begin() == '0' ) ans.erase(ans.begin());
            cout << ans << endl;
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章