//============================================================================
// Name : POJ_2945.cpp
// Author : tiger
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <stdio.h>
using namespace std;
int ans[20005];
struct NODE
{
int num;
NODE *next[4];
void intil()
{
num = 0;
for (int i = 0; i < 4; i++)
next[i] = NULL;
}
};
NODE trie[20005*20];
int ant;
void insert(char *s, NODE *root)
{
if ( *s == '/0' )
{
root->num ++;
return ;
}
int p;
if (*s == 'A')
p = 0;
else if (*s == 'C')
p = 1;
else if (*s == 'G')
p = 2;
else
p = 3;
if(root->next[p] == NULL)
{
ant ++;
root->next[p] = trie+ant;
root->next[p]->intil();
}
insert(s+1,root->next[p]);
}
void find(NODE *root)
{
ans[root->num]++;
int i;
for(i= 0; i < 4; i++)
{
if(root->next[i])
find(root->next[i]);
}
}
int main()
{
freopen("in","r",stdin);
int i,n,m;
char s[30];
ant = 0;
NODE *root;
while(scanf("%d %d",&n,&m) )
{
if(n==0 && m ==0)//注意此题一定要判断n与m同时为0
break;
ant = 0;
root = trie+ant;
root->intil();
for(i = 1; i <= n; i++)
{
ans[i] = 0;
scanf("%s",s);
insert(s,root);
}
find(root);
for(i = 1; i <= n; i++)
{
printf("%d/n",ans[i]);
}
}
return 0;
}
本文详细解析了POJ_2945.cpp代码实现,介绍了一个基于C++的简单字符串匹配算法,利用前缀树(Trie树)进行字符串模式匹配。文章通过具体的代码展示了如何构造和使用前缀树来处理字符串查询问题。

被折叠的 条评论
为什么被折叠?



