zoukankan      html  css  js  c++  java
  • poj2503

    trie树。

    这题学会的:

    1.strtok(char * st1, char*st2)用st2分割st1,损坏原串,返回分割后的第一个串的指针,想获得被分割的第二个串则需要调用第二次,并且第一个参数给NULL

    2.unget(ch, stdin);可以把读到的字符ch放回到输入文件中去。相当于getchar()的你过程。

    3.树状结构频繁开辟指针空间浪费时间,可以直接开辟节点数组,并让指针指向数组中的未使用位。

    View Code
    #include <iostream>
    #include
    <cstdio>
    #include
    <cstdlib>
    #include
    <cstring>
    #include
    <algorithm>
    using namespace std;

    #define maxn 100005
    #define L 11

    struct Node
    {
    Node
    *next[26];
    char *word;
    }
    *trie;

    Node
    *insert(Node *proot, char *a)
    {
    if (a[0] == '\0')
    return proot;
    if (proot->next[a[0] - 'a'] == NULL)
    {
    proot
    ->next[a[0] - 'a'] = new Node;
    memset(proot
    ->next[a[0] - 'a']->next, 0, sizeof(proot->next[a[0] - 'a']->next));
    proot
    ->next[a[0] - 'a']->word = NULL;
    }
    return insert(proot->next[a[0]-'a'], a + 1);
    }

    Node
    *query(Node *proot, char *a)
    {
    if (a[0] == '\0')
    {
    if (proot->word)
    return proot;
    return NULL;
    }
    if (proot->next[a[0]-'a'])
    return query(proot->next[a[0]-'a'], a + 1);
    return NULL;
    }


    int main()
    {
    freopen(
    "t.txt", "r", stdin);
    char st[L];
    trie
    = new Node;
    memset(trie
    ->next, 0, sizeof(trie->next));
    trie
    ->word = NULL;
    while (gets(st) && strcmp(st, "") != 0)
    {
    strtok(st,
    " ");
    char *ps = strtok(NULL, " ");
    if (ps == NULL)
    break;
    Node
    *p = insert(trie, ps);
    p
    ->word = new char[10];
    strcpy(p
    ->word, st);
    }
    while (gets(st) && strcmp(st, "") != 0)
    {
    Node
    *p = query(trie, st);
    if (p)
    printf(
    "%s\n", p->word);
    else
    printf(
    "eh\n");
    }
    return 0;
    }

  • 相关阅读:
    7月17日
    7月16日学习记录
    7月15日学习记录
    git 学习
    投稿相关
    ubuntu16.04 安装以及要做的事情
    python学习使用
    图像相关
    不识别移动硬盘
    深度学习
  • 原文地址:https://www.cnblogs.com/rainydays/p/2048032.html
Copyright © 2011-2022 走看看