现在的位置: 首页 > 综合 > 正文

trie树 HDU1671

2018年04月29日 ⁄ 综合 ⁄ 共 879字 ⁄ 字号 评论关闭
#include <iostream>
using namespace std;

struct trie
{
	trie():end(false)
	{
		for(int i =0; i < 10; ++i)
			next[i] = NULL;
	}
	bool end;
	trie *next[10];
};

void insert(trie *root, const char *a)
{
	trie *p = root;
	int len = strlen(a);
	
	for(int i = 0; i < len; ++i)
	{
		if(!p->next[a[i] - '0'])
		{
			trie *t = new trie;
			p->next[a[i] - '0'] = t;
		}
		p = p->next[a[i] - '0'];
	}
	p->end = true;
}

bool search(trie *root, const char *a)
{
	trie *p = root;
	int len = strlen(a);
	
	for(int i = 0; i < len; ++i)
	{
		int k = a[i] - '0';
		p = p->next[k];

		if(p->end)
		{
			if(i + 1 != len)
				return true;
		}	
	}
	return false;
}

void del(trie *p)
{
	if(!p)
		return;
	for(int i = 0; i < 10; ++i)
	{
		if(p->next[i])
		{
			del(p->next[i]);
		}
	}
	delete p;
}

int main(void)
{
	//freopen("1.txt", "r", stdin);
	int t, n;
	bool fail;
	cin >> t;
	while(t--)
	{
		trie *root = new trie;
		fail = false;
		char celnum[10010][11];
		cin >> n;
		for(int i = 0; i < n; ++i)
		{
			scanf("%s", celnum[i]);
			insert(root, celnum[i]);
		}
		for(int j = 0; j < n; ++j)
		{
			if(search(root, celnum[j]))
				fail = true;
		}
		if(fail)
			cout << "NO" << endl;
		else
			cout << "YES" << endl;
		del(root);
	}
	return 0;
}

抱歉!评论已关闭.