HDU5687(Problem C)

Problem C

Problem Description

度熊手上有一本神奇的字典,你可以在它裏面做如下三個操作:

1、insert : 往神奇字典中插入一個單詞

2、delete: 在神奇字典中刪除所有前綴等於給定字符串的單詞

3、search: 查詢是否在神奇字典中有一個字符串的前綴等於給定的字符串

Input

這裏僅有一組測試數據。第一行輸入一個正整數N(1≤N≤100000),代表度熊對於字典的操作次數,接下來N行,每行包含兩個字符串,中間中用空格隔開。第一個字符串代表了相關的操作(包括: insert, delete 或者 search)。第二個字符串代表了相關操作後指定的那個字符串,第二個字符串的長度不會超過30。第二個字符串僅由小寫字母組成。

Output

對於每一個search 操作,如果在度熊的字典中存在給定的字符串爲前綴的單詞,則輸出Yes 否則輸出 No。

Sample Input

5
insert hello
insert hehe
search h
delete he
search hello

Sample Output

Yes
No

思路

字典樹 + 增刪查。

  1. 增加字符串是最基本的字典樹操作,並且記錄每個前綴有多少個。
  2. 查詢也是最基本的字典樹操作,直接看前綴數目是不是爲0
  3. 刪除就比較囉嗦了,最開始沒考慮全情況WA幾發沒找到錯誤。大概就是先找到這個前綴的位置,並且取出這個前綴的數目,然後將該前綴的子前綴數目統統減掉前綴的數目,在把前綴的26項全部置爲0就刪完這個前綴了。

坑點:刪除的前綴可能不存在需要特判一下,不然會RE。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1000005;
int trie[maxn][26];
int num[maxn];
int cnt;
void insert_s(char *s)
{
	int n = strlen(s);
	int root = 0;
	for(int i = 0;i < n;i++){
		int k = s[i] - 'a';
		if(!trie[root][k]){
			trie[root][k] = ++cnt;
		}
		root = trie[root][k];
		num[root]++;
	}
}
int find_s(char *s)
{
	int n = strlen(s);
	int root = 0;
	for(int i = 0;i < n;i++){
		int k = s[i] - 'a';
		if(!trie[root][k]){
			return 0;
		}
		root = trie[root][k];
	}
	return num[root];
}
void delete_s(char *s)
{
	int n = strlen(s);
	int root = 0;
	for(int i = 0;i < n;i++){
		int k = s[i] - 'a';
		if(!trie[root][k]){			//刪除的前綴不存在 
			return ;
		}
		root = trie[root][k];
	}	
	int ans = num[root];root = 0;
	for(int i = 0;i < n;i++){		//該前綴的所有子前綴減掉該前綴的貢獻值 
		int k = s[i] - 'a';
		root = trie[root][k];
		num[root] -= ans;
	}
	for(int i = 0;i < 26;i++){		//該前綴的子節點全部初始化爲0 
		trie[root][i] = 0;
	}
}
int main()
{
	cnt = 0;
	memset(trie,0,sizeof(trie));
	memset(num,0,sizeof(num));
	int n;
	scanf("%d",&n);
	char op[35],s[35];
	for(int i = 0;i < n;i++){
		scanf("%s%s",op,s);
		if(op[0] == 'i'){
			insert_s(s);
		}
		if(op[0] == 's'){
			if(find_s(s)){
				printf("Yes\n");
			}
			else{
				printf("No\n");
			}
		}
		if(op[0] == 'd'){
			delete_s(s);
		}
	}
	return 0;
}

願你走出半生,歸來仍是少年~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章