字典樹裸題——統計難題

來源:互聯網
上載者:User
#include<iostream>#include<cstdio>#include<cstring>#include<string>#include<algorithm>using namespace std;#define N 3010struct Tire{int num;Tire *next[26];};Tire *root;void init() //初始化{root = new Tire;for(int i = 0; i < 26; ++i){root->next[i] = NULL;}}void insert(string word) {int temp, len;Tire *cur;len = word.length();cur = root;for(int i = 0; i < len; ++i){temp = word[i] - 'a';if(cur->next[temp] == NULL)//不存在則建立新的節點{Tire *newTire = new Tire;newTire->num=1;for(int j = 0; j < 26; ++j){newTire->next[j]=NULL;}cur->next[temp]=newTire;//將新節點接到當前節點的next上}else{cur->next[temp]->num++;//注意這個地方,num++的位置,是下一個節點的num++}cur = cur->next[temp];}}/*我第一次錯誤的寫法記憶體沒有釋放完全需要遞迴的釋放而這種釋放只釋放了26次void del(Tire *root) //動態建樹,用完釋放記憶體{for(int i = 0; i < 26; ++i)if(root->next[i] != NULL)delete(root->next[i]);}*/void del(Tire *root) //動態建樹,用完釋放記憶體{    for(int i=0;i<10;++i)    {        if(root->next[i]!=NULL)        del(root->next[i]);    }    delete(root);}//正確的寫法int search(string word){int len, temp;Tire *cur;len = word.length();cur = root;for(int i = 0; i < len; ++i){temp = word[i] - 'a';if(cur->next[temp] == NULL)return 0;cur = cur->next[temp];}return cur->num;}int main(){init();char word[11],ask[11];while(gets(word)){if(word[0]=='\0')break;insert(word);}while(gets(ask)){int count=search(ask);printf("%d\n",count);}del(root); //釋放記憶體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.