poj 1816(trie+dfs)

//poj 1816
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
const int inf=1<<28;
int n,m,k;

const int  root=0;

struct ID
{
 int id;
 ID * next;
 ID(){next=0;}
 ID(int i,ID* nxt):id(i),next(nxt){}
};
struct node
{
 ID* ind;  //由于本题可能出现相同pattern,所以不得以用一个链表,
           //这里本来用了个vector<int>,导致MLE了好多次
 bool mark;  //是否有元素
 int branch[28];  //分支,0-25为'a'->'z',26为'?',27为'*'
}num[700001];

int size;

int index(char ch)
{
 if (ch=='?')return 26;
 else if (ch=='*') return 27;
 return ch-'a';
}

//插入字典树
void insert(char *key,int id)
{
 int cur=root;
 ID *pt;

 for (int i=0;key[i];i++)
 {
  int next=index(key[i]);
  if (num[cur].branch[next]==-1) //如果节点不存在则创建(注意初始化)
  {
   num[cur].branch[next]=size;
   num[size].mark=false;
   memset(num[size].branch,-1,sizeof(num[size].branch));
   while(num[size].ind)
   {
    pt=num[size].ind;
    num[size].ind=pt->next;
    delete pt;
   }
   size++;
  }
  cur=num[cur].branch[next];  //指向下一个节点
 }

 num[cur].mark=true; 
 num[cur].ind=new ID(id,num[cur].ind); 

}

char word[25];
int wlen;
int ans[100001];
bool exist[100001]; //可能出现重复ID,需要判断一下

void dfs(int step,int cur)
{
 if (step==wlen)
 {
  while (cur!=-1)
  {
        if (num[cur].mark )
  {
   for (ID *pt=num[cur].ind;pt;pt=pt->next)
    if (!exist[pt->id])
    {
       ans[k++]=pt->id;
       exist[pt->id]=true;
    }
  }
  cur=num[cur].branch[27];
  }
  return ;
  

 }
 if (num[cur].branch[word[step]-'a']!=-1)
  dfs(step+1,num[cur].branch[word[step]-'a']);
 if (num[cur].branch[26]!=-1)
  dfs(step+1,num[cur].branch[26]);
 if (num[cur].branch[27]!=-1)
 {
  for (int i=step;i<=wlen;i++)
   dfs(i,num[cur].branch[27]);
 }
  

}
   

int main()
{
 char p[10];
 while (scanf("%d%d",&n,&m)!=EOF)
 {
  memset(num[0].branch,-1,sizeof(num[0].branch));
  size=1;
  for (int i=0;i<n;i++)
  {
   scanf("%s",p);
   insert(p,i);
  }
  while (m--)
  {
   scanf("%s",word);
   wlen=strlen(word);
   memset(exist,0,sizeof(exist));
   k=0;
   dfs(0,root);
   if (!k) printf("Not match/n");
   else {
    sort(ans,ans+k);
    printf("%d",ans[0]);
    for (int i=1;i<k;i++)
     printf(" %d",ans[i]);
    printf("/n");
   }
   
  }
    
 }
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值