现在的位置: 首页 > 综合 > 正文

HDU 1251 统计难题 – from lanshui_Yang

2019年01月07日 ⁄ 综合 ⁄ 共 1025字 ⁄ 字号 评论关闭

        题目大意:给你一个单词表,然后统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

        解题思路:这是一道赤裸裸的Trie树简单题,只要建好Trie树就可以了。

请看代码:

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std ;
const int MAXN = 1e5 + 7 ;
char s[100] ;
struct Tnode      // 建立 节点 结构
{
    int count ;
    Tnode *next[27] ;
} ;
Tnode * creatNode()
{
    Tnode * p = new Tnode ;
    p -> count = 0 ;
    memset(p -> next , 0 , sizeof(p -> next)) ;
    return p ;
}
void insert(char *str , Tnode * root)  // 插入 节点
{
    Tnode *p = root ;
    char *q = str ;
    while (*q)
    {
        char t = *q ;
        if(p -> next[t - 'a'] == NULL)
        {
            p -> next[t - 'a'] = creatNode() ;
        }
        p = p -> next[t - 'a'] ;
        p -> count ++ ;
        ++ q ;
    }
}
int search(char * str , Tnode * root)  // 查询节点
{
    Tnode *p = root ;
    char *q = str ;
    while (*q)
    {
        char t = *q ;
        if(p -> next[t - 'a'] == NULL)
            return 0 ;
        p = p -> next[t - 'a'] ;
        ++ q ;
    }
    return p -> count ;
}
void dele(Tnode * root)  // 释放 Trie 树
{
    Tnode *p = root ;
    int i ;
    for( i = 0 ; i < 26 ; i ++)
    {
        if(p -> next[i] != NULL)
        {
            dele(p -> next[i]) ;
        }
    }
    delete p ;
}
int main()
{
    Tnode *root = creatNode() ;
    while (gets(s))
    {
        if(s[0] == '\0')
            break ;
        insert(s , root) ;
    }
    while (gets(s) != NULL)  // 注意:gets()函数返回的是char 型的指针
    {
        if(s[0] == 0)
        break ;
        int ans = search(s , root) ;
        printf("%d\n" , ans) ;
    }
    return 0 ;
}


抱歉!评论已关闭.