solution-cf1552g

· · 题解

upd on 2023/10/24

翻新。曾经写的不堪入目,感谢被辱眼的各位没有喷我。

如果暴力,一个数列复杂度 O(n!) ,无法接受。

考虑 01 序列。

有结论: 操作序列能对所有序列排序,当且仅当它能对所有 n 位 01 序列排序

证明:

根据结论直接暴力的话。 O(2^n) 也会炸掉。

想想怎么减少状态数。可以发现排序后,对应位置一定形如 000...11,所以只要知道排序前对应位置的 01 个数分别是多少就可以得到排序后的状态。

具体的,假设当前要进行第 i 次排序操作,经过前 i-1 次排序后一个可能的状态为 S。第 i 次操作处理的位置可以分为 1.在前 i-1 次操作中出现过的位置,他们的 01 状态是已知的。2.没有被排序过的位置,我们需要枚举他们的 01 状态,此时只需枚举 01 个数。

时间复杂度最坏为 O((\frac n k+1)^k)

code:

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

int read() {
    int x=0; char ch=getchar();
    while (ch<'0') ch=getchar();
    while (ch>='0') x=x*10+ch-48, ch=getchar();
    return x;
}

typedef long long ll;
int no() {return puts("REJECTED"), 0;}
int yes() {return puts("ACCEPTED"), 0;}

const int K=11;
int n, k;
ll opt[K], T[K], all;
vector<int> g[K];

int dfs(int i, ll S) {
    if (i==k+1) return S==(1ll<<__builtin_popcountll(S))-1;
// 当前做第 i 个操作,被前 i-1 个操作排序过的位置的状态可以到达 S
    int d0=__builtin_popcountll((S^all)&T[i-1]&opt[i]);
    int d1=__builtin_popcountll(S&opt[i]);
    int sz=__builtin_popcountll(opt[i]);
    for (int p:g[i]) S|=1ll<<p;
    int j=0;
    for (int p:g[i]) {
        if (j>=d0) if (!dfs(i+1, S)) return 0;
        j++, S^=1ll<<p;
        if (j>sz-d1) return 1;
    }
    if (j>=d0) return dfs(i+1, S);
    return 1;
}

signed main() {
    n=read(), k=read();
    if (n==1) return yes();
    for (int i=1; i<=k; i++) {
        int x=read();
        while (x--) {
            g[i].push_back(n-read());
            opt[i]|=(1ll<<g[i].back());
        }
        T[i]=T[i-1]|opt[i];
    }
    all=(1ll<<n)-1;
    if (T[k]!=all) return no();
    if (dfs(1, 0)) return yes();
    no();
    return 0;
}