Trie树_POJ3630_Phone List

版权声明:本文为博主原创作品, 转载请注明出处! https://blog.csdn.net/solider98/article/details/83867351

点此打开题目页面

思路分析:

    将输入字符串按照长度非递减排序, 然后直接应用Trie树即可, 具体见如下AC代码:

//POJ3630_Phone List
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX = 1e4 + 5;
int trie[MAX * 10][10], tot; bool end[MAX * 10];
char s[MAX][15]; 
pair<int, int> slen[MAX];//firsr:长度, second在s中一维下标 
int main(){
	int t; scanf("%d", &t);
	while(t--){
		memset(trie, 0, sizeof(trie)), memset(end, false, sizeof(end)), tot = 0;
		int n; scanf("%d", &n);
		bool yes = true;
		for(int i = 1; i <= n; ++i) 
			scanf("%s", s[i] + 1), slen[i] = make_pair(strlen(s[i] + 1), i);
		sort(slen + 1, slen + n +1);
		for(int i = 1; i <= n; ++i){
			int k = 0;
			for(int j = 1, len = slen[i].first; j <= len; ++j){
				int b = s[slen[i].second][j] - '0';
				if(!trie[k][b]) trie[k][b] = ++tot;
				else if(end[trie[k][b]]) yes = false;
				k = trie[k][b];		
			}
			end[k] = true;
		}
		cout << (yes? "YES": "NO") << endl;
	}	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/solider98/article/details/83867351