hdu 2846 Repository

题意:
     给你一些模式串。然后给你一些提问,每一个提问是给你一个串,问你这个串在上
面的模式串中出现的次数。


思路:

    字典树处理前缀的出现的次数的时候很拿手的,对于这个题目。我们能够把每一个串都拆开。拆成一个一个的,然后在把他们加在树里面,这样就OK了,另一个关键的地方,就是比方拆这个串 aa 能够拆成 a ,a ,aa。所以我们要在第一个a的时候仅仅累加一次,怎么做到呢,能够在node的结构体里面在开个变量,标记当前这个字母最后一次是被谁更新的,假设是自己,那么就不会num++.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ZERO 0
#define ALPH_LEN 26 /* 26个字母 */
const char FIRST_CHAR = 'a';

typedef struct node
{
    struct node *child[ALPH_LEN]; /* 存储下一个字符 */
    int n;
    int  num;
}node, *Node;

Node root; /* 字典树的根结点(不存储不论什么字符) */
/* 插入单词 */
void insert(char *str,int k)
{
    int i, index, len;
    Node current = NULL, newnode = NULL;
    
    len = strlen(str);
    
    current = root; /* 開始时当前的结点为根结点 */
    for (i = 0; i < len; i++) /* 逐个字符插入 */
    {
        index = str[i] - FIRST_CHAR; /* 获取此字符的下标 */
        if (current->child[index] != NULL) /* 字符已在字典树中 */
        {
            current = current->child[index]; /* 改动当前的结点位置 */
            if(current->num!=k)
            {
               (current->n)++;
               current->num=k;
            } 
        }
        else /* 此字符还没出现过, 则新增结点 */
        {
            newnode = (Node)calloc(1, sizeof(node)); /* 新增一结点, 并初始化 */
            current->child[index] = newnode;
            current = newnode; /* 改动当前的结点的位置 */
            current->n = 1; /* 此新单词出现一次 */
            current->num=k;
        }
    }
}
/* 在字典树中查找单词 */
int find_word(char *str)
{
    int i, index, len;
    Node current = NULL;
    
    len = strlen(str);
    
    current = root; /* 查找从根结点開始 */
    for (i = 0; i < len; i++)
    {
        index = str[i] - FIRST_CHAR; /* 获取此字符的下标 */
        if (current->child[index] != NULL) /* 当前字符存在字典树中 */
        {
            current = current->child[index]; /* 改动当前结点的位置 */
        }
        else
        {
            return ZERO; /*还没比較完就出现不匹配, 字典树中没有此单词*/
        }
    }
    
    return current->n; /* 此单词出现的次数 */
}

int main()
{
    char str[25],str2[25];
    int i,n,m,j,len;
    
    root = (Node)calloc(1, sizeof(node));
    scanf("%d",&n);
   {
      for(i=1;i<=n;i++)
      {
         scanf("%s",str);
         len=strlen(str);
        for(j=0;j<len;j++)
       {
          
          strncpy(str2,str+j,len-j);
          str2[len-j]='';
          insert( str2, i );
        }
      }
      scanf("%d",&m);
      while(m--)
      {
        scanf("%s",str);
        i = find_word( str );
        printf("%d
", i);
      }
   }
    return 0;
}


原文地址:https://www.cnblogs.com/llguanli/p/7010887.html