题意:
思路:
考虑数列最终的状态一定是相同颜色在一起,所以我们发现他的颜色是有顺序的!显然可以用状压 d p dp dp来枚举颜色的顺序,但是又有问题了,你怎么确定当前这个颜色加入这个集合的时候贡献是多少呢?
更深刻的考虑一下,我们使用状压 d p dp dp给颜色定序,实际上也就是将颜色大小重新定义了一下,最终排在最前面的是 1 1 1,以此类推,而变换到答案序列的时候就是将其转变为递增序列。这样想有什么好处呢?我们知道将一个数列变为递增的,如果只能交换相邻的元素的话,冒泡排序是最优的,所需要的操作次数也就是逆序对个数。
可以发现,这样的话就比较容易了。设 f [ S ] f[S] f[S]为当前集合为 S S S的时候最少逆序对个数,假设当前枚举的集合为 S S S,一个不在集合中的颜色为 x x x,加上 x x x之后的集合为 G G G,那么我们如果枚举 S S S集合中某个颜色 y y y,让后只需要计算一下有多少对 l < r , a l = x , a r = y l<r,a_l=x,a_r=y l<r,al=x,ar=y,加入答案即可,也就是 f [ G ] = f [ S ] + ∑ y ∈ S c o s t [ y ] [ x ] f[G]=f[S]+\sum_{y\in S} cost[y][x] f[G]=f[S]+∑y∈Scost[y][x]。
现在问题就变成了我们如何处理
c
o
s
t
[
y
]
[
x
]
cost[y][x]
cost[y][x]数组,一种显然的方式就是直接
20
∗
20
20*20
20∗20枚举
y
,
x
y,x
y,x,让后
O
(
n
)
O(n)
O(n)扫一遍统计逆序对即可,这个复杂度为
O
(
n
∗
400
)
O(n*400)
O(n∗400)。还有一种比较快的方式就是从头扫,记
c
n
t
[
i
]
cnt[i]
cnt[i]为到当前点颜色
i
i
i出现的次数,让后再枚举其他颜色,加上答案即可,复杂度
O
(
n
∗
20
)
O(n*20)
O(n∗20)。
复杂度
O
(
2
20
∗
400
+
n
∗
400
)
O(2^{20}*400+n*400)
O(220∗400+n∗400)
// Problem: E. Marbles
// Contest: Codeforces - Codeforces Round #585 (Div. 2)
// URL: https://codeforces.com/contest/1215/problem/E
// Memory Limit: 256 MB
// Time Limit: 4000 ms
//
// Powered by CP Editor (https://cpeditor.org)
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")
//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#include<random>
#include<cassert>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid ((tr[u].l+tr[u].r)>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;
//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
const int N=1000010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;
int n;
int a[N];
LL f[4*N],cs[30][30];
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]),a[i]--;
for(int i=0;i<20;i++) {
for(int j=0;j<20;j++) {
if(i==j) continue;
LL ans=0,cnt=0;
for(int k=1;k<=n;k++) {
if(a[k]==i) cnt++;
else if(a[k]==j) ans+=cnt;
}
cs[i][j]=ans;
}
}
memset(f,0x3f3f3f3f,sizeof(f));
f[0]=0;
for(int i=0;i<1<<20;i++) {
for(int j=0;j<20;j++) if(!(i>>j&1)) {
LL sum=0;
for(int k=0;k<20;k++) if(i>>k&1) {
sum+=cs[k][j];
}
f[i|(1<<j)]=min(f[i|(1<<j)],f[i]+sum);
}
}
cout<<f[(1<<20)-1]<<endl;
return 0;
}
/*
*/