zoukankan      html  css  js  c++  java
  • hdu 1251(字典树)

    题意:容易理解。。。

    思路:很简单的字典树,容易求解,但是也有坑爹的地方。

    代码实现:

    #include<iostream>
    #include<cstring>
    #include<stdlib.h>
    using namespace std;
    struct node{
    struct node *next[26];
    int num;
    node()
    {
    memset(next,NULL,sizeof(next));
    num=1;
    }
    };
    struct node *root;
    void insert(char *str)
    {
    struct node *p=root;
    int index;
    for(;*str!='\0';str++)
    {
    index=*str-'a';
    if(p->next[index]==NULL)
    p->next[index]=new node;
    else
    p->next[index]->num++;
    p=p->next[index];
    }
    }
    int find(char *str)
    {
    struct node *p=root;
    int index;
    for(;*str!='\0';str++)
    {
    index=*str-'a';
    if(p->next[index]!=NULL)
    p=p->next[index];
    else
    return 0;
    }
    return p->num;
    }
    void del(struct node *tree)//虽然题目明确指出只有一组测试数据,但还是养成好的习惯释放内存
    {
    int i;
    for(i=0;i<26;i++)
    {
    if(tree->next[i]!=NULL)
    del(tree->next[i]);
    }
    delete(tree);//c++中的,c语言中是free
    }
    int main()
    {
    char str[20];
    root=new node;
    while(1)
    {
    gets(str);//scanf("%s",str);//这个地方很坑爹,用scanf他妈的就是不行
    if(strlen(str)==0)//因为scanf是无法读入空格的
    break;
    insert(str);
    }
    while(scanf("%s",str)!=EOF)
    {
      printf("%d\n",find(str));
    }
    del(root);
    return 0;
    }

  • 相关阅读:
    I
    poj 3414 pots (bfs+路径记录)
    hdoj 1495 非常可乐(bfs)
    hdoj 1241 Oil Deposits (dfs)
    hdoj 2612 find a way (两次bfs)
    poj 3984 迷宫问题
    poj 3087 Shuffle'm Up (bfs)
    poj 3126 Prime Path (bfs)
    poj 3279 Fliptile
    hdu_3068 最长回文(Manacher算法)
  • 原文地址:https://www.cnblogs.com/jiangjing/p/2951710.html
Copyright © 2011-2022 走看看