UVa 11062 - Andy's Second Dictionary

題目:統計一個文本中的單詞,在每行結尾處的連詞符'-'代表一個單一被切割開,

            字典序輸出所有單詞的小寫形式。

分析:數據結構(DS),字典樹。檢查沒行結束的時候是不是'-',如果是就和下一行的一起處理。

說明:基本上用的是UVa10815的代碼。注意單詞中(非行末)的'-'。

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

using namespace std;

//Trie
#define TRIE_NODE_SIZE 5000
#define TRIE_DICT_SIZE 128
typedef struct node1
{
	bool   flag;
	node1 *next[TRIE_DICT_SIZE];
}tnode;
tnode dict[TRIE_NODE_SIZE];

class Tire
{
		tnode* root;
		int    size;
		char   save[501];
	public:
		Tire() {
            size = 0;
            root = newnode();
        }
		int ID(char ch) {
			if (ch >= 'A' && ch <= 'Z') {
                return ch-'A'+'a';
            }
			return ch;
		}
		//构造新节点 
		tnode* newnode() {
			for (int i = 0; i < TRIE_DICT_SIZE; ++ 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 < TRIE_DICT_SIZE; ++ i) {
				if (r->next[i]) {
                    save[d] = i;
					output(r->next[i], d+1);
				}
            }
		}
		void output(){ 
            output(root,0); 
        }
};
//Tire end

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值