小于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; }