hdu1251-統計難題 字典樹經典例題



Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字符串爲前綴的單詞數量(單詞本身也是自己的前綴). 
Input輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串. 

注意:本題只有一組測試數據,處理到文件結束. 
Output對於每個提問,給出以該字符串爲前綴的單詞的數量. 
Sample Input
banana
band
bee
absolute
acm

ba
b
band
abc
Sample Output
2
3
1
0


這是一道非常經典的字典樹題目,赤裸裸的字典樹。需要注意的是需要使用C++提交,G++會超

字典樹專題:點擊打開鏈接http://blog.csdn.net/wang_heng199/article/details/76448804


ac代碼:
//提交代碼使用C++,G++會超內存 
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
struct node
{
	int count;
	node *childs[26];
	node()
	{
		count=0;
		int i;
		for(i=0;i<26;i++)
		childs[i]=NULL;
	}
};

node *root=new node;

node *current,*newnode;

void insert(char *str)//插入 
{
	int i,m;
    current=root;
    for(int i=0;i<strlen(str);i++)
    {
       m=str[i]-'a';
        if(current->childs[m]==NULL)
        current->childs[m]=new node;
        current=current->childs[m];
       (current->count)++;
    }
}
int search(char *str)//查找 
{
	int i,m;
    current=root;
	for(i=0;i<strlen(str);i++)
	{
	    m=str[i]-'a';
		if(current->childs[m]==NULL)
		return 0;
		current=current->childs[m];
	}
	return current->count;
}
int main()
{
	char str[20];
	
	while(gets(str),strcmp(str,""))	 
	     insert(str);
	
	while(gets(str)!=NULL)	
	    printf("%d\n",search(str));

	return 0;
}

題目鏈接:點擊打開鏈接http://acm.hdu.edu.cn/showproblem.php?pid=1251
發佈了83 篇原創文章 · 獲贊 63 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章