hdu 1004 簡單字典樹(靜態)

hdu1004

菜鳥要從水做起

Let the Balloon Rise 我用的靜態字典樹(動態的沒看懂),題意是找出氣球顏色多的輸出敲打,所以只需要字典樹的一步“插入單詞”函數就可完成。


字典樹的意思就是先給一個根節點,然後順着這條根節點往下連接兒子節點的那條邊作爲單詞的一個字母,如果存在這個字母就下去找那個兒子節點,然後同理找下一個字母。不存在這個字母的話,根節點就再生一個兒子,然後繼續不斷地生..查找同理,字母不存在就說明沒這個單詞

本題的水代碼

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <math.h>
#include <map>
#include <algorithm>
using namespace std;
char s[20], ans[20];
int ch[1500][26];
int val[1500];
int tot, maxx;
void insert(char *a, int rt)
{
    for (int i = 0; a[i]; i++)
    {
        int x = a[i] - 'a';
        if (ch[rt][x] == 0)
        {
            ch[rt][x] = tot++;
        }
        rt = ch[rt][x];
    }
    val[rt]++;
    if (maxx < val[rt])
    {
        maxx = val[rt];
        strcpy(ans, a);
    }
}

int main()
{
    int n;
    while (scanf("%d", &n) == 1 && n)
    {
        int i;
        tot = 0, maxx = 0;
        memset(val, 0, sizeof val);
        memset(ch[1], 0, sizeof(ch[1]));
        for (i = 0; i < n; i++)
        {
            scanf("%s", s);
            insert(s, 1);
        }
        printf("%s\n", ans);
    }
    return 0;
}

附一個學長給的靜態字典樹模板

#include <stdio.h>
#include <string.h>
const int maxn=10000;//提前估計好可能會開的節點的個數

int tot;            //節點編號,模擬申請新節點,靜態申請
int trie[maxn][26]; //假設每個節點的分支有26個
bool isw[maxn];     //判斷該節點是不是單詞結尾

void insert(char *s,int rt){
    for(int i=0;s[i];i++){
        int x=s[i]-'a';//假設單詞都是小寫字母組成
        if(trie[rt][x]==0){//沒有,申請新節點
            trie[rt][x]=++tot;
        }
        rt=trie[rt][x];
    }
    isw[rt]=true;
}

bool find(char *s,int rt){
    for(int i=0;s[i];i++){
        int x=s[i]-'a';//假設單詞都是小寫字母組成
        if(trie[rt][x]==0){
            return false;
        }
        rt=trie[rt][x];
    }
    return isw[rt];
}

char s[22];//單詞讀入

int main(){
    tot=0;//一開始沒有節點

    int rt=++tot;//申請一個根節點
    memset(trie[rt],0,sizeof(trie[rt]));//初始化根節點
    memset(isw,false,sizeof(isw));

    while(scanf("%s",s),s[0]!='#'){//新建字典,以一個'#'結束
        insert(s,rt);
    }
    while(scanf("%s",s),s[0]!='#'){//查單詞,以一個'#'結束
        if(find(s,rt))
            printf("%s 在字典中\n",s);
        else
            printf("%s 不在字典中\n",s);
    }
    return 0;
}




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