hdu 4287 Intelligent IME (字典树)

来源:互联网 发布:淘宝店铺网站名片 编辑:程序博客网 时间:2024/04/27 17:07

题意:

给出n个手机上9宫格输入的数字,之后在输入了字典的单词。现在问,这些数字分别能在字典中找到多少种单词。

题解:

一开始直接暴力搜索,存储的字典树是按字母来的,可想而知复杂度O(n*m!)果断TL

然后换成用数字存,每次找对应字母是否有数字能对应他,字典树这边有个小技巧,就是键值用来存对应单词的标号,也就是对应数字是第几个输入的。然后愉快的ac。

#include<iostream>#include<math.h>#include<stdio.h>#include<algorithm>#include<string.h>#include<vector>#include<map>using namespace std;typedef long long lld;const int oo=0x3f3f3f3f;const lld OO=1e18;const int Mod=1000000007;const int maxn=5000+5;const int maxm=12;int n,m,T;char word[10];int res[maxn],cnt;map<char,char>mat;struct Trie{    struct TrieNode    {        int nCount;        TrieNode* child[10];        TrieNode()        {            memset(child,NULL,sizeof child);            nCount=0;        }    }*root;    Trie()    {        root=new TrieNode();    }    void Insert(char str[])    {        TrieNode* p=root;        for(int i=0,k;str[i];i++,p=p->child[k])        {            k=str[i]-'0';            if(!p->child[k])                p->child[k]=new TrieNode();        }        p->nCount=cnt;    }    int Search(char str[])    {        TrieNode* p=root;        for(int i=0,k;str[i];i++)        {            k=mat[str[i]];            if(p->child[k])                p=p->child[k];            else                return 0;        }        return p->nCount;    }    void Free(TrieNode* Root)    {        TrieNode* p=Root;        for(int i=0;i<10;i++)            if(p->child[i])                Free(p->child[i]);        delete p;    }    ~Trie()    {        Free(root);    }};///字典树数据结构到此为止void getHash(){    mat['a']=mat['b']=mat['c']=2;mat['d']=mat['e']=mat['f']=3;mat['g']=mat['h']=mat['i']=4;mat['j']=mat['k']=mat['l']=5;mat['m']=mat['n']=mat['o']=6;mat['p']=mat['q']=mat['r']=mat['s']=7;mat['t']=mat['u']=mat['v']=8;mat['w']=mat['x']=mat['y']=mat['z']=9;}int main(){    getHash();    scanf("%d",&T);    while(T--)    {        Trie tree;        memset(res,0,sizeof res);        scanf("%d %d",&n,&m);        cnt=0;        for(int i=1;i<=n;i++)        {            scanf("%s",word);            ++cnt;            tree.Insert(word);        }        for(int i=1;i<=m;i++)        {            scanf("%s",word);            int cur=tree.Search(word);            res[cur]++;        }        for(int i=1;i<=n;i++)            printf("%d\n",res[i]);    }    return 0;}/**13 5466444874goinnightmightgn*/




0 0