zoukankan      html  css  js  c++  java
  • poj 2001 Trie树

    题意思路简单,直接贴代码

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

    #define MAXN 1005
    #define MAXLEN 25

    int N;
    char strs[MAXN][MAXLEN];

    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;
    }
    }
    }

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

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

    void work() {
    Trie
    *root = newTrieNode();
    int len, i;
    N
    = 0;
    while (scanf("%s", strs[N]) != EOF) {
    N
    ++;
    }
    for(i = 0; i < N; i++) {
    len
    = strlen(strs[i]);
    insert(root, strs[i], len);
    }
    count(root);
    for(i = 0; i < N; i++) {
    printf(
    "%s ", strs[i]);
    putprefix(root, strs[i], strlen(strs[i]));
    putchar(
    '\n');
    }
    destroy(root);
    }

    int main() {
    #ifndef ONLINE_JUDGE
    freopen(
    "data.in", "r", stdin);
    #endif
    work();
    return 0;
    }
  • 相关阅读:
    nput keyup 500ms 延时输入 事件处理
    browser-sync默认地址如何转成127.0.0.1
    overflow:scroll-css知识备忘
    圆角的css样式
    支付宝开发
    C#代码与javaScript函数的相互调用
    高性能web开发 如何加载JS,JS应该放在什么位置?
    Makefile自动生成头文件依赖
    一步步教你如何写Makefile
    (一):U-BOOT启动分析--概述
  • 原文地址:https://www.cnblogs.com/moonbay/p/2144873.html
Copyright © 2011-2022 走看看