标签:
题目链接:http://poj.org/problem?id=3630
题意:给定n个字符串。判断是否存在其中某个字符串为另外一个字符串的前缀。若不存在输出YES。否则输出NO。
思路:裸的字典树。
代码
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <string>
using namespace std;
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define ceil(x, y) (((x) + (y) - 1) / (y))
const int SIZE = 10;
const int N = 1e5 + 10;
const int INF = 0x7f7f7f7f;
struct Trie {
	int val[SIZE];
	int count;//有多少个子节点
};
int sz;
Trie pn[N];
int newnode() {
	memset(pn[sz].val, 0, sizeof(pn[sz].val));
	pn[sz].count = 0;
	return sz++;
}
void insert(char *s) {
	int u = 0;
	for (int i = 0; s[i]; i++) {
		int idx = s[i] - '0';
		if (!pn[u].val[idx]) {
			pn[u].val[idx] = newnode();
			pn[u].count++;
		}
		u = pn[u].val[idx];
	}
}
bool findpre(char *s) {
	int u = 0;
	for (int i = 0; s[i]; i++) {
		int idx = s[i] - '0';
		if (!pn[u].val[idx]) {
			if (!pn[u].count)
				return true;
			else
				return false;
		}
		u = pn[u].val[idx];
	}
	return true;
}
int main() {
	int t_case;
	scanf("%d", &t_case);
	for (int i_case = 1; i_case <= t_case; i_case++) {
		int n;
		scanf("%d", &n);
		char str[SIZE];
		bool flag = true;
		sz = 0;
		newnode();
		scanf("%s", str);
		insert(str);
		for (int i = 1; i < n; i++) {
			scanf("%s", str);
			if (findpre(str))
				flag = false;
			insert(str);
		}
		if (flag)
			puts("YES");
		else
			puts("NO");
	}
	return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u014357885/article/details/47701081