您的位置:首页 > 其它

hihoCoder 1014trie树(字典树)

2015-07-27 21:40 351 查看

hihoCoder 1014

题目提示已经很清楚了~

贴代码……

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int MAXN = 100000 + 10;
const int alNum = 26;
struct Node{
int cnt;
int next[alNum];
void init(){
memset(next,-1,sizeof(next));
cnt = 0;
return;
}
};
Node trie[MAXN];
int tt;
void build_trie(char str[]){
int len = strlen(str);
int p = 0;
for(int i = 0;i < len;i++){
int ch = str[i] - 'a';
if(trie

.next[ch] == -1){ trie[tt].init(); trie[p].next[ch] = tt++; } p = trie[p].next[ch]; trie[p].cnt++; } } int quercy(char str[]){ int len = strlen(str); int p = 0; for(int i = 0;i < len;i++){ int ch = str[i] - 'a'; if(trie[p].next[ch] == -1){ return 0; } p = trie[p].next[ch]; } return trie[p].cnt; } int main(){ // freopen("input.txt","r",stdin); int n,m; while(~scanf("%d",&n)){ char str[20]; tt = 0; trie[tt++].init(); for(int i = 0;i < n;i++){ scanf("%s",str); build_trie(str); } scanf("%d",&m); for(int i = 0;i < m;i++){ scanf("%s",str); int q = quercy(str); printf("%d\n",q); } } return 0; }

[p]hdu1671  Phone List

字典树 水题

判断一个是否为另一个的前缀。

注意 9113

  911 的情况……

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int MAXN = 10000000 + 10;
const int NextNum = 10;

int tt;
struct Node{
int next[NextNum];
bool flag;
void init(){
memset(next,-1,sizeof(next));
flag = 0;
}
};
Node trie[MAXN];
bool build_trie(char str[]){
int p = 0;
int len = strlen(str);
for(int i = 0;i < len;i++){
int x = str[i] - '0';
if(trie

.next[x] == -1){ trie[tt].init(); trie[p].next[x] = tt++; } p = trie[p].next[x]; if(trie[p].flag){ return 0; } } for(int i = 0;i < NextNum;i++){ if(trie[p].next[i] != -1){ return 0; } } trie[p].flag = 1; return 1; } int main(){ // freopen("input.txt","r",stdin); int t; scanf("%d",&t); while(t--){ int n; scanf("%d",&n); tt = 0; trie[tt++].init(); bool ok = 1; char str[40+10]; for(int i = 0;i < n;i++){ scanf("%s",str); if(!ok){ continue; } ok = build_trie(str); } printf("%s\n",ok?"YES":"NO"); } return 0; }

[p] 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: