题意
给定 和 的一个大小为 的子序列 。求有多少长度为 的排列 ,使得 是 的一个 LIS。。
题解
题意看上去一脸 DP 套 DP 的样子,经典地,我们这样刻画 LIS:维护一个集合 ,每次考虑一个数 ,将 中第一个大于 的数替换成 ,若不存在,则直接加入 ,最终 的大小就是 LIS 的长度。把题述条件拆成两个部分:一部分是 在 中是按值从小到大依次出现的,另一部分是 LIS 长度为 。设计 DP:令 表示考虑了 中的数,计算 LIS 时维护的集合为 时的方案数。转移时枚举加入一个数 , 直接按照上述方式更新。注意若 ,则需要保证 中 的数已经加入 中。最终答案即为 。注意到 ,因此状态数为 ,时间复杂度为 。
我偷懒写 unordered_map 也过了。
代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using i128 = __int128;
using ui = unsigned int;
using ull = unsigned long long;
using u128 = unsigned __int128;
using ld = long double;
using pii = pair<int, int>;
const int N = 15, S = 1 << 15;
template<typename T> inline T lowbit(T x) { return x & -x; }
template<typename T> inline void chk_min(T &x, T y) { if (y < x) x = y; }
template<typename T> inline void chk_max(T &x, T y) { if (x < y) x = y; }
int n, k, mask[N], pc[S];
ll ans;
unordered_map<int, ll> f[S];
bool mark[N];
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> k;
for (int i = 1, s = 0, x; i <= k; ++i) {
cin >> x, --x;
mark[x] = 1;
mask[x] = s, s ^= 1 << x;
}
for (int s = 1; s < 1 << n; ++s) pc[s] = pc[s ^ lowbit(s)] + 1;
f[0][0] = 1;
for (int s = 0; s < (1 << n) - 1; ++s) {
for (auto [t, val] : f[s]) {
for (int x = 0; x < n; ++x) if (~s >> x & 1) {
if (mark[x] && (s & mask[x]) != mask[x]) continue;
int ns = s ^ (1 << x), nt = (t ^ lowbit(t & -(1 << x))) ^ (1 << x);
if (pc[nt] <= k) f[ns][nt] += f[s][t];
}
}
}
for (int t = 0; t < 1 << n; ++t) if (pc[t] == k) ans += f[(1 << n) - 1][t];
cout << ans;
return 0;
}