AC自动化

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ZERO 0
#define clen 26 /* 26个字母 */
const char fc = 'a';
typedef struct node
{
    struct node *child[clen]; /* 存储下一个字符 */
    int n; /* 记录当前单词出现的次数 */
}*Node;

Node root; /* 字典树的根结点(不存储任何字符) */
/* 插入单词 */
void insert(char *str)
{
    int i, index, len;
    Node current = NULL, newnode = NULL;
   
    len = strlen(str);
    if (ZERO == len) /* 此单词长度为零, 无须插入 */
    {
        return;
    } 
    current = root; /* 开始时当前的结点为根结点 */
    for (i = 0; i < len; i++) /* 逐个字符插入 */
    {
        index = str[i] - FIRST_CHAR; /* 获取此字符的下标 */
        if (current->child[index] != NULL) /* 字符已在字典树中 */
        {
            current = current->child[index]; /* 修改当前的结点位置 */
            (current->n)++; /* 当前单词又出现一次, 累加 */
        }
        else /* 此字符还没出现过, 则新增结点 */
        {
            newnode = (Node)calloc(1, sizeof(node)); /* 新增一结点, 并初始化 */
            if (NULL == newnode)
            {
                printf("空间分配失败! ");
                exit(-1);
            }
            current->child[index] = newnode;
            current = newnode; /* 修改当前的结点的位置 */
            current->n = 1; /* 此新单词出现一次 */
        }
    }
}
/* 在字典树中查找单词 */
int find_word(char *str)
{
    int i, index, len;
    Node current = NULL;
   
    len = strlen(str);
    if (ZERO == len) /* 当前单词长度为0, 则直接返回 */
    {
        return ZERO;
    }
   
    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; /* 此单词出现的次数 */
}
/*释放内存*/
void release(Node root)
{
    int i;  
    if (NULL == root)
    {
        return;
    }
   
    for (i = 0; i < ALPH_LEN; i++)
    {
        if ( root->child[i] != NULL )
        {
            release( root->child[i] );
        }
    }
   
    free( root );
    root = NULL;
}

int main()
{
    char tmp[11];
    int i;
  
    root = (Node)calloc(1,sizeof(node));
    if (NULL == root)
    {
        printf("空间分配失败! ");
        exit(-1);
    }

    while (gets(tmp), strcmp(tmp, "") != ZERO)
    {
        insert( tmp );
    }
   
    while (scanf("%s", tmp) != EOF)
    {
        i = find_word( tmp );
        printf("%d ", i);
    }
   
    release( root );

    return 0;
}

Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.
 
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 
Sample Input
banana
band
bee
absolute
acm

ba
b
band
abc
 
Sample Output
2
3
1
0
 
 
原文地址:https://www.cnblogs.com/luzhongshan/p/3875452.html