小于n的最大数

给定A数组其中0 <= a[i] <= 9,给定n。可重复使用A中的元素,要求构造小于n的最大数。

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int mod = 1e9 + 7;

void solve() {
    int A[] = {9, 8};
    int n = 9;
    n --;
    map<int, int> mp;
    for(auto x: A) mp[x] = 1;

    int a[10], cnt = 0;
    while(n) {
        a[cnt ++] = n % 10;
        n /= 10;
    }

    function<int(int)> fin = [&](int x) -> int {
        for(int i = x; i >= 0; -- i) {
            if(mp[i]) return i;
        }
        return -1;
    };

    bool f = false;
    stack<int> st;

    if(fin(a[cnt - 1]) == -1) {
        for(int i = cnt - 2; i >= 0; -- i) {
            st.push(fin(9));
        }
    } else {
        for(int i = cnt - 1; i >= 0; -- i) {
            if(f) {
                st.push(fin(9));
                continue;
            }
            int x = fin(a[i]);
            if(x == -1) {
                while(!st.empty()) {
                    int _x = st.top();
                    x = fin(_x - 1);
                    st.pop();
                    i ++;
                    if(x == -1) continue;
                    st.push(x);
                    f = true;
                    break;
                }
            } else {
                if(x != a[i]) f = true;
                st.push(x);
            }
        }
    }
    string ans = "";
    while(!st.empty()) {
        ans = char(st.top() + '0') + ans;
        st.pop();
    }
    cout << ans << '\n';
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#ifdef ACM_LOCAL
    freopen("in", "r", stdin);
    freopen("out", "w", stdout);
#else
    solve();
#endif
    return 0;
}

全部评论

相关推荐

07-11 13:16
湖南工学院 Java
坚定的芭乐反对画饼_...:谁也不知道,毕竟现在的互联网和十年前已经完全不同了,谁都无法预测未来
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 12:05
俺不中了,BOSS遇到了一个hr,我觉得我咨询的问题都很正常吧,然后直接就被拒绝了???
恶龙战士:你问的太多了,要不就整理成一段话直接问他,一个一个问不太好
点赞 评论 收藏
分享
求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务