HDU2072——单词数

字典树模板套用,求不同单词数的个数。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <algorithm>
using namespace std;

const int MAX=26;

typedef struct TrieNode
{
    int flag; 
    struct TrieNode *next[MAX]; //该节点的后续节点
} TrieNode;

TrieNode Memory[1000000]; 
int allocp = 0;
char s[50000];
int sum=0;
TrieNode * createTrieNode()
{
    TrieNode * tmp = &Memory[allocp++];
    tmp->flag = 1;
    for (int i = 0; i < MAX; i++)
        tmp->next[i] = NULL;
    return tmp;
}

void insertTrie(TrieNode *  pRoot, char * str)
{
    TrieNode * tmp = pRoot;
    int i = 0, k;
    //一个一个的插入字符
    int sign=1;
    while (str[i])
    {
        k = str[i] - 'a'; //当前字符 应该插入的位置
        if (tmp->next[k])
        {
            if(str[i+1]=='\0'&&tmp->next[k]->flag==1)
                sum++;
        }
        else
        {
            if(sign)
            {
                sum++;
                sign=0;
            }
            tmp->next[k] = createTrieNode();

        }

        tmp = tmp->next[k];
        i++; //移到下一个字符
    }
    tmp->flag=0;

}


int main(void)
{
    char temp[1000];
    int i;
    int length;
    int j;
    while(gets(s))
    {
        if(s[0]=='#')
            return 0;
        sum=0;
        length=strlen(s);
        
        allocp=0;
        TrieNode *Root = createTrieNode();
        i=0;
        while(i<length)
        {
            j=0;
            while(s[i]!=' '&&i<length)
            {
                temp[j++]=s[i++];
                
            }
            while(s[i]==' '&&i<length)
            {
                i++;
            }
            temp[j]='\0';
            //printf("%s\n",temp);

            insertTrie(Root,temp);
        }
        printf("%d\n",sum);
        
        
        
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值