zoukankan      html  css  js  c++  java
  • 统计难题

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

    通过这道题学习一下Trie字典树.

    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <string>
    #include <algorithm>
    #include <map>
    #include <stack>
    #include <cmath>
    #include <queue>
    #include <set>
    #include <list>
    #include <cctype>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define REP(i,j,k) for(int i = j ; i < k ; ++i)
    #define MAXV (1000)
    #define INF (0x6FFFFFFF)
    #define MAX 26
    using namespace std;
    typedef struct Trie
    {
        Trie *next[MAX];
        int v;//这里表示该字符前缀出现的次数
    };
    Trie *root;
    
    void Insert(char *str)
    {
        Trie *current = root;
        int  len=strlen(str);
        if(len==0) return ;
        REP(i,0,len)
        {
            //若节点存在,则直接访问下一个节点,并此前缀出现次数+1
            if(current->next[str[i]-'a']!=NULL)
            {
                current=current->next[str[i]-'a'];
                current->v++;
            }
            //若节点不存在,则新建节点并初始化
            else
            {
                current->next[str[i]-'a']=(Trie*)malloc(sizeof(Trie));
                current=current->next[str[i]-'a'];
                REP(i,0,26) current->next[i]=NULL;
                current->v=1;
            }
        }
    }
    int Find(char *str)
    {
        int len=strlen(str);
        struct Trie *current=root;
        if(len==0) return 0;
        REP(i,0,len)
        {
            //如果关键词本字符存在,则访问下一个节点
            if(current->next[str[i]-'a']!=NULL)
                current=current->next[str[i]-'a'];
            else
                return 0;//不存在直接返回0
        }
        return current->v;//返回该前缀出现次数
    }
    void Init()
    {
        root=(Trie *)malloc(sizeof(Trie));
        REP(i,0,26) root->next[i]=NULL;
        root->v=1;
    }
    int main()
    {
        Init();
        char str[11];
       // freopen("in.txt","r",stdin);
        while(gets(str)&&strcmp(str,"")!=0)
                Insert(str);
        char tmp[11];
        while(~scanf("%s",tmp))
            printf("%d\n",Find(tmp));
        return 0;
    }
  • 相关阅读:
    [SCM]软件配置管理
    Jenkins入门总结
    Linux sh/bash[精华]
    [BRE]软件构建发布自动化
    python总结
    代码质量第 3 层 可读的代码
    记一次 WinDbg 分析 .NET 某工厂MES系统 内存泄漏分析
    记一次 .NET 某消防物联网 后台服务 内存泄漏分析
    Covariant(协变)与 Contravariant(逆变)
    三藩市湾区一周游
  • 原文地址:https://www.cnblogs.com/aboutblank/p/3122648.html
Copyright © 2011-2022 走看看