Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

CF1215E Marbles

LuoGu: CF1215E Marbles

CF: E. Marbles

只要确定了最后颜色的排列顺序,答案就是逆序对数。但是枚举排列复杂度不可接受。

记 $f _ i$ 表示集合 $i$ 中的颜色都已经确定了顺序的最小逆序对数。预处理在某个颜色后选择一个颜色的逆序对数,然后 DP 每次在集合中添加一个数,可以做到 $O(2 ^ n n ^ 2)$ 。

查看代码
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
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
flag && (x = ~x + 1);
}
template <class Type>
void write(Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar(x % 10 + '0');
}
const LL inf = 2e11;
const int N = 20, M = 1 << N;
int n, cnt[N];
LL pre[N][N], f[M];
int main ()
{
read(n);
for (int a; n; n--)
{
read(a);
cnt[--a]++;
for (int j = 0; j < N; j++)
pre[j][a] += cnt[j];
}
for (int i = 1; i < M; i++)
f[i] = inf;
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
{
if (i >> j & 1)
continue;
LL s = 0;
for (int k = 0; k < N; k++)
i >> k & 1 && (s += pre[k][j]);
f[i | 1 << j] = min(f[i | 1 << j], f[i] + s);
}
write(f[M - 1]);
return 0;
}