# Educational Codeforces Round 74E 状态压缩dp

https://codeforces.com/problemset/problem/1238/E

#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
#define PB push_back
#define LL long long
#define pii pair<int,int>
#define MEM(x,y) memset(x,y,sizeof(x))
#define bug(x) cout<<"debug "#x" is "<<x<<endl;
#define FIO ios::sync_with_stdio(false);
#define ALL(x) x.begin(),x.end()
#define LOG 20
const int inf =0x3f3f3f3f;
const int maxn =(1<<20)+7;
int dp[maxn];
map<int,int> h;
int sum[maxn][22];
int cnt[22][22];
int n,m;
string s;
int lower_bit(int x){return x&-x;};

int get_sum(int x,int i){
if(sum[x][i]!=-1)return sum[x][i];
if(x==0) return sum[x][i]=0;
sum[x][i]=get_sum(x&(x-1),i)+cnt[h[lower_bit(x)]][i];
return sum[x][i];
}

int DP(int x){
if(dp[x]!=-1) return dp[x];
if(x==0)return dp[x]=0;
int t=x;
dp[x]=inf;
for(int i=0;i<m;i++){
if(x&(1<<i)){
int p=x^(1<<i);
int q=x^((1<<m)-1);
dp[x]=min(dp[x],DP(p)+__builtin_popcount(p)*(get_sum(p,i)-get_sum(q,i)));
}
}
return dp[x];
}

int main(){
FIO;
cin>>n>>m>>s;
MEM(dp,-1);MEM(sum,-1);
for(int i=0;i<m;i++) h[1<<i]=i;
for(int i=1;i<n;i++){
++cnt[s[i] - 'a'][s[i - 1] - 'a'];
++cnt[s[i - 1] - 'a'][s[i] - 'a'];
}
cout<<DP((1<<m)-1)<<endl;
return 0;
}


posted @ 2019-10-11 17:21  zhangxianlong  阅读(121)  评论(0编辑  收藏