Trie · Trie

Trie is an advanced data structures used to count to find more strings, because the dictionary to find ways and content and would like to, it is called a trie

So - as long as you look up, you'll trie

Look at a map

Here Insert Picture Description
Now here we have a dictionary as shown above, then in the dictionary we want to insert a word, how to do it, for example, we insert "Tsinghua University Park," then we'll go first to "clear" the word, to find "Hua "but there is no garden, so we can not even park in China to the following

So insert trie and this almost every time a character go down, if not to build a point

On the code:

inline void add(char s[]){
	int len=strlen(s);
	int u=1;
	for(int i=0;i<len;i++){
		int fin=s[i]-'a';
		if(!trie[u][fin])trie[u][fin]=++num;
		u=trie[u][fin];
	}
	end[u]++;
}

Inquiry is also very simple

	inline int ask(int* s){
		int u=1;
		int ans=0;
		Rep(i,1,s[0]){
			if(!trie[u][s[i]])return ans;
			u=trie[u][s[i]];
			ans+=end[u];
		}
		return ans-end[u]+cnt[u];
	}

Because the contents of each topic to be queried is not the same, so the trie are not the same wording
for this question P2922 [USACO08DEC] Secret Message Secret Message

Probably look like this (structure Edition)

struct dictionary_tree{
	int trie[N][2];
	int end[N],cnt[N];
	int sum;
	dictionary_tree(){
		memset(trie,0,sizeof(trie));
		memset(end,0,sizeof(end));
		memset(cnt,0,sizeof(end));
	}
	inline void add(int* s){
		int u=1;
		Rep(i,1,s[0]){
			if(!trie[u][s[i]])trie[u][s[i]]=++sum;
			u=trie[u][s[i]];
			cnt[u]++;
		}
		end[u]++;
	}
	inline int ask(int* s){
		int u=1;
		int ans=0;
		Rep(i,1,s[0]){
			if(!trie[u][s[i]])return ans;
			u=trie[u][s[i]];
			ans+=end[u];
		}
		return ans-end[u]+cnt[u];
	}
}Trie;
Published 18 original articles · won praise 3 · Views 1263

Guess you like

Origin blog.csdn.net/devout_/article/details/100015832