UVa 11062 - Andy's Second Dictionary

来源:互联网 发布:海伦凯勒商城源码 编辑:程序博客网 时间:2024/06/06 16:25

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

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

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

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

#include <iostream>#include <cstdlib>#include <cstring>#include <cstdio>using namespace std;//Trie#define TRIE_NODE_SIZE 5000#define TRIE_DICT_SIZE 128typedef 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 endint 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;}

0 0