• Trie树


    字典树查询

    #include<iostream>
    #include<cstring>
    #include<malloc.h>
    
    using namespace std;
    
    const int maxn = 30;
    
    typedef struct Trie{
    	int v;
    	Trie *next[ maxn ];
    }Trie;
    
    Trie root;
    
    void CreateTrie( char *str ){
    	int len = strlen( str );
    	//cout << str << endl;
    	Trie *p = &root, *q;
    	for( int i = 0; i < len; ++i ){
    		int id = str[ i ] - 'a';
    		if( p -> next[ id ] == NULL ){
    			//q = new Trie;
    			q = ( Trie * )malloc( sizeof( root ) );
    			for( int j = 0; j < maxn; ++j ){
    				q -> next[ j ] = NULL;
    			}
    			q -> v = 1;
    			p  -> next[ id ] = q;
    		}
    		else{
    			p -> next[ id ] -> v++;
    		}
    		p = p -> next[ id ];
    	}
    }
    
    int FindTrie( char *str ){
    	int len = strlen( str );
    	Trie *p = &root;
    	for( int i = 0; i < len; ++i ){
    		int id = str[ i ] - 'a';
    		if( p -> next[ id ] == NULL ){
    			return 0;
    		}
    		p = p -> next[ id ];
    	}
    	return p -> v;
    }
    
    
    int main(){
    	int n, m;
    	char str[ maxn ];
    	for( int i = 0; i < maxn; ++i ){
    		root.next[ i ] = NULL;
    	}
    	cin >> n;
    	while( n-- ){
    		cin >> str;
    		CreateTrie( str );
    	}
    	memset( str, 0, sizeof( str ) );
    	cin >> m;
    	while( m-- ){
    	cin >> str;
    		int ans = FindTrie( str );
    		cout << ans << endl;
    	}
    	return 0;
    }
    
    /*
    5
    banana
    band
    bee
    absolute
    acm
    
    4
    ba
    b
    band
    abc
    
    
    
    
    
    
    2
    3
    1
    0 
    */


  • 相关阅读:
    转:ORA-12541:TNS:无监听程序问题
    实战jmeter入门压测接口性能
    数据库的4种常用设计模式
    三范式,数据库设计的基本准则
    html5学习2
    html5学习1
    php初写成
    Typora编辑区域空白过大问题
    CURL 常用命令
    阿里云镜像创建Spring Boot工厂
  • 原文地址:https://www.cnblogs.com/yfceshi/p/6731663.html
Copyright © 2020-2023  润新知