zoukankan      html  css  js  c++  java
  • 字典树算法

     这里演示关于字典树的插入删除 查找

    字典树的每个节点有26个子节点分别对应26个英文字母 ;每个节点还有个属性表示该节点是否为一个单词(从根节点到盖子节点)

    参考http://www.cnblogs.com/archimedes/p/trie-tree.html

    #include<iostream>
    using namespace std;
    struct Trie
    {
    	Trie *next[26];
    	bool isword;
    }root;
    void insertchar(char* str);//函数声明 
    bool selectstr(char *str);
    void delstr(char* str);
    int main()
    {
       	insertchar("abc");
       	insertchar("ab");
       	delstr("ab");
       	cout<<selectstr("abc");
        getchar();
    }
    void insertchar(char* str)
    {
        //获取根节点
    	Trie *head = &root;
    	while(*str)
    	{
    		int index = *str-'a';
                                         //使用NULL检验是否存在该字符 
    		if(head->next[index]==NULL) //表示不存在该字符
    		   head->next[index]=new Trie();//不存在则实例化该对象,并返回地址
    	    str++; //指针运算 检验下一字符串
    		cout<<*str;   
    		head = head->next[index]; //变为下一节点 
    	    	    
    	}
    	head->isword=true; 
    }
    bool selectstr(char *str)
    {
        Trie *head =&root;
        while(*str)
        {
        	int index=*str-'a';
            if(head->next[index]==NULL)
                 return false;
            str++;
            head=head->next[index];
        	
        }
        if(head->isword)
           return true;
         else
           return false;
    } 
    void delstr(char* str)
    {
    	Trie* head=&root;
    	while(*str)
    	{
    		int index=*str-'a';
    		if(head->next[index]==NULL)
    		      return;
            str++;
            head=head->next[index];
    	}
        if(head->isword)
           head->isword=false;
    }
    

      

  • 相关阅读:
    [HNOI2004]L语言
    快速沃尔什变换FWT
    [BZOJ1486][HNOI2009]最小圈
    [BZOJ4819][SDOI2017]新生舞会
    [POJ2976]Dropping tests
    CTSC2018&APIO2018游记
    [Luogu3769][CH弱省胡策R2]TATT
    [BZOJ3489]A simple rmq problem
    [BZOJ4066]简单题
    [BZOJ2648]SJY摆棋子
  • 原文地址:https://www.cnblogs.com/Small-Life/p/4007428.html
Copyright © 2011-2022 走看看