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

    HDU 1251 字典树
    
    #include <iostream>
    using namespace std;
    
    const int kind = 26;
    
    struct TreeNode
    {
    	int count;
    	TreeNode *next[kind];
    
    	TreeNode()
    	{
    		count = 1;
    		for(int i = 0; i < kind; i++)
    			next[i] = NULL;
    	}
    };
    
    
    void Insert(TreeNode *&root, const char *word)
    {
    	TreeNode *p = root;
    	int i, branch;
    	i = branch = 0;
    
    	if(NULL == p)
    	{
    		p = new TreeNode;
    		root = p;
    	}
    
    	while(word[i])
    	{
    		branch = word[i] - 'a';
    		if(p->next[branch])
    			p->next[branch]->count++;
    		else
    			p->next[branch] = new TreeNode;
    
    		i++;
    		p = p->next[branch];
    	}
    }
    
    
    int Search(TreeNode *&root, char *word)
    {
    	TreeNode *p = root;
    
    	if(!p)
    		return 0;
    
    	int i, branch, ans;
    	i = branch = ans = 0;
    
    	while(word[i])
    	{
    		branch = word[i] - 'a';
    		if(NULL == p->next[branch])
    			return 0;
    		ans = p->next[branch]->count;
    		i++;
    		p = p->next[branch];
    	}
    	return ans;
    }
    
    
    int main()
    {
    
    	char word[10], ask[10];
    	TreeNode *root = NULL;
    	while(gets(word))
    	{
    		if(word[0] == '\0')
    			break;
    		Insert(root, word);
    	}
    
    	while(gets(ask))
    		cout<<Search(root, ask)<<endl;
    
    	return 0;
    }
    

  • 相关阅读:
    (2015年郑州轻工业学院ACM校赛题) B迷宫
    (2015年郑州轻工业学院ACM校赛题) A 彩票
    POJ 1861 Network
    动态逆序对
    K大数查询
    Dynamic Rankings
    Cleaning
    Boxes
    P3601 签到题
    How many integers can you find
  • 原文地址:https://www.cnblogs.com/steady/p/1949200.html
Copyright © 2011-2022 走看看