hdu 4057 Rescue the Rabbit AC自动机+DP

本文介绍了一道经典的AC自动机结合DP算法的题目。通过构造AC自动机并使用动态规划求解最大权值问题,提供了完整的代码实现及解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.hdu.edu.cn/showproblem.php?pid=4057


11年大连站的题目,在现场已经算是简单题了。。。


给出N(N<=10)个串,每个串都有个权值Wi,|Wi|<100。如果一个串出现了给定的串,那么权值就加上那个W,但只能加一次。现在问你长度为L(L<=100)的串的最大权值是多少?


构造AC自动机,然后DP就好了,DP[100][1000][1024],dp[i][j][k]表示长度为i的串,匹配到自动机中j号节点的状态,串出现的状态二进制表示为k时是否可达。


这时候很容易根据每个状态来转移,但是空间开不下,可以开滚动数组把第一维拿掉。这样就够了。。。大概10^8的算法,10s已经够了。。。


如果写成Trie图会更快点。。。。我的代码500ms


#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 1001;
const int INF = 0x3ffffff;
struct Node{
	int ch[4],pre;
	int b;
}node[maxn];
int top;
int root;
int val[11];
int nw(){
	memset(node[top].ch,0,sizeof(node[top].ch));
	node[top].pre=0;
	node[top].b=0;
	return top++;
}
int tran(char c){
	if(c=='A')return 0;
	else if(c=='T')return 1;
	else if(c=='G')return 2;
	else return 3;
}
char str[100000];
queue<int>q;
void bfs(){
	q.push(root);
	while(!q.empty()){
		int u=q.front();q.pop();
		for(int i=0;i<4;i++){
			int p=node[u].pre;
			if(node[u].ch[i]){
				int v=node[u].ch[i];
				if(u==root)node[v].pre=root;
				else {
					node[v].pre=node[p].ch[i];
					node[v].b|=node[node[p].ch[i]].b;
				}
				q.push(node[u].ch[i]);
			}else{
				if(u==root)node[u].ch[i]=root;
				else {
					node[u].ch[i]=node[p].ch[i];
					//node[u].b|=node[node[p].ch[i]].b;
				}
			}
		}
	}
}
bool dp[2][1010][1024];
int main(){
	int n,l;
	while(~scanf("%d%d",&n,&l)){
		top=0;
		root=nw();
		for(int i=0;i<n;i++){
			scanf("%s",str);
			int len=strlen(str);
			int p=root;
			if(len>l){
				scanf("%d",&val[i]);
				continue;
			}
			for(int j=0;j<len;j++){
				int c=tran(str[j]);
				if(node[p].ch[c]==0){
					node[p].ch[c]=nw();
				}
				p=node[p].ch[c];
			}
			node[p].b=node[p].b|(1<<i);
			scanf("%d",&val[i]);
		}
		bfs();
		int cur=0;
		for(int i=0;i<top;i++){
			for(int j=0;j<1<<n;j++){
				dp[cur][i][j]=false;
			}
		}
		dp[cur][0][0]=true;
		for(int k=0;k<l;k++){
			int next=(cur+1)%2;
			for(int i=0;i<top;i++){
				for(int j=0;j<1<<n;j++){
					dp[next][i][j]=false;
				}
			}
			for(int i=0;i<top;i++){
				for(int j=0;j<1<<n;j++){
					if(dp[cur][i][j]==false)continue;
					for(int t=0;t<4;t++){
						int to=node[i].ch[t];
						int bb=j|node[to].b;
						dp[next][to][bb]=true;
					}
				}
			}
			cur=next;
		}
		int ans=-1;
		for(int i=0;i<top;i++){
			for(int j=0;j<1<<n;j++){
				if(dp[cur][i][j]){
					int sum=0;
					for(int k=0;k<n;k++){
						if(j&(1<<k))sum+=val[k];
					}
					ans=max(sum,ans);
				}
			}
		}
		if(ans<0)printf("No Rabbit after 2012!\n");
		else printf("%d\n",ans);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值