单词查找树 (Trie 字典树)

题目链接

裸的字典树题目,用一个全局变量记录插入的点的个数,注意每次有新的插入点就自增一次

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10, M = 30;
int trie[N][M], k, cnt;
void insert(char *s){
	int len = strlen(s);
	int p = 0;
	for (int i = 0; i < len; i++){
		int c = s[i] - 'A';
		if(!trie[p][c]){
			trie[p][c] = k++;
			++cnt;
		}
		p = trie[p][c];
	}
}
int main()
{
	k = 1;
	cnt = 0;
	char s[100];
	while (~scanf("%s", s)){
		insert(s);
	}
	printf("%d", cnt + 1);
	return 0;
}

 

posted @ 2019-10-07 21:35  correct  阅读(119)  评论(0)    收藏  举报