点击打开链接hdu 1251
题意:给点一序列的字符串,再给你一些单词,问以这个单词为前缀的字符串的个数,注意本身也是自己的前缀
思路:把给定的字符串建立一棵字典树,每一个节点保存的是当前节点为结尾的字符串出现的次数,那么对于给定的单词我们只要去查找字典树即可
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 1000010;
const int N = 26;
struct Node{
int cnt;
Node* child[N];
};
Node node[MAXN];
Node* root;
int pos;
Node* newNode(){
node[pos].cnt = 0;
for(int i = 0 ; i < N ; i++)
node[pos].child[i] = NULL;
return &node[pos++];
}
void insert(char* str){
int len = strlen(str);
Node* s = root;
for(int i = 0 ; i < len ; i++){
int num = str[i]-'a';
if(s->child[num] == NULL)
s->child[num] = newNode();
s = s->child[num];
s->cnt++;
}
}
int search(char* str){
int len = strlen(str);
Node* s = root;
for(int i = 0 ; i < len ; i++){
int num = str[i]-'a';
if(s->child[num] == NULL)
return 0;
s = s->child[num];
}
return s->cnt;
}
int main(){
pos = 0;
root = newNode();
char str[N];
while(gets(str) && str[0] != '\0')
insert(str);
while(scanf("%s" , str) != EOF)
printf("%d\n" , search(str));
return 0;
}
分享到:
相关推荐
HDU的1250,主要是利用高精度加法,但是代码有点繁琐,效率不是很高
杭电ACMhdu1163
HDU1059的代码
hdu1001解题报告
hdu 1574 passed sorce
HDU的一题........HDU DP动态规
hdu2101AC代码
hdu acm 教案 搜索入门 hdu acm 教案 搜索入门
搜索 dfs 解题代码 hdu1241
hdu 5007 Post Robot 字符串枚举。 暴力一下就可以了。
hdu acm 教案 动态规划(1) hdu acm 教案 动态规划(1)
ACM HDU题目分类,我自己总结的大概只有十来个吧
hdu 1166线段树代码
HDU最全ac代码
自己做的HDU ACM已经AC的题目
hdu动态规划算法集锦
hdu题目分类
HDU图论题目分类
hdu-acm源代码(上百题)hdu-acm源代码、hdu-acm源代码hdu-acm源代码
Hdu 1237 解题代码