题解:P14818 [ICPC 2023 Yokohama R] Chayas

· · 题解

P14818 [ICPC 2023 Yokohama R] Chayas

观察数据范围可得,这题是一道典型的状压。

设 dp_i 表示若 i 的第 j 位为 1,则以选择此位。

发现直接做是不可做的,那么考虑升维或钦定。发现升维没什么好思路,我们不妨钦定在转移时,新添加的那一个数必须加在末尾。

注意到,对于每一条限制 (a_i,b_i,c_i),若添加 b_i 时 a_i,c_i 均已添加或均未添加则此情况不合法。那么转移式就呼之欲出了。

设 s_i 表示 s 的二进制下第 i 位,即 (1&(s>>(i-1)))。

dp_s=\sum_{i=1,s_i=1}^{n}dp_{s\oplus2^{i-1}},\forall (a_i,b_i,c_i),s_{b_i}=1,s_{a_i}\oplus s_{c_i}=1

::::info[附代码]

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
int dp[1<<24];
vector<pair<int,int> >lim[25];
const int mod = 998244353;
int n,m;
signed main(){
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    cin >> n >> m;
    for(int i =1;i <= m; i++){
        int a,b,c;
        cin >> a>>b>>c;
        lim[b].push_back({a,c});
    }
    dp[0]=1;
    for(int s  = 1; s < (1<<n); s++){
        for(int i = 1; i <= n; i++){
            if(!(1&(s>>(i-1))))continue;
            int t = s^(1<<(i-1));
            bool f=0;
            for(auto pi:lim[i]){
                int  a=pi.first,b=pi.second;
                if((1&(t>>(a-1)))&&(1&(t>>(b-1)))){
                    f=1;
                    break;
                }
                if(!(1&(t>>(a-1)))&&!(1&(t>>(b-1)))){
                    f=1;
                    break;
                }
            }
            if(f)continue;
            dp[s]+=dp[t];
            dp[s]%=mod;
        }
    }
    cout << dp[(1<<n)-1]<<endl;
    return 0;
}

::::

这题数据有点水?理论上来说,时间复杂度是超的,但是却能过,可能是限制太多,跑不满,之所以设 24 是因为设小了会让暴搜卡过去吧。