#include <iostream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #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‘ 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;} //head #ifdef ONLINE_JUDGE const int N = 1e6+10; #else const int N = 111; #endif int n, m, mx, ans = INF; char s[N]; int a[N], tmp[1<<17], f[1<<17]; int cst[1<<17], dp[1<<17]; int g[17][17]; void dfs(int x) { if (tmp[x]) return; tmp[x] = 1; for (int y=x; y; y^=y&-y) dfs(x^y&-y); } void dfs1(int x) { if (f[x]||tmp[x]) return; tmp[x] = 1; ans = min(ans, cst[x]); for (int y=x; y; y^=y&-y) dfs1(x^y&-y); } int main() { scanf("%d%d%s", &n, &m, s+1), mx=(1<<m)-1; REP(i,1,n) ++cst[1<<(a[i]=s[i]-‘a‘)]; REP(i,1,mx) cst[i]=cst[i^i&-i]+cst[i&-i]; REP(i,0,m-1) REP(j,0,m-1) scanf("%d", &g[i][j]); REP(i,0,m-1) REP(j,0,m-1) if (!g[i][j]) { int now = 0, pre = -1; REP(k,1,n) { if (a[k]==i||a[k]==j) { if (a[k]==i&&pre==j||a[k]==j&&pre==i) { dfs(mx^now); } now = 0, pre = a[k]; } else now |= 1<<a[k]; } int t = 1<<i|1<<j; REP(k,0,mx) { if ((k&t)==t) f[k] |= tmp[k]; tmp[k]=0; } } dfs1(mx); printf("%d\n", ans); }
原文地址:https://www.cnblogs.com/uid001/p/10754403.html
时间: 2024-11-09 10:33:34