大意: 给定串$s$, 字符集为字母表前$m$个字符, 求一个$m$排列$pos$, 使得$\sum\limits_{i=2}^n|{pos}_{s_{i-1}}-{pos}_{s_{i}}|$最小.
状压$dp$, 费用提前计算一下, 预处理$cost_{i,j}$表示与字符$i$相连的状态为$j$时的方案数
总复杂度是$O(n 2^n)$
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <cmath> #include <set> #include <map> #include <queue> #include <string> #include <cstring> #include <bitset> #include <functional> #include <random> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl ‘\n‘ #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<‘,‘;hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<‘0‘||p>‘9‘)p=getchar();while(p>=‘0‘&&p<=‘9‘)x=x*10+p-‘0‘,p=getchar();return x;} //head const int N = 1e6+50; int n, m; char s[N]; int cnt[20][20],Log[1<<20]; int dp[1<<20], cost[20][1<<20]; void chkmin(int &a, int b) {a>b?a=b:0;} int main() { printf("%d\n",n); scanf("%d%d%s",&n,&m,s+1); REP(i,2,n) { int a=s[i-1]-‘a‘,b=s[i]-‘a‘; ++cnt[a][b],++cnt[b][a]; } REP(i,0,m-1) Log[1<<i] = i; int mx = (1<<m)-1; REP(i,0,m-1) REP(j,1,mx) cost[i][j]=cost[i][j^j&-j]+cnt[i][Log[j&-j]]; memset(dp,0x3f,sizeof dp); dp[0] = 0; REP(i,0,mx) { int c = 0, s = ~i&mx; REP(j,0,m-1) if (i>>j&1) c += cost[j][s]; REP(j,0,m-1) if (i>>j&1^1) { chkmin(dp[i^1<<j],dp[i]+c+cost[j][s^1<<j]-cost[j][i]); } } printf("%d\n", dp[mx]); }
原文地址:https://www.cnblogs.com/uid001/p/11644921.html
时间: 2024-11-09 10:33:53