码迷,mamicode.com
首页 > 其他好文 > 详细

hdu2027 trie树 字典树模板

时间:2016-05-31 23:57:12      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <sstream>
using namespace std;

#define Max 26

const int maxn=100000;

typedef struct TrieNode{
    int nCount;//根据需要改变
    struct TrieNode *next[Max];
}TrieNode;

TrieNode *root=NULL;

int allcop=0,ans,flag;

TrieNode memory[maxn];

TrieNode *CreatTrieNode(){
     TrieNode *temp=&memory[allcop++];
     temp->nCount=0;
     for(int i=0;i<Max;i++) temp->next[i]=NULL;
     return temp;
}

void InsertTrie(TrieNode **pRoot,char *str){
      TrieNode *temp=*pRoot;
      int i=0,k;
      while(str[i]){
        k=str[i]-a;
        if(temp->next[k]){
                //temp->next[k]->nCount++;
        } else temp->next[k]=CreatTrieNode();
        temp=temp->next[k];
        i++;
      }
      temp->nCount++;
}

int SearchTrie(TrieNode *root,char *str){
    if(root==NULL) return 0;
    TrieNode *temp=root;
      int i=0,k;
      while(str[i]){
        k=str[i]-a;
        if(temp->next[k]){
                temp=temp->next[k];
        } else return 0;
        i++;
      }
      return temp->nCount;
}

void Traverse(TrieNode *root){
     for(int i=0;i<Max;i++){
        if(root->next[i]){
                if(root->next[i]->nCount>0) ans++;
                Traverse(root->next[i]);
        }
     }
}

char str[1010];

void init(){
  ans=0;
  flag=0;
  allcop=0;
  memset(memory,0,sizeof(memory));
  root=CreatTrieNode();
}

int main()
{
    while(1){
        init();
        string line;
        getline(cin,line);
        stringstream ss(line);
        while(ss>>str) {
        if(str[0]==#) {
                flag=1;
                break;
        }
        InsertTrie(&root,str);
        }
        if(flag) break;
        Traverse(root);
        printf("%d\n",ans);
    }
    return 0;
}

输入方式值得学习

hdu2027 trie树 字典树模板

标签:

原文地址:http://www.cnblogs.com/GeniusYang/p/5547815.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!