結果

問題 No.1630 Sorting Integers (Greater than K)
ユーザー H3PO4
提出日時 2023-10-11 17:59:19
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 17 ms / 2,000 ms
コード長 1,733 bytes
コンパイル時間 849 ms
コンパイル使用メモリ 74,536 KB
最終ジャッジ日時 2025-02-17 06:44:25
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <array>
#include <iostream>
#include <string>
#include <vector>

inline int ctoi(const char &c) { return (int)c - '0'; };
inline char itoc(const int &n) { return (char)n + '0'; };

std::string solve(const int N, const std::string &K,
                  const std::array<int, 9> &C) {
    if (K.size() > N) return "-1";
    if (K.size() < N) {
        // 一番小さくなるように作る
        std::string res;
        for (int i = 1; i < 10; i++) {
            res += std::string(C.at(i - 1), itoc(i));
        }
        return res;
    }

    // i桁目より上の判定
    int max_i = K.size() - 1;
    std::array<int, 9> D;
    for (int i = 0; i < 9; i++) D.at(i) = C.at(i);
    for (int i = 0; i < K.size() - 1; i++) {
        int k = ctoi(K.at(i));
        if (k == 0) {
            max_i = i;
            break;
        }
        if (D.at(k - 1) <= 0) {
            max_i = i;
            break;
        }
        D.at(k - 1)--;
    }

    for (int i = max_i; i >= 0; i--) {
        std::array<int, 9> used;
        for (int j = 0; j < 9; j++) used.at(j) = D.at(j);

        for (int n = ctoi(K.at(i)) + 1; n < 10; n++) {
            if (used.at(n - 1) <= 0) continue;
            used.at(n - 1)--;
            std::string res = K.substr(0, i);
            res += itoc(n);
            for (int i = 1; i < 10; i++) {
                res += std::string(used.at(i - 1), itoc(i));
            }
            return res;
        }

        if (i == 0) break;
        D.at(ctoi(K.at(i - 1)) - 1)++;
    }
    return "-1";
}

int main() {
    int N;
    std::string K;
    std::array<int, 9> C;
    std::cin >> N >> K;
    for (int i = 0; i < 9; i++) std::cin >> C.at(i);
    std::cout << solve(N, K, C) << std::endl;
}
0