BZOJ4416 [Shoi2013]阶乘字符串 【序列自动机 + 状压dp】

题目链接

BZOJ4416

题解

建立序列自动机,即预处理数组\(nxt[i][j]\)表示\(i\)位置之后下一个\(j\)出现的位置
\(f[i]\)表示合法字符集合为\(i\)的最短前缀,枚举最后一个加入的字符进行转移
注意到合法串长度是\(O(n^2)\)级别的,所以\(n > 21\)直接判掉

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
using namespace std;
const int maxn = 455,maxm = 1 << 22,INF = 1000000000;
inline int read(){
	int out = 0,flag = 1; char c = getchar();
	while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
	while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
	return out * flag;
}
int nxt[maxn][26],last[26],f[maxm],n,m;
char S[maxn];
int main(){
	int T = read();
	while (T--){
		n = read(); scanf("%s",S + 1); m = strlen(S + 1);
		if (n > 21){puts("NO"); continue;}
		for (int i = 0; i < n; i++) nxt[m + 1][i] = last[i] = m + 1;
		for (int i = m; ~i; i--){
			for (int j = 0; j < n; j++)
				nxt[i][j] = last[j];
			if (i) last[S[i] - 'a'] = i;
		}
		int maxv = (1 << n) - 1;
		for (int i = 1; i <= maxv; i++){
			f[i] = 0;
			for (int j = 0; j < n; j++)
				if (i & (1 << j)){
					f[i] = max(f[i],nxt[f[i ^ (1 << j)]][j]);
				}
		}
		puts(f[maxv] <= m ? "YES" : "NO");
	}
	return 0;
}

posted @ 2018-06-24 10:19  Mychael  阅读(159)  评论(0编辑  收藏  举报