状压 DP。
Problem
已知一个长为 序列 ,求一个长为 的排列 ,使得 的值最小。
- 。
Solution
发现只有相邻的两个字母才有贡献,不妨先全部数出来,也就是记 表示字母 、字母 有多少次相邻。
看到这么小的 ,很容易想到状压 DP。不妨定义 表示选择字母集合为 的答案,枚举最后一个插入的数字。也就是:
但是这个 并不是很好求,如果正常做的话,我们需要知道 这个集合的具体顺序,但这是不可能的。
不妨考虑所有 的贡献:
- 之前的 :;
- 之后的 :。
也就是说,所有在 前面的 , 提供了 的贡献,而 后的 提供了 的贡献。而 必然满足 ,所以就很好维护了。
时间复杂度 。
Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e6+5;
int dp[N],c[50][50],t[N];
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
int n,m;string s;
cin>>n>>m>>s;
for(int i=1;i<(int)s.size();i++)
c[s[i]-'a'][s[i-1]-'a']++,
c[s[i-1]-'a'][s[i]-'a']++;
for(int i=1;i<(1<<m);i++)
{
dp[i]=LLONG_MAX;
int len=0;
for(int p=0;p<m;p++)
t[p]=0;
for(int p=0;p<m;p++)
if(i&(1<<p))
t[p]=1,len++;
for(int p=0;p<m;p++)
if(t[p])
{
int j=i^(1<<p),res=0;
for(int k=0;k<m;k++)
if(k!=p)
{
if(t[k]) res=res+len*c[p][k];
else res=res-len*c[p][k];
}
dp[i]=min(dp[i],dp[j]+res);
}
}
cout<<dp[(1<<m)-1];
return 0;
}