পৃষ্ঠাসমূহ

শনিবার, ১৭ মে, ২০১৪

prefix tree/trie tree.......

#include<bits/stdc++.h>
using namespace std;
struct node
{
    bool endmark;
    node *next[27];
    node()
    {
        endmark=false;
        for(int i=0;i<27;i++)
        next[i]=NULL;
    }
}*root;
void insert(char *str,int len)
{
    node *cur=root;
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(cur->next[id]==NULL)
        cur->next[id]=new node();
        cur=cur->next[id];
    }
    cur->endmark=true;
}
bool search(char *str,int len)
{
    node *cur=root;
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(cur->next[id]==NULL)
        return false;
        cur=cur->next[id];
    }
    return cur->endmark;
}
main()
{
    int i,t,j,m,n;
    cin>>t;
    while(t--)
    {
        root=new node();
        cin>>m;
        while(m--)
        {
            char c[100];
            scanf("%s",c);
            insert(c,strlen(c));
        }
        cin>>n;
        while(n--)
        {
            char d[100];
            scanf("%s",d);
            if(search(d,strlen(d)))
            cout<<"YES"<<endl;
            else
            cout<<"NO"<<endl;
        }
    }
}