HDU 2846 Repository

给一列数据list  再给查询字符串  求字符串在list中出现的次数

对于每个数据  暴力枚举他的子串  注意同一个字符串出现的次数不要叠加

如 list:  abab  ab  Q: ab  则答案为2 不为3  故要记录子串处于哪个数据(pos)

View Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const int MAXN = 50005;
struct node
{
    int pos, cnt;
    node *next[26];
    node()
    {
        cnt = 1;
        memset(next, 0, sizeof(next));
    }
}*tree ;
void insert( char *s, int i )
{
    node *p = tree;
    while( *s )
    {
        int num = *s - 'a';
        if(p->next[num] == NULL )
        {
            node *nn = new node();
            p->next[num] = nn;
            p->next[num]->pos = i;
        }
        else if(p->next[num]->pos != i)
        {
            p->next[num]->cnt ++ ;
            p->next[num]->pos = i;
        }
        p = p->next[num];
        s++;
    }
}
int search( char *s )
{
    node *p = tree ;
    while( *s )
    {
        int num = *s - 'a';
        if(p->next[num] == NULL)
            return 0;
        p = p->next[num];
        s++;
    }
    return p->cnt;
}
int main()
{
    int i = 0, n, q, cnt = 0;
    char str[25];
    tree = new node();
    scanf("%d", &n);
    while( n -- )
    {
        scanf("%s", str);
        int len = strlen(str);
        ++cnt ;
        for(i=0; i<len; i++)
            insert(str+i, cnt);
    }
    scanf("%d", &q);
    while( q-- )
    {
        scanf("%s", str);
        printf("%d\n", search(str));
    }
    return 0;
}

 

posted @ 2013-03-12 13:27  April_Tsui  阅读(129)  评论(0编辑  收藏  举报