标签:字典树
2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
NO YES
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <cstdlib>
#include <algorithm>
#define ls u << 1
#define rs u << 1 | 1
#define lson l, mid, u << 1
#define rson mid + 1, r, u << 1 | 1
#define INF 0x3f3f3f3f
#define MAX 10
using namespace std;
typedef long long ll;
const int M = 1e4 + 100;
const int mod = 2147483647;
struct Trie{
Trie *next[MAX];
int index;
Trie(){
index = 1;
memset(next,0,sizeof(next));
}
};
char s[20];
bool flag;
void Trie_insert(Trie *tr,int len){
if(!flag) return;
if(s[len]){
int u = s[len] - '0';
if(tr->next[u] == 0){
tr->next[u] = new Trie;
}
else {
if(tr->next[u]->index == -1 || s[len + 1] == '\0'){
flag = false;
return ;
}
}
Trie_insert(tr->next[u],len + 1);
}
else tr->index = -1;
}
void deal_Trie(Trie *tr){
if(tr == NULL) return ;
for(int i = 0; i < MAX; i++){
if(tr->next[i]) deal_Trie(tr->next[i]);
}
free(tr);
}
int main(){
int T,n;
cin>>T;
while(T--){
scanf("%d",&n);
flag = true;
Trie *root = new Trie;
while(n--){
scanf("%s",s);
if(flag) Trie_insert(root,0);
}
if(flag) puts("YES");
else puts("NO");
deal_Trie(root);
}
return 0;
}
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <cstdlib>
#include <algorithm>
#define ls u << 1
#define rs u << 1 | 1
#define lson l, mid, u << 1
#define rson mid + 1, r, u << 1 | 1
#define INF 0x3f3f3f3f
#define MAX 10
using namespace std;
typedef long long ll;
const int M = 1e4 + 100;
const int mod = 2147483647;
map<ll,int>mp;
ll d[M];
bool solve(int n){
mp[d[0]] = 1;
for(int i = 1; i < n; i++){
ll res = d[i];
while(res >= 100){ //剪枝,不加会超时.
res /= 10;
if(mp[res]) return 1;
}
mp[d[i]] = 1;
}
return 0;
}
int main(){
int T,n;
char s[20];
scanf("%d",&T);
while(T--){
mp.clear();
scanf("%d",&n);
for(int i = 0; i < n; i++){
scanf("%s",s);
ll res = 1;
for(int j = 0; s[j]; j++) res = res * 10 + s[j] - '0';
d[i] = res;
}
sort(d,d + n);
if(solve(n)) puts("NO");
else puts("YES");
}
return 0;
}标签:字典树
原文地址:http://blog.csdn.net/zsgg_acm/article/details/43837083