hdu 1251 統計難題(字典樹)

題目鏈接:hdu 1251


解法:構造一個字典樹,根據給出模式串統計字典樹上的結點分別被多少個單詞覆蓋到,統計到的某結點的ch值便是以該結點結尾的字符串爲前綴的單詞個數。

代碼如下:

#include <cstdio>
#include <cstring>

struct trie
{
	trie *next[26]; // 假設只有26個小寫字母
	int ch;         // 統計有多少個單詞覆蓋到當前結點
	trie() {        // 用於初始化的構造函數
		memset(next, 0, sizeof(next));
		ch = 1;
	}
} *root;

void insert(char *s)
{
	trie *p = root;
	while(*s) {
		int index = *s - 'a';
		if(p->next[index]) p->next[index]->ch++;
		else p->next[index] = new trie;
		p = p->next[index];
		s++;
	}
}

int search(char *s)
{
    trie *p = root;
	while(*s) {
		int index = *s - 'a';
		if(!p->next[index]) return 0;
		p = p->next[index];
		s++;
	}
	return p->ch;
}

int main()
{
    root = new trie;
    char s[15];
    while(gets(s), s[0] != '\0') insert(s);
    while(gets(s)) printf("%d\n", search(s));
    return 0;
}




發佈了40 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章