UVa 10815 - Andy's First Dictionary

题目:统计单词。

分析:字符串处理、字典树。比较裸的字典树,建树输出即可。

注意:库iostream中没有gets。万恶的CE,╮(╯▽╰)╭。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

//Trie
typedef struct node1
{
	bool   flag;
	node1 *next[26];
}tnode;
tnode dict[50000];

class Tire
{
		tnode* root;
		int    size;
		char   save[201];
	public:
		Tire() {size = 0;root = newnode();}
		int ID( char ch ) {
			if ( ch <= 'Z' ) return ch-'A';
			else return ch-'a';
		}
		//构造新节点 
		tnode* newnode() {
			for ( int i = 0 ; i < 26 ; ++ i )
				 dict[size].next[i] = NULL;
			dict[size].flag = false;
			return &dict[size ++]; 
		}
		//单词插入 
		void insert( char* word, int len ) {
			tnode *now = root;
			for ( int i = 0 ; i < len ; ++ i ) {
				if ( !now->next[ ID(word[i]) ] )
					now->next[ ID(word[i]) ] = newnode();
				now = now->next[ ID(word[i]) ];
			}now->flag = true;
		}
		//利用dfs遍历输出 
		void output( tnode* r, int d ) {
			if ( r->flag ) {
				save[d] = 0;puts(save);
			}
			for ( int i = 0 ; i < 26 ; ++ i )
				if ( r->next[i] ) {
					save[d] = i+'a';
					output( r->next[i], d+1 );
				}
		}
		void output(){ output(root,0); }
};
//Tire end

int main()
{
	char buf[201],sav[201];
	Tire tire;
	while ( gets(buf) ) {
		int len = strlen(buf);
		int cou = 0;
		for ( int i = 0 ; i <= len ; ++ i )
			if ( (buf[i] >= 'a' && buf[i] <= 'z') ||
				 (buf[i] >= 'A' && buf[i] <= 'Z') )
				sav[cou ++] = buf[i];
			else if ( cou ) {
				sav[cou] = 0;
				tire.insert( sav, cou );
				cou = 0;
			}
	}
	tire.output();
	return 0;
}

你可能感兴趣的:(UVa 10815 - Andy's First Dictionary)