← 返回题目页

A0727 [2006J3]Jam 的计数法

标程

#include <bits/stdc++.h>
#include <string>
#include <vector>
using namespace std;

// 求下一个 Jam 数字;不存在时返回空串。
// d[i] 是第 i 个字母的序号(1..26),且严格递增。
// d[i] 可以加一,当且仅当加完之后后面还放得下 w-1-i 个更大的字母。
string nextJam(const string &cur, int s, int t, int w) {
    vector<int> d(w);
    for (int i = 0; i < w; ++i) d[i] = cur[i] - 'a' + 1;

    int i = w - 1;
    while (i >= 0 && d[i] >= t - (w - 1 - i)) --i;
    if (i < 0) return "";

    ++d[i];
    for (int j = i + 1; j < w; ++j) d[j] = d[j - 1] + 1;

    string res;
    for (int j = 0; j < w; ++j) res.push_back(char('a' + d[j] - 1));
    return res;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int s, t, w;
    cin >> s >> t >> w;
    string cur;
    cin >> cur;

    for (int k = 0; k < 5; ++k) {
        cur = nextJam(cur, s, t, w);
        if (cur.empty()) break;
        cout << cur << "\n";
    }
    return 0;
}

动画演示