hdu1251(統計難題)

來源:互聯網
上載者:User

標籤:des   style   class   java   ext   color   

這題就是一個字典樹的模板題

統計難題

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others) Total Submission(s): 16997    Accepted Submission(s): 7318

Problem DescriptionIgnatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字串為首碼的單詞數量(單詞本身也是自己的首碼). Input輸入資料的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字串.
注意:本題只有一組測試資料,處理到檔案結束. Output對於每個提問,給出以該字串為首碼的單詞的數量. Sample Inputbananabandbeeabsoluteacmbabbandabc Sample Output2310想到的是對於輸入我卻不會,以空行結束while(gets(a)!=EOF&&a[0])//這題不能用scanf();\\if(strlen(a)==0) break;

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
typedef struct Node
{
    int flag;
    struct Node *next[26];
}Node,*Tree;
int kk=0;
void Creat(Tree &T)
{
    T=(Node *)malloc(sizeof(Node));
    T->flag=0;
    for(int i=0;i<26;i++)
        T->next[i]=NULL;
}
void insert(Tree &T,char *s)
{
    Tree p=T;
    int l=strlen(s);
    int t;
    for(int i=0;i<l;i++)
    {
        t=s[i]-‘a‘;
        if(p->next[t]==NULL)
            Creat(p->next[t]);
        p=p->next[t];
        p->flag++;
    }
}
int search(Tree &T,char *s)
{
    int t;
    Tree p=T;
    int l=strlen(s);
    for(int i=0;i<l;i++)
    {
        t=s[i]-‘a‘;
        if(p->next[t]==NULL)
            return 0;
        p=p->next[t];
    }
    return p->flag;
}
void Delete(Tree p)
{
    for(int i=0;i<26;i++)
     if(p->next[i]!=NULL)
      Delete(p->next[i]);
    free(p);
}
int main()
{
    char str[20];
    char a[20];
    Tree T;
    Creat(T);
    while(gets(a)&&a[0])
    {
        insert(T,a);
    }
    int tt;
    while(scanf("%s%*c",str)!=EOF)
    {
        tt=search(T,str);
        printf("%d\n",tt);
    }
    Delete(T);
    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.