統計難題(map / 字典樹)

HDU1251
Problem Description
 Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字符串爲前綴的單詞數量(單詞本身也是自己的前綴).

Input
 輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.

注意:本題只有一組測試數據,處理到文件結束.

Output
對於每個提問,給出以該字符串爲前綴的單詞的數量.

Sample Input
banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output
2
3
1
0

map:

#include<stdio.h>
#include<string>
#include<map>
#include<string.h>
using namespace std;
int main(){
    char a[20], b[20];
    map<string,int>s;
    s.clear();
    while(gets(a), a[0] != '\0'){
         for(int i = strlen(a); i >= 0; i--){
             a[i] = '\0';
             s[a]++;
         }
    }
    while(gets(b)){
        printf("%d\n", s[b]);
    }
    return 0;
}

字典樹:
  推薦博客:http://www.cnblogs.com/TheRoadToTheGold/p/6290732.html
(1)數組模擬:

#include <stdio.h>
#include <string.h>
using namespace std;
int trie[2000005][30];
char a[20], b[20];
int root;
int tot, sum[2000005];
void insert(){
    int len = strlen(a);
    root = 0;
    for(int i = 0; i < len; i++){
        int pos = a[i] - 'a';
        if(!trie[root][pos]) trie[root][pos] = ++tot; //編號
        sum[trie[root][pos]]++;//統計前綴
        root = trie[root][pos];
    }
}
int search(){
    root = 0;
    int len = strlen(b);
    for(int i = 0; i < len; i++){
        int pos = b[i] - 'a';
        if(!trie[root][pos]) return 0;
        root = trie[root][pos];
    }
    return sum[root];
}
int main(){
    while(gets(a), a[0] != '\0'){
        insert();
    }
    while(gets(b)){
        printf("%d\n", search());
    }
}

(2)指針模擬
這道題用指針提交,無論如何都“Memory Limit Exceeded”,以後換道題試試指針好了

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