牛客周賽 Round 66 G

MGNisme發表於2024-11-06

G.小苯的數位MEX

思路

比較模板的數位dp,雖然我不會

程式碼

#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;
using piii = pair<int, pii>;
using pll = pair<ll, ll>;
using plll = pair<ll, pll>;
using plii = pair<ll, pii>;
#define fi first
#define se second
const int INF = 0x3f3f3f3f;
const ull mod1 = (1ull << 61) - 1, mod2 = 1e9 + 7;
const ull base1 = 131, base2 = 13331;
// mt19937 rnd(time(0));

const int mod = 998244353;

vector<int> nums;
int mex;
int f[11][1100];  //f[dep][state]到第dep位(從高位到低位),該位之前的狀態為state(不包括該位)

//分別為層數  狀態  最高位限制  有無前導零
int dfs(int dep, int state, bool limit, bool lead0) {
    if (dep == nums.size()) {
        if (lead0)
            return mex == 1 ? 1 : 0;
        for (int i = 0; i < mex; i++) {
            if ((state >> i & 1) == 0)
                return limit ? 0 : f[dep][state] = 0;
        }
        return limit ? 1 : f[dep][state] = 1;
    }
    if (!lead0 && !limit && f[dep][state] != -1) //不加lead0也行
        return f[dep][state];
    int up = limit ? nums[dep] : 9;  //根據有無限制確定第dep位列舉上限
    int res = 0;
    for (int i = 0; i <= up; i++) {
        int fst = state | (1 << i);
        if (lead0 && i == 0) //如果有前導零,則無法傳遞
            fst = 0;
        if (i == mex && (lead0 & i == 0) == 0) //如果i等於mex(沒前導零的情況),也是不成立的
            continue;
        res += dfs(dep + 1, fst, limit && i == up, lead0 && i == 0);
    }
    if (!limit && !lead0)   //不加lead0也行
        f[dep][state] = res;
    return res;
}

int get(int x) {
    memset(f, -1, sizeof f);
    nums.clear();
    if (!x) { //x為零無法進入while迴圈,特判
        return mex == 1 ? mex : 0;
    }
    while (x) {
        nums.push_back(x % 10);
        x /= 10;
    }
    reverse(nums.begin(), nums.end());
    return dfs(0, 0, 1, 1);
}

void solve() {
    int a, b;
    cin >> a >> b;
    b += a;
    for (int i = 10; i >= 0; i--) {
        mex = i;
        int ans = get(b) - get(a - 1);
        if (ans) {
            cout << i << " " << ans << endl;
            return;
        }
    }
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int _ = 1;
    cin >> _;
    while (_--) {
        solve();
    }
    return 0;
}

相關文章