• HDU 4287 Intelligent IME(字典树)


     

     在我没用hash之前,一直TLE,字符串处理时间过长,用了hash之后一直CE,(请看下图)我自从经历我的字典树G++MLE,C++AC以后,一直天真的用C++,后来的CE就是因为这个,G++才支持这个hash...

    #include<cstdio>
    #include<iostream> #include
    <string.h> int hash[128]; struct TrieNode { int no; TrieNode *next[10]; } node[30005]; TrieNode *root = &node[0]; int cnt,result[5005]; char word[10],s[10]; void init() { hash['a']=hash['b']=hash['c']=2; hash['d']=hash['e']=hash['f']=3;
    hash[
    'g']=hash['h']=hash['i']=4; hash['j']=hash['k']=hash['l']=5; hash['m']=hash['n']=hash['o']=6; hash['p']=hash['q']=hash['r']=hash['s']=7; hash['t']=hash['u']=hash['v']=8; hash['w']=hash['x']=hash['y']=hash['z']=9; } void initRoot()
    {
    int i; for(i=0; i<10; i++) { root->next[i]=NULL; } } void insert(char str[],int num) { TrieNode *p = root; int len=strlen(str),i,j; for(i=0; i<len; i++)
    {
    if(p->next[str[i]-'0']==NULL) { p->next[str[i]-'0']=&node[cnt]; for(j=0; j<10; j++)node[cnt].next[j]=NULL; node[cnt].no=-1; cnt++; } p=p->next[str[i]-'0']; } p->no=num; } /** 查询一个字母字符串对应的数字串 */ void query(char str[]) { int len=strlen(str),i; TrieNode *p=root; for(i=0; i<len; i++) {
    p
    =p->next[hash[str[i]]]; if(p==NULL)break; } if(p==NULL)return; else {
    if(p->no!=-1)result[p->no]++; } } int main() { int t,m,n,i;
    scanf(
    "%d",&t); init();
    while(t--) { cnt=1; initRoot(); memset(result,0,sizeof(result));
    scanf(
    "%d%d",&n,&m); for(i=0; i<n; i++) { scanf("%s",word); insert(word,i);
    }
    for(i=0; i<m; i++) { scanf("%s",s); query(s); } for(i=0; i<n; i++)
    { printf(
    "%d ",result[i]); } } return 0; }
  • 相关阅读:
    常用正则、正则表达式
    移动端虚拟手机键盘
    如何隐藏滚动条还能实现滚动的功能
    醉盏的第一篇博客-关于title的换行处理
    Mybatis-Generator自动生成Dao、Model、Mapping等相关映射文件(懒人版)
    java学习笔记----@Override的作用
    web项目生成web.xml的两种方式
    angular分页插件tm.pagination二次触发问题解决歪方案
    Ubuntu Server17.10配置静态IP
    cors 的深入细节
  • 原文地址:https://www.cnblogs.com/jifahu/p/5449449.html
Copyright © 2020-2023  润新知