zoukankan      html  css  js  c++  java
  • 字典树 HDU 1251 统计难题

    http://acm.hdu.edu.cn/showproblem.php?pid=1251

    这是重写的,让我感觉到每一次的理解程度都在增加
    #include<iostream>
    #include<algorithm>
    #include<stdio.h>
    #include<string.h>
    using namespace std;
    struct
    node
    {

        int
    sum;
        node *next[26];
        node()//初始化数据
        {
            memset(next, NULL, sizeof(next));
            sum=0;
        }
    };

    node *head=new node();//用C++的new动态申请内存其实delete和new是一对儿哦
    node *now=(node *)malloc(sizeof(node));//用C语言动态申请内存
    void buildtiretree(char *s)//建立字典数
    {
        node *p=new node();
        p=head;
        for
    (int i=0; s[i]; i++)
        {

            int
    k=s[i]-'a';
            if
    (p->next[k]==NULL)//如果p->next[k]为空
                p->next[k]=new node();//就动态申请一个内存
            now=p->next[k];
            now->sum++;
            p=now;
            /*也可以这样写,其实就是第一个,也就是head不存任何东西
            p=p->next[k];
            p->sum++;
            */

        }
    }

    int
    query(char *s)//查询单词
    {
        node *p=new node();
        p=head;
        //node *p=head;
        for(int i=0; s[i]; i++)
        {

            int
    k=s[i]-'a';
            if
    (p->next[k]==NULL)
                return
    0;
            p=p->next[k];
        }

        return
    p->sum;
    }

    void
    Free(node *head)//释放内存
    {
        int
    i;
        if
    (head==NULL)
            return
    ;
        for
    (i=0; i<26; i++)
        {

            if
    (head->next[i]!=NULL)
                Free(head->next[i]);
        }

        free(head);
        head=NULL;
    }

    int
    main()
    {

        char
    s[15];
        while
    (gets(s), s[0])
            buildtiretree(s);
        while
    (cin >> s)
        printf("%d ", query(s));
        Free(head);
        return
    0;
    }


    之前写的
    #include<iostream> #include<algorithm> #include<stdio.h>
    using namespace std; struct node { int sum; node *next[26]; }; void buildtrietree(node *head, char s[]) { node *p=new node(); p=head; for(int i=0; s[i]; i++) { int k=s[i]-'a'; if(p->next[k]==0) p->next[k]=new node(); p=p->next[k]; p->sum++; } } int query(node *head, char s[]) { node *p=new node(); p=head; for(int i=0; s[i]; i++) { int k=s[i]-'a'; if(p->next[k]==0) return 0; p=p->next[k]; } return p->sum; } int main() { char s[12]; node *head=new node(); while(gets(s), s[0]) buildtrietree(head, s); while(cin >> s) printf("%d ", query(head, s)); return 0; }

     

  • 相关阅读:
    排序-堆排序
    排序-计数排序
    Django之路——10 django的分页组件
    Django之路——9 Django的form组件的信息校验
    Django之路——8 cookie 和sessions
    Django之路——7 django与ajax
    Django之路——6 Django的模型层(二)
    Django之路——6 Django的模型层(一)
    Django之路——4 Django的视图层
    Django之路——5 Django的模板层
  • 原文地址:https://www.cnblogs.com/wazqWAZQ1/p/4691142.html
Copyright © 2011-2022 走看看