SRM 557 1000

//ac自动机解决 长度为L的不含某些指定串,至少含一个指定串(总数-转化为不含),含一个指定串的总的字符串
#include<stdio.h>
#include<string.h>
#include<string>
using namespace std;

typedef int lld;
const int MM = 55;
const int M1 = 4;
const int mod=1000000009;

class FoxAndMountain{
public:

	int N,M;
	int L;
	
	int q[MM],front,last;
	int dp[MM][MM][MM];//dp[len][height][match_len]  ac自动机处理状态转移
	struct node{
		int sign;
		int fail;
		int next[4];
	}tree[MM];
	
	void init(int p)
	{
		for(int i=0;i<M1;i++)
			tree[p].next[i]=0;
		tree[p].sign=tree[p].fail=0;
	}
	
	void insert(string s)
	{
		int i=0,p=0,x;
		int sz=s.size();
		while(sz>i)
		{
			if(s[i]=='U')x=0;
			else x=1;
			if(tree[p].next[x]==0)
			{
				tree[p].next[x]=++L;
				init(L);
			}
			p=tree[p].next[x];
			i++;
		}
	}
	
	void build(  )
	{
		front = last = 0;
		for(int i=0;i<M1;i++)
			if(tree[0].next[i])
			{
				q[front++]=tree[0].next[i];
				tree[tree[0].next[i]].fail=0;
			}
			while( last < front )
			{
				
				int t = q[last++];
				for( int i = 0; i < M1; ++i )
				{
					int tt = tree[t].next[i];
					int ff = tree[t].fail;
					if( tree[t].next[i] )
					{
						tree[tt].fail = tree[ff].next[i];
						q[front++] = tt;
					}
					else
						tree[t].next[i] = tree[ff].next[i];
				}
			}
	}
	int count(int n, string history){
		int i,j,k;
		L=0;
		init(0);
		insert(history);
		build();
		int sz=history.size();
		memset(dp,0,sizeof(dp));
		dp[0][0][0]=1;
		tree[sz].next[0]=tree[sz].next[1]=sz;
		for(i=1;i<=n;i++){
			for(j=0;j<=n;j++){
				for(k=0;k<=sz;k++){
					int t0=tree[k].next[0];
					int t1=tree[k].next[1];
					if(j<n){
						dp[i][j+1][t0]=(dp[i][j+1][t0]+dp[i-1][j][k])%mod;
					}
					if(j){
						dp[i][j-1][t1]=(dp[i][j-1][t1]+dp[i-1][j][k])%mod;
					}
				}
			}
		}
		return dp[n][0][sz];
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值