题解:AT_abc415_c [ABC415C] Mixture

· · 题解

我怎么感觉比第五题难?

考虑状压。

设 dp_{s} 表示状态 s 是否可达,然后暴力枚举更新其它的点,设 sf_s 表示状态 s 是否是安全的,那么,sf_i 就取决与 s_{i-1} 是否是字符 0。判断一下转移的状态是否安全即可。

#include <bits/stdc++.h>

using namespace std;

#define int long long
#define VB vector<bool>

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int T, N;
    string S;
    cin >> T;
    while (T-- && cin >> N >> S) {
        const int t = 1 << N;
        VB sf(t, 0); sf[0] = true;
        for (int i = 1; i < t; i++) sf[i] = (S[i - 1] == '0');
        if (!sf[t - 1]) {
            cout << "No\n";
            continue;
        }
        vector<bool> dp(t, 0);
        dp[0] = 1;  // 空状态可达 
        // 状压
        for (int s = 0; s < t; s++) {
            if (!dp[s]) continue;  // 不可达状态 
            // 尝试添加每种化学品 
            for (int j = 0; j < N; j++) { // 更新其它状态 
                if (s & (1 << j)) continue;  // 已包含j 
                int nws = s | (1 << j);
                if (sf[nws]) dp[nws] = 1;
            }
        }
        cout << (dp[t - 1] ? "Yes\n" : "No\n");
    }

    return 0;
}