hdu 1800字典樹

簡單的字典樹實現

#include<iostream>
#include<string>

using namespace std;

int N, n, Max;
string str;
char ch;

struct node{
	node* son[10]; 
	int tag;
	int count;
	node()
	{
		tag = 1;
		count = 0;
		for(int i = 0; i < 10; i ++)
		{
			son[i] = NULL;
		} 
	}
};

node* root = new node();

void BuildTree(string str)
{
	int i;
	for(i = 0; i < str.length(); i ++)
	{
		if(str[i] == '0') continue;
		else break;
	}
	node* p = root;
	for(; i < str.length(); i ++)
	{
		int s = str[i]-'0';
		//cout<<s<<endl;
		if(p->son[s] == NULL) {
			p->son[s] = new node();
		}
		p = p->son[s];
		p->tag = s;
	}
	p->count++;
	if(p->count > Max) Max = p->count;
}

void DeleteTree()
{
	root = new node();
}

int main()
{
	while(cin >> n)
	{
		Max = 0;
		DeleteTree();
		while(n --){
			cin >> str;
			BuildTree(str);
		}
		cout<<Max<<endl;
	}
	return 0;
} 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章