• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
james1207

博客园    首页    新随笔    联系   管理    订阅  订阅

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;
}

 

 

 

posted @ 2013-10-10 21:46  Class Xman  阅读(153)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3