​http://codeforces.com/problemset/problem/633/C​

这里DFS的作用和for循环一样 复杂度有点迷。。

感觉是因为这里用了字典树来剪枝 匹配的要求比较严格 当前位置找不到就必须返回

#include <bits/stdc++.h>
using namespace std;

struct node
{
node *next[26];
int id;
bool flag;
};

node *root;
int ans[10010];
int n,m,flag,num;
char pre[100010][1010];
char tar[10010];

void getnode(node *&ptr)
{
int i;
ptr=new node;
for(i=0;i<26;i++) ptr->next[i]=NULL;
ptr->flag=false;
}

void update(node *ptr,char *ch,int id,int cur,int len)
{
if(ptr->next[ch[cur]-'a']==NULL) getnode(ptr->next[ch[cur]-'a']);
if(cur==len-1)
{
ptr->next[ch[cur]-'a']->id=id;
ptr->next[ch[cur]-'a']->flag=true;
return;
}
update(ptr->next[ch[cur]-'a'],ch,id,cur+1,len);
}

bool dfs(int cur)
{
node *ptr;
int i;
if(cur==n) return true;
ptr=root;
for(i=cur;i<n;i++)
{
if(ptr->next[tar[i]-'a']==NULL) return false;
else if(ptr->next[tar[i]-'a']->flag)
{
ans[num++]=ptr->next[tar[i]-'a']->id;
if(dfs(i+1)) return true;
num--;
}
ptr=ptr->next[tar[i]-'a'];
}
return false;
}

int main()
{
int i,j,len;
char tmp[1010];
scanf("%d%s",&n,tar);
getnode(root);
scanf("%d",&m);
for(i=0;i<m;i++)
{
scanf("%s",pre[i]);
len=strlen(pre[i]);
for(j=0;j<len;j++)
{
if('A'<=pre[i][len-j-1]&&pre[i][len-j-1]<='Z') tmp[j]=pre[i][len-j-1]+('a'-'A');
else tmp[j]=pre[i][len-j-1];
}
update(root,tmp,i,0,len);
}
dfs(0);
for(i=0;i<num;i++) printf("%s ",pre[ans[i]]);
printf("\n");
return 0;
}