【题解】ARC126D Pure Straight

简要题意

给定一个长度为 $n$ 的序列, 序列中的每个数不大于 $K$ , 每次可交换相邻的两个数, 求最小交换次数使序列存在子区间满足 $a_i = 1, a_{i+1} = 2, \dots a_{i+K-1} = K$ .

$n \leqslant 200, K \leqslant 16$ .


题解

由于 $K$ 比较小, 可以考虑对已经选入区间的数进行状态压缩.

我们发现这个问题可以拆分成两个部分, 一是将所有需要的数移至一个连续的区间, 选完数之后再是经典问题计算逆序对.

考虑设 $dp_{i,j,0/1}$ 为考虑了前 $i$ 个数, 已经选则的数的状态为 $j$ , 是否选定最终区间.

在未选定区间的时候转移为已经选择的数向右移动, 选定区间后则是未选则的数向左移动 $\left( \text{这个是真的有蛮有意思的操作, 我大受震撼} \right)$ .

转移的时候同时考虑新增的数会对逆序对数造成什么样的贡献.

时间复杂度 $\mathcal{O} \left( 2^nn \right)$ .


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/************************************************
*Author : demonlover
*Created Time : 2021.11.05.10:50
*Problem : ARC126D
************************************************/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
typedef pair <int,int> pii;
#define DEBUG(x) cerr << #x << " = " << x << endl
template <typename T>
inline bool read(T &x) {
int f = 1,c = getchar();x = 0;
while (!isdigit(c)) {if (c == 45)f = -1;c = getchar();}
while (isdigit(c))x = (x<<3)+(x<<1)+(c^48),c = getchar();
return x *= f,true;
}
template <typename T,typename... Args>
inline bool read(T &x,Args &...args) {
return read(x) && read(args...);
}

namespace run {
const int maxn = 2e2+10,maxk = 1<<16|1;
const int inf = 1<<30;
int f[2][maxk][2],a[maxn],cnt[maxk];
int n,k,lim;
inline int main() {
read(n,k);lim = (1<<k)-1;
memset(f,0x3f,sizeof(f));f[0][0][0] = 0;
for (register int i = 1;i <= n;++i)read(a[i]);
for (register int i = 1;i <= lim;++i)cnt[i] = cnt[i>>1]+(i&1);
for (register int i = 1;i <= n;++i) {
int now = i&1,lst = now^1,tmp = (1<<(a[i]-1)),bl = lim^((1<<a[i])-1);
for (register int j = 0;j <= lim;++j)f[now][j][0] = f[now][j][1] = inf;
for (register int j = 0;j <= lim;++j) {
f[now][j][0] = min(f[now][j][0],f[lst][j][0]+cnt[j]);
f[now][j][1] = min(f[now][j][1],f[lst][j][0]+cnt[j]);
f[now][j][1] = min(f[now][j][1],f[lst][j][1]+cnt[lim^j]);
if (tmp&j)continue;
f[now][j|tmp][0] = min(f[now][j|tmp][0],f[lst][j][0]+cnt[j&bl]);
f[now][j|tmp][1] = min(f[now][j|tmp][1],f[lst][j][0]+cnt[j&bl]);
f[now][j|tmp][1] = min(f[now][j|tmp][1],f[lst][j][1]+cnt[j&bl]);
}
}
printf("%d\n",f[n&1][lim][1]);
cerr<<1.0*clock()/CLOCKS_PER_SEC<<endl;
return 0;
}
}

#define demonlover
int main() {
#ifdef demonlover
freopen("ARC126D.in","r",stdin);
freopen("ARC126D.out","w",stdout);
#endif
return run :: main();
}