HDOJ1671

字典树,照模板写的。。。。。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char arr[20];

typedef struct Trie{
	int v;
	Trie *next[10];
}Trie;

Trie *root;

void createTrie(char *s){
	Trie * p = root, *q;
	int len = strlen(arr);	
	for(int i = 0;i < len; i++){
		int id = s[i] - '0';
		if (p -> next[id] == NULL){
			Trie *q = new Trie;	
			q -> v = 1;	
			for(int j = 0;j < 10; j++)	
				q -> next[j] = NULL;	
			p -> next[id] = q;			
			p = p -> next[id];
		}	
		else{
			p -> next[id] -> v++;		
			p = p -> next[id];	
		}	
	}
	p -> v = -1;
}

int findTrie(char *s){
	Trie *p = root;
	int len = strlen(s);	
	for(int i = 0;i < len; i++){
			int id = s[i] - '0';	
			p = p -> next[id];	
			if (p == NULL)
				return 0;
			if (p -> v == -1)
				return -1;
	}
	return -1;
}

int deal(Trie *T){
	if (T == NULL)
		return 0;
	for(int i = 0;i < 10; i++){
		if(T -> next[i] != NULL)	
			deal(T -> next[i]);	
	}
	free(T);
	return 0;
}

int main(){
	int n, flag;
	scanf("%d", &n);
	while (n--){
		flag = 0;
		root = (Trie*)malloc(sizeof(Trie));	
	//	Trie *root = new Trie;
		for(int i = 0;i < 10; i++)	
			root -> next[i] = NULL;
		int m;	
		scanf("%d", &m);		
		for(int i = 0;i < m; i++){
			scanf("%s", arr);	
			if (findTrie(arr) == -1)		
				flag = 1;	
			if(flag)
				continue;
			createTrie(arr);
		}		
		if (flag)	
			printf("NO\n");
		else
			printf("YES\n");
		deal(root);
	}
	return 0;
}



你可能感兴趣的:(HDOJ1671)