UVALive 3942 - Remember the Word 字典树+dp
状态转移方程很容易想出,和背包思想有点像,难点在如何如何用字典树来搞dp,ps:原来在建stuct时初始化时可以节省不少时间的!!
#include<cstdio> #include<cstring> using namespace std; const int max_node=400100; const int modn=20071027; const int son_num=26; int ch[max_node][son_num]; int val[max_node]; int sz; int dp[300100]; struct trie { trie() { sz=1; memset(ch,0,sizeof(ch)); memset(val,0,sizeof(val)); } int idx(char c) { return c-'a'; } void insert(char *s) { int u,c,n,i,j; u=0; n=strlen(s); for(i=0;i<n;i++) { c=idx(s[i]); if(!ch[u][c])ch[u][c]=sz++; u=ch[u][c]; } val[u]=1; } int query(char *T,int pos) { int u,c,n,i,j; int res; u=0; n=strlen(T); res=0; for(i=pos;i<n&&i<=pos+100;i++) { c=idx(T[i]); if(!ch[u][c])return res; u=ch[u][c]; if(val[u])res=(res+dp[i+1])%modn; } return res; } }; char T[300100],s[110]; int main() { int cas,n,i,j,len; cas=1; while(scanf("%s",T)!=EOF) { scanf("%d",&n); trie op; while(n--) { scanf("%s",s); op.insert(s); } len=strlen(T); dp[len]=1; for(i=len-1;i>=0;i--) dp[i]=op.query(T,i); printf("Case %d: %d\n",cas++,dp[0]); } }
浙公网安备 33010602011771号