HDU-1251 统计难题

老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀)

 

就是一个简单的字典树的题,写个字典树就OK了,但是要注意,解题的时候的字典树注意要尽量避免去使用动态开内存的情况,因为,内存可能会爆炸,题目中也说了。只有50000个单词,每个单词最多10个字符,那么也就是说,字典树中最多只有500000个节点,我们直接将这些节点开出来就可以了

 

代码实现

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

typedef struct node{
    // 记录在trie上经过当前节点的字符串的数量
    int count;
    char flag;
    int next[26];
}Node;

Node root;
int use = 1;
Node nodes[500005];

void init(Node* node){
    for(int i=0;i<26;i++){
        node->next[i] = 0;
    }
    node->count = 1;
    node->flag = 0;
}

void insert(char *str){
    Node* cur = &root;
    for(int i=0;str[i];i++){
        int c = str[i] - 'a';
        if(cur->next[c]){
            cur = &nodes[cur->next[c]];
            cur->count++;
        }else{
            Node* newNode = &nodes[use];
            init(newNode);
            cur->next[c] = use++;
            cur = newNode;
        }
    }
    cur->flag = 1;
}

int query(char * str){
    Node* cur = &root;
    for(int i=0;i<str[i];i++){
        int c = str[i] - 'a';
        if(cur->next[c]){
            cur = &nodes[cur->next[c]];
        }else{
            return 0;
        }
    }
    return cur->count;
}


int main(){
    printf("%d",sizeof(Node));
    char s[12];
    int len;
    init(&root);
    while(gets(s)){
        if(s[0] == '\0'){
            break;
        }
        insert(s);
    }
    while(gets(s)){
        printf("%d\n",query(s));
    }
}

 

这个就是爆空间的代码

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

typedef struct node{
    int count;
    char flag;
    int next[26];
}Node;

Node root;
int use = 1;
Node nodes[500005];

void init(Node* node){
    for(int i=0;i<26;i++){
        node->next[i] = 0;
    }
    node->count = 1;
    node->flag = 0;
}

void insert(char *str){
    Node* cur = &root;
    for(int i=0;str[i];i++){
        int c = str[i] - 'a';
        if(cur->next[c]){
            cur = &nodes[cur->next[c]];
            cur->count++;
        }else{
            Node* newNode = &nodes[use];
            init(newNode);
            cur->next[c] = use++;
            cur = newNode;
        }
    }
    cur->flag = 1;
}

int query(char * str){
    Node* cur = &root;
    for(int i=0;i<str[i];i++){
        int c = str[i] - 'a';
        if(cur->next[c]){
            cur = &nodes[cur->next[c]];
        }else{
            return 0;
        }
    }
    return cur->count;
}


int main(){
    printf("%d",sizeof(Node));
    char s[12];
    int len;
    init(&root);
    while(gets(s)){
        if(s[0] == '\0'){
            break;
        }
        insert(s);
    }
    while(gets(s)){
        printf("%d\n",query(s));
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值