POJ3630——Phone List【字典树】

poj_3630

题目大意:给你一组字符串,让你判断这其中的某一个字符串是不是其他字符串的前缀,如果是输出NO,否则输出YES。

大致思路:这道题我们可以用字典树来做,在每一个字符串后面一个节点加一个标记,标记一下这个字符串已经存在了。在字符串输入的时候判断一下其前缀是否已经出现了。

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>

using namespace std;

const int MAXN = 1e5 + 10;
int trie[MAXN][10],tot;
bool ed[MAXN];
char ss[MAXN][12];

bool search(char *s){
	int len = strlen(s),p = 1;
	for(int i = 0; i < len; i++){
		int ch = s[i] - '0';
		if(trie[p][ch] == 0) trie[p][ch] = ++tot;
		p = trie[p][ch];
		if(ed[p]) return true;
	}
	for(int i = 0; i < 10; i++){
		if(trie[p][i]) return true;
	}
	ed[p] = true;
	return false;
}

int main(int argc, char const *argv[])
{
	int t;
	scanf("%d",&t);
	while(t--){
		memset(ed,0,sizeof(ed));
		memset(trie,0,sizeof(trie));
		int n;
		scanf("%d",&n);
		bool flag = false;
		tot = 1;
		for(int i = 0; i < n; i++){
			scanf("%s",ss[i]);
			if(search(ss[i])) flag = true;
		}
		if(flag) puts("NO");
		else puts("YES");
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值