ZOJ - 3494【AC自动机+数位DP】

数据那么大肯定是数位DP呀。
DP状态很好分析出来,注意数位DP上判一下前导零的情况就行。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2005;
typedef long long ll;
char ss[maxn];
int bit[maxn];
ll dp[205][maxn];
const ll mod = 1000000009;
char ch[12][10] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001"};
struct AC{
	int nex[maxn][2], tot, root;
	int f[maxn], ed[maxn];
	int newnode() {
		for(int i = 0; i < 2; i++) nex[tot][i] = -1;
		ed[tot] = 0;
		return tot++;
	}
	void init() {
		tot = 0;
		root = newnode();
	}
	void insert(char *s) {
		int u = root, len = strlen(s);
		for(int i = 0; i < len; i++) {
			int ch = s[i]-'0';
			if(nex[u][ch] == -1) nex[u][ch] = newnode();
			u = nex[u][ch];
		}
		ed[u] = 1;
	}
	void getfail() {
		queue<int>Q;
		for(int i = 0; i < 2; i++) {
			if(nex[root][i] == -1) nex[root][i] = root;
			else {
				f[nex[root][i]] =  root;
				Q.push(nex[root][i]);
			}
		}
		while(!Q.empty()) {
			int u = Q.front();Q.pop();
			ed[u] |= ed[f[u]];
			for(int i = 0; i < 2; i++) {
				if(nex[u][i] == -1) nex[u][i] = nex[f[u]][i];
				else {
					f[nex[u][i]] = nex[f[u]][i];
					Q.push(nex[u][i]);
				}
			}
		}
	}
	ll query(char *s) {
		int len = strlen(s), p = 0;
		for(int i = len-1; i >= 0; i--) {
			bit[++p] = s[i]-'0';
		}
		return dfs(p, root, 1, 1);
	}
	ll dfs(int p, int s, int flag, int f1) {
		if(p == 0) return (1&&!f1);
		if(!flag && !f1 && dp[p][s] != -1) return dp[p][s];
		int up = flag?bit[p]:9;
		ll res = 0;
		for(int i = 0; i <= up; i++) {
			if(i==0&&f1) {
				res = (res + dfs(p-1, root, (i==up)&&flag, 1))%mod;
				continue;
			}
			int u = s, f = 0;
			for(int j = 0; j < 4; j++) {
				u = nex[u][ch[i][j]-'0'];
				if(ed[u]) {f = 1;break;}
			}
			if(!f){res = (res + dfs(p-1, u, (i==up)&&flag, 0))%mod;}
		}
		if(!flag && !f1) dp[p][s] = res;
		return res;
	}
}ac;
char l[205], r[205];
void solve() {
	memset(dp, -1, sizeof(dp));
	int n;
	scanf("%d", &n);
	ac.init();
	for(int i = 1; i <= n; i++) {
		scanf("%s", ss);
		ac.insert(ss);
	}
	ac.getfail();
	scanf("%s%s", l, r);
	int len = strlen(l);
	for(int i = len-1; i >= 0; i--) {
		if(l[i] > '0') {
			l[i]--;
			break;
		}
		l[i] = '9';
	}
	printf("%lld\n", (ac.query(r)-ac.query(l)+mod)%mod);
}
int main() {
	int Case;
	scanf("%d", &Case);
	while(Case--) {
		solve();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39921637/article/details/89209728
ZOJ