HDU1251 統計難題

HDU 1251 字典樹應用: 統計給定字符串爲前綴的單詞的數量 http://acm.hdu.edu.cn/showproblem.php?pid=1251

  又稱單詞查找樹,Trie樹,是一種樹形結構,是一種哈希樹的變種。典型應用是用於統計排序保存大量的字符串(但不僅限於字符串),所以經常被搜索引擎系統用於文本詞頻統計。它的優點是:利用字符串的公共前綴來節約存儲空間,最大限度地減少無謂的字符串比較,查詢效率比哈希表高。

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
struct Tire
{
    int count;
    struct Tire *tire[26];
}*a;
void init()
{
    a = new Tire;
    for(int i = 0; i < 26; i++)
        a->tire[i] = NULL;
}
void insert(char ch[])
{
    int length = strlen(ch);
    int k;
    Tire *head = a;
    for(int i = 0; i < length; i++)
    {
        k = (int)(ch[i]-97);
        if(head->tire[k] != NULL)
        {
            head = head->tire[k];
            head->count++;
        }
        else
        {
            head->tire[k] = new Tire;
            head = head->tire[k];
            head->count = 1;
            for(int j = 0; j < 26; j++)
                head->tire[j] = NULL;
        }
    }
}
int find(char cal[])
{
    int len = strlen(cal);
    int k;
    Tire *newhead = a;
    for(int i = 0; i < len; i++)
    {
        k = (int)(cal[i]-97);
        if(newhead->tire[k] != NULL)
            newhead = newhead->tire[k];
        else
            return 0;
    }
    return newhead->count;
}
int main()
{
    char s[10], ss[10];
    init();
    int len,num=0;
    while(gets(s)) //gets可以接收空格;而scanf遇到空格、回車和Tab鍵都會認爲輸入結束,所有它不能接收空格。
    {
        len = strlen(s);
        if(len == 0)
            break;
        insert(s);
    }
    while(gets(ss))
    {
        num = 0;
        num = find(ss);
        printf("%d\n", num);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章