pku 1816 Wild Words(强烈推荐,Trie+DFS,很多细节啊)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>

using namespace std;

#define MAXLEN 22
#define MAXSON 28

typedef struct TNode
{
    TNode()
    {
        memset(next,0,sizeof(next));
    }
    vector<int> vidx;
    TNode *next[MAXSON];
}*Trie;

int len;
vector<int> ans;

inline int getidx(char ch)
{
    if( 'a' <= ch && ch <= 'z' ) return ch-'a';
    else if(ch=='?') return 26;
    else return 27;
}

void insert(Trie T,char *patt,int id)
{
    int i;
    while(*patt)
    {
        i=getidx(*patt);
        if(!T->next[i]) T->next[i]=new TNode;
        T=T->next[i];
        patt++;
    }
    T->vidx.push_back(id);
}

void search(Trie T,char *word,int depth)
{
    if( depth >= len )
    {
        while(T)
        {
            for(vector<int>::const_iterator it = T->vidx.begin(); it != T->vidx.end(); it++)
                ans.push_back( *it );
            T=T->next[27];
        }
    }
    else
    {
        int i=getidx( word[ depth ] );
        if(T->next[i]) search(T->next[i],word,depth+1);
        if(T->next[26]) search(T->next[26],word,depth+1);
        if(T->next[27])
        {
            for(int j=depth;j<=len;j++)
                search(T->next[27],word,j);
        }
    }
}

void destroy(Trie &T)
{
    if(!T) return;
    for(int i=0;i<MAXSON;i++)
        destroy(T->next[i]);
    T->vidx.clear();//////////////???
    delete T;
}

int main()
{
    int i,N,M;
    char str[MAXLEN];
    while(scanf("%d %d",&N,&M)!=EOF)
    {
        Trie tree=new TNode;
        for(i=0;i<N;i++)
        {
            scanf("%s",str);
            insert(tree,str,i);
        }
    //    ans.clear();
        for(i=0;i<M;i++)
        {
            scanf("%s",str);
            len=strlen(str);
            search(tree,str,0);

            vector<int>::size_type sz=ans.size();
            if(sz==0) printf("Not match\n");
            else
            {
                sort(ans.begin(),ans.end());
                printf("%d",ans[0]);
                for(vector<int>::size_type t=1;t<sz;t++)
                {
                    if( ans[t] != ans[t-1])
                        printf(" %d",ans[t]);
                }
                printf("\n");
                ans.clear();
            }
        }
 //       destroy(tree);//不加这句话2808K 407MS,注释后2804K 391MS
    }
    return 0;
}

 

posted @ 2010-08-25 22:58  菜到不得鸟  阅读(286)  评论(0)    收藏  举报