zoukankan      html  css  js  c++  java
  • hdu 1251 赤裸裸的Trie树

    在网吧做题,赶上杭电OJ不能交题,先把代码存在博客里,回学校提交,有错再改。

    /*
    * hdu1251/win.c
    * Created on: 2011-8-18
    * Author : ben
    */
    #include
    <stdio.h>
    #include
    <stdlib.h>
    #include
    <string.h>
    #include
    <math.h>

    typedef
    struct Trie {
    int num;
    struct Trie * br[26];
    } Trie;

    Trie
    * newTrieNode() {
    int i;
    Trie
    * node = (Trie *) malloc(sizeof(Trie));
    for (i = 0; i < 26; i++) {
    node
    ->br[i] = NULL;
    }
    node
    ->num = 0;
    return node;
    }

    void insert(Trie *root, char *str, int len) {
    int i;
    if (len <= 0) {
    root
    ->num = 1;
    return;
    }
    i
    = (*str) - 'a';
    if (!root->br[i]) {
    root
    ->br[i] = newTrieNode();
    }
    insert(root
    ->br[i], str + 1, len - 1);
    }

    void count(Trie *root) {
    int i;
    for (i = 0; i < 26; i++) {
    if (root->br[i]) {
    count(root
    ->br[i]);
    root
    ->num += root->br[i]->num;
    }
    }
    }

    int find(Trie *root, char *str, int len) {
    int i;
    if (len <= 0) {
    return root->num;
    }
    i
    = (*str) - 'a';
    if (!root->br[i]) {
    return 0;
    }
    else {
    return find(root->br[i], str + 1, len - 1);
    }
    }

    void destroy(Trie *root) {
    int i;
    for (i = 0; i < 26; i++) {
    if (root->br[i] != NULL) {
    destroy(root
    ->br[i]);
    }
    }
    free(root);
    }

    void work() {
    Trie
    *root = newTrieNode();
    char str[100];
    int len;
    while (1) {
    gets(str);
    len
    = strlen(str);
    if (len <= 0) {
    break;
    }
    insert(root, str, len);
    }
    count(root);
    while (scanf("%s", str) != EOF) {
    printf(
    "%d\n", find(root, str, strlen(str)));
    }
    destroy(root);
    }

    int main() {
    #ifndef ONLINE_JUDGE
    freopen(
    "data.in", "r", stdin);
    #endif
    work();
    return 0;
    }
    果然有错,还是太粗心了……
  • 相关阅读:
    LeetCode
    <OFFER15> 15_NumberOf1InBinary
    《OFFER14》14_CuttingRope
    Convert DataFrame string complex i to j python // “Cloning” row or column vectors
    Sorting arrays in NumPy by column
    【説明する】深度优先及宽度优先算法比较
    codevs 2924 数独挑战 x(三种做法+超详细注释~)
    第四次考试大整理
    洛谷 P1048 采药
    codevs 3137-3139 栈练习 x
  • 原文地址:https://www.cnblogs.com/moonbay/p/2144732.html
Copyright © 2011-2022 走看看