首页 > 其他 > 详细

HDU 1671 Phone List(字典树Trie)

时间:2015-02-11 18:34:37      阅读:252      评论:0      收藏:0      [点我收藏+]

解题思路:

判断是否有一个字符串是另一个字符串的前缀,直接用字典树搞。

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <stack>
#include <map>
#define LL long long
using namespace std;
typedef struct Trie_Node
{
	bool isword;
	struct Trie_Node *next[10];
}Trie;
void insert(Trie *root, char *word)
{
	Trie *p = root;
	int i = 0;
	while(word[i] != '\0')
	{
		if(p->next[word[i]-'0'] == NULL)
		{
			Trie *temp = new Trie;
			temp->isword = false;
			for(int j=0;j<10;j++)
				temp->next[j] = NULL;
			p->next[word[i]-'0'] = temp;
		}
		p = p->next[word[i]-'0'];
		i++;
	}
	p->isword = true;
}
int Find(Trie *root, char *word)
{
	Trie *p = root;
	int i = 0;
	int c = 0;
	while(word[i] != '\0')
	{
		if(p->next[word[i] - '0'] == NULL)
			return 0;
		p = p->next[word[i]-'0'];
		if(p->isword) c++;
		i++;
	}
	return c;
}
void del(Trie *root)
{
    for(int i=0;i<10;i++)
    {
        if(root->next[i] != NULL)
            del(root->next[i]);
    }
    free(root);
}
char s[10010][15];
int main()
{
	int T, N;
	scanf("%d", &T);
	while(T--)
	{
		Trie *root = new Trie;
		root->isword = false;
		for(int i=0;i<10;i++)
			root->next[i] = NULL;
		scanf("%d", &N);
		for(int i=1;i<=N;i++)
		{
			scanf("%s", s[i]);
			insert(root, s[i]);
		}
		bool ok = true;
		for(int i=1;i<=N;i++)
		{
			if(Find(root,s[i]) > 1)
			{
				ok = false;
				break;
			}
		}
		if(ok) printf("YES\n");
		else printf("NO\n");
		del(root);
	}
	return 0;
}


HDU 1671 Phone List(字典树Trie)

原文:http://blog.csdn.net/moguxiaozhe/article/details/43736585

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!