zoukankan      html  css  js  c++  java
  • Keyboard Purchase CodeForces

    大意: 给定串$s$, 字符集为字母表前$m$个字符, 求一个$m$排列$pos$, 使得$sumlimits_{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 '
    '
    #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);
    	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
    ", dp[mx]);
    }
    
  • 相关阅读:
    SparkSql初级编程实践
    云时代架构之苏宁安全架构演进及实践
    云时代架构之知乎网站架构变迁史
    质量属性的六个常见属性场景之《淘宝网》
    云时代架构之游戏服务器的架构演进
    《架构漫谈阅读心得》
    转换后缀表达式
    约瑟夫环(改进3.0)
    栈结构之后缀表达式
    约瑟夫环(改进2.0)
  • 原文地址:https://www.cnblogs.com/uid001/p/11644921.html
Copyright © 2011-2022 走看看