日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

hdu 1251 统计难题 (Trie树)

發(fā)布時間:2025/3/15 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 hdu 1251 统计难题 (Trie树) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
本題是trie樹模板題,如果不用trie而用map寫可以看出trie處理這類問題有明顯的時間優(yōu)勢。 在trie樹中查找一個關(guān)鍵字的時間和樹中包含的結(jié)點數(shù)無關(guān),而取決于組成關(guān)鍵字的字符數(shù)。(對比:二叉查找樹的查找時間和樹中的結(jié)點數(shù)有關(guān)O(log2n)。) 如果要查找的關(guān)鍵字可以分解成字符序列且不是很長,利用trie樹查找速度優(yōu)于二叉查找樹。 若關(guān)鍵字長度最大是5,則利用trie樹,利用5次比較可以從265=11881376個可能的關(guān)鍵字中檢索出指定的關(guān)鍵字。而利用二叉查找樹至少要進行l(wèi)og2265=23.5次比較。 //125ms #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<string> #include<cmath> #include<map> #include<set> #include<vector> #include<algorithm> #include<stack> #include<queue> #include<cctype> #include<sstream> using namespace std; #define pii pair<int,int> #define LL long long int const int eps=1e-8; const int INF=1000000000; const int maxn=1; struct trie {trie *child[26];int v; }; trie root; void create_trie(char *ss) {int len=strlen(ss);trie *p=&root,*q;for(int i=0;i<len;i++){int id=ss[i]-'a';if(p->child[id]==NULL){q=(trie*)malloc(sizeof(trie));q->v=1;for(int j=0;j<26;j++){q->child[j]=NULL;}p->child[id]=q;p=p->child[id];}else{p->child[id]->v++;p=p->child[id];}} } int find_trie(char*ss) {int len=strlen(ss);trie *p=&root;for(int i=0;i<len;i++){int id=ss[i]-'a';if(p->child[id]==NULL) return 0;p=p->child[id];}return p->v; } int main() {//freopen("in8.txt","r",stdin);char str[15];while(gets(str)&&(str[0]!='\0')){create_trie(str);}while(scanf("%s",str)!=EOF){printf("%d\n",find_trie(str));}return 0; } trie樹實現(xiàn) //1171ms #include <iostream> #include <map> #include <cstring> #include <string> using namespace std;int main() {int i, len;char str[10];map<string, int> m;while( gets(str) ){len = strlen(str);if ( !len ){break;}for(i = len; i > 0; i--){str[i] = '\0';m[str]++;}}while( gets(str) ){cout << m[str] << endl;}return 0; } map實現(xiàn)

?

?

轉(zhuǎn)載于:https://www.cnblogs.com/zywscq/p/4127602.html

總結(jié)

以上是生活随笔為你收集整理的hdu 1251 统计难题 (Trie树)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。