您的位置:首页 > 其它

hdu4057 ac自动机+dp(我用的方法)

2016-01-29 23:22 302 查看
艾玛虽说在10s的时限内用7s过了但是为啥前面那么多人都在1s内就搞定了囧。。。

因为太气了所以发个题解上来(雾。。顺便纪念一下ac自动机系列的完成!

那么说正题,这道题显然就是先建ac自动机了,题目要求每个串只能被计算一次,这种情况用一般的做法就难办了。

然后因为n最大只有10,容易联想到状压,于是结尾标记我用1<<id来或一起,这也方便了后面dp的处理

再之后就是dp了,定义状态dp[长度][在ac自动机上的状态节点][各模式串被计算的状态],这样是100*1000*1024空间是不够的,所以我们要把长度那一维滚动掉

状态转移也很容易想到啦,详细的我就不说了反正下面有代码

跑这么慢真的好气啊,有没有啥地方可以优化一下啊囧。。。或者有更好的dp姿势吗???

代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<iomanip>
#include<vector>
#include<set>
#include<map>
#include<queue>

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;

#define rep(i,k,n) for(int i=(k);i<=(n);i++)
#define rep0(i,n) for(int i=0;i<(n);i++)
#define red(i,k,n) for(int i=(k);i>=(n);i--)
#define sqr(x) ((x)*(x))
#define clr(x,y) memset((x),(y),sizeof(x))
#define pb push_back
#define mod 1000000007
const int maxnode=1110;
const int maxs=4;
int mp[100];
int w[20];
struct ac_automation
{
int next[maxnode][maxs],fail[maxnode],end[maxnode];
int root,L;
int newnode()
{
rep0(i,maxs)next[L][i]=-1;
end[L]=0;
return L++;
}
void init()
{
L=0;
root=newnode();
}
void insert(char str[],int id)
{
int len=strlen(str);
int now=root;
rep0(i,len)
{
int s=mp[str[i]];
if(next[now][s]==-1)
next[now][s]=newnode();
now=next[now][s];
}
end[now]|=1<<id;
}
void build()
{
fail[root]=root;
queue<int> q;
rep0(i,maxs)
{
if(next[root][i]==-1)
next[root][i]=root;
else
{
fail[next[root][i]]=root;
q.push(next[root][i]);
}
}
while(!q.empty())
{
int now=q.front();
q.pop();
end[now]|=end[fail[now]];
rep0(i,maxs)
{
if(next[now][i]==-1)
next[now][i]=next[fail[now]][i];
else
{
fail[next[now][i]]=next[fail[now]][i];
q.push(next[now][i]);
}
}
}
}
int dp[2][maxnode][1<<11];
const int inf=0x80808080;
inline void upd(int &a,int b)
{
a=max(a,b);
}
void solve(int n,int m)
{
clr(dp,128);
int now=0,last,tot=1<<n,nxt,xin,tt;
dp[now][0][0]=0;
rep0(i,m)
{
last=now;
now^=1;
clr(dp[now],128);
rep0(j,L)rep0(k,tot)if(inf!=dp[last][j][k])
{
rep0(x,maxs)
{
nxt=next[j][x];
xin=(end[nxt]&k)^end[nxt];
tt=0;
rep0(y,n)if(xin&(1<<y))tt+=w[y];

upd(dp[now][nxt][k|xin],dp[last][j][k]+tt);
}
}
}
int ans=-1;
rep0(i,L)rep0(j,tot)ans=max(ans,dp[now][i][j]);
if(ans<0)puts("No Rabbit after 2012!");
else printf("%d\n",ans);

}
}ac;

int main()
{
int n,m;
char str[110];
mp['A']=0;mp['C']=1;mp['G']=2;mp['T']=3;
while(~scanf("%d%d",&n,&m))
{
ac.init();
rep0(i,n)
{
scanf("%s%d",str,&w[i]);
ac.insert(str,i);
}
ac.build();

ac.solve(n,m);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: