跳到正文

题解

题解:P15301 [ROI 2012 Day 2] army 汗国军队

P2441M约 4 分钟
原文

这是 2026年4月21日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年2月14日
收录
2026年4月21日
更新
2026年9月18日
篇幅
约 4 分钟
题目
P15301

版本

  1. v2当前
  2. v1

题意

给定 nn 和 1,⋯ ,n1,\cdots,n 的一个大小为 kk 的子序列 aa。求有多少长度为 nn 的排列 pp,使得 aa 是 pp 的一个 LIS。k≤n≤15k\leq n\leq 15。

题解

题意看上去一脸 DP 套 DP 的样子,经典地,我们这样刻画 LIS:维护一个集合 SS,每次考虑一个数 xx,将 SS 中第一个大于 xx 的数替换成 xx,若不存在,则直接加入 xx,最终 SS 的大小就是 LIS 的长度。把题述条件拆成两个部分:一部分是 aa 在 pp 中是按值从小到大依次出现的,另一部分是 LIS 长度为 kk。设计 DP:令 fS,Tf_{S,T} 表示考虑了 SS 中的数,计算 LIS 时维护的集合为 TT 时的方案数。转移时枚举加入一个数 x∉Sx\notin S,TT 直接按照上述方式更新。注意若 x∈ax\in a,则需要保证 aa 中 <x<x 的数已经加入 SS 中。最终答案即为 ∑∣T∣=kfU,T\sum\limits_{|T|=k}f_{U,T}。注意到 T⊆ST\subseteq S,因此状态数为 O(3n)\mathcal{O}(3^n),时间复杂度为 O(n3n)\mathcal{O}(n3^n)。

我偷懒写 unordered_map 也过了。

代码
C++
#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;
}