hdu1671(Tire-Tree)

思路:建立一个字典树,然后对路径上的结定做一个标记,方便后面再次遍历寻找的时候判断前缀。

/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :2015
File Name   :
*****************************************/
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
#define MEM(a,b) memset(a,b,sizeof a)
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
inline int Readint(){
	char c = getchar();
	while(!isdigit(c)) c = getchar();
	int x = 0;
	while(isdigit(c)){
		x = x * 10 + c - '0';
		c = getchar();
	}
	return x;
}
struct Tire{
	int v;
	Tire* nxt[26];
};
Tire *rt;
void insert(char *s){
	Tire *p = rt,*q;
	int len = strlen(s);
	for (int i = 0;i < len;i++){
		int pos = s[i] - '0';
		if (p->nxt[pos] == NULL){
			q = (Tire*)malloc(sizeof (Tire));
			for(int j = 0;j < 10;j++)
				q->nxt[j] = NULL;
			q->v = 1;
			p->nxt[pos] = q;
			p = q;
		}else{
			p->nxt[pos]->v++;
			p = p->nxt[pos];
		}
	}
}
int find(char*s){
	int len = strlen(s);
	Tire* p = rt;
	for (int i = 0;i < len;i++){
		int pos = s[i] - '0';
		if (p->nxt[pos] == NULL || p->nxt[pos]->v == 1)
			return 0;
		p = p->nxt[pos];
	}
	return 1;
}
void DelTire(Tire* p){
	if (p == NULL) return;
	for (int i = 0;i < 10;i++)
		if (p->nxt[i] != NULL) DelTire(p->nxt[i]);
	free (p);
}
int main()
{	
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	int T;
	T = Readint();
	while(T--){
		int n = Readint();
		char str[10010][11];
		rt = (Tire*)malloc(sizeof (Tire));
		for (int i = 0;i < 10;i++)
			rt->nxt[i] = NULL;
		rt->v = 0;
		for (int i = 0;i < n;i++){
			scanf("%s",str[i]);
			insert(str[i]);
		}
		int flag = 0;
		for (int i = 0;i < n;i++){
			flag = find(str[i]);
			if (flag){
				printf("NO\n");
				break;
			}
		}
		if (!flag) printf("YES\n");
		DelTire(rt);
	}
	return 0;
}


你可能感兴趣的:(字典树)