題目鏈接:https://vjudge.net/problem/Gym-102348C
一個特別好的狀壓dp題目,但是突然有點懶,不想寫題解了,直接發代碼吧。
#include <bits/stdc++.h>
#define rep(i, a, b) for(int i = (a); i <= (b); i++)
#define per(i, a, b) for(int i = (a); i >= (b); i--)
#define ll long long
using namespace std;
const int N = 3e6+10000;
const int mod = 1e9;
ll dp[N],x,num[20],cnt[20][20];
int n,m;
int main() {
// freopen("a.txt","r",stdin);
ios::sync_with_stdio(0);
ll S = (1<<20)-1;
cin>>n;
rep(i, 1, n) {
cin>>x;
x--;
num[x]++;
rep(j, 0, 19) cnt[x][j] += num[j];
}
rep(i, 1, S) dp[i] = 9e18;
rep(i, 0, S)
rep(j, 0, 19)
if((i>>j)&1) {
ll x = 0;
rep(k, 0, 19)
if(!((i>>k)&1))
x += cnt[j][k];
dp[i] = min(dp[i],dp[i^(1<<j)]+x);
}
cout<<dp[S];
return 0;
}