题解:CF1238E Keyboard Purchase
状压 DP。
Problem
已知一个长为
-
## Solution 发现只有相邻的两个字母才有贡献,不妨先全部数出来,也就是记 $c_{x,y}$ 表示字母 $x$、字母 $y$ 有多少次相邻。
看到这么小的
但是这个
不妨考虑所有
也就是说,所有在
时间复杂度
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;
}