POJ-2001(trie字典树)

char ss[1005][30];
struct trie
{
	int cnt;
	trie *p[26];
} * root;
void make_tree(char *s)
{
	trie * r = root;
	trie * tmp;
	int i, j;
	for (i = 0; s[i] != '\0'; ++i) {
		if (r->p[s[i] - 'a'] == NULL) {
			tmp = new trie;
			tmp->cnt = 0;
			for (j = 0; j < 26; ++j)
				tmp->p[j] = NULL;
			r->p[s[i] - 'a'] = tmp;
		}
		r = r->p[s[i] - 'a'];
		r->cnt++;
	}
}
void search(char s[])
{
	trie * r = root;
	int i;
	for (i = 0; s[i] != '\0'; ++i) {
		r = r->p[s[i] - 'a'];
		printf("%c", s[i]);
		if (r->cnt == 1)
			break;
	}
	printf("\n");
}
int main()
{
	root = new trie;
	int i, j;
	for (i = 0; i < 26; ++i)
		root->p[i] = NULL;
	i = 0;
	while (scanf("%s", ss[i]) == 1) {
		make_tree(ss[i]);		
		++i;
	}
	for (j = 0; j < i; ++j) {
		printf("%s ", ss[j]);
		search(ss[j]);
	}
	return 0;
}


你可能感兴趣的:(c,struct,tree,null,search)