poj2418map或者字典树
生活随笔
收集整理的這篇文章主要介紹了
poj2418map或者字典树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:
? ? ?給你一些串,然后求出每個串出現的概率。
思路:
? ? ?給你一些串,然后求出每個串出現的概率。
思路:
? ? ?簡單題目,做法也很多,我用字典樹做了下,然后又用map做了下,其實這個題目我感覺直接排序一遍之后線性輸出應該是最簡單最快的(這個沒敲),就是只是排序的時間復雜度而已O(n*log(n)*len)字典序的排序時間復雜度記得*len.
字典樹829MS #include<stdio.h> #include<stdlib.h> #include<string.h> #include<algorithm>using namespace std;typedef struct Tree {Tree *next[129];int v; }Tree;typedef struct {char s[32]; }SS;Tree root; SS S[10005];bool camp(SS a ,SS b) {return strcmp(a.s ,b.s) < 0; }void BuidTree(char *str) {int len = strlen(str);Tree *p = &root ,*q;for(int i = 0 ;i < len ;i ++){int id = str[i];if(p -> next[id] == NULL){q = (Tree *)malloc(sizeof(root));q -> v = 0;for(int j = 0 ;j <= 128 ;j ++)q -> next[j] = NULL;p -> next[id] = q;p = p -> next[id];}else p = p -> next[id];}p -> v ++; }int Query(char *str) {int len = strlen(str);Tree * q = &root;for(int i = 0 ;i < len ;i ++){int id = str[i];q = q -> next[id];if(q == NULL) return 0;}return q -> v; }int main () {int i ,n ,id;char str[35];n = id = 0;for(i = 0 ;i <= 128 ;i ++)root.next[i] = NULL;while(gets(str)){if(!Query(str)){id ++;int len = strlen(str);for(int j = 0 ;j <= len ;j ++)S[id].s[j] = str[j];}BuidTree(str);n ++;}sort(S + 1 ,S + id + 1 ,camp);for(i = 1 ;i <= id ;i ++)printf("%s %.4lf\n" ,S[i].s ,Query(S[i].s) * 100.0 / n);return 0; }map 1500ms #include<map> #include<string> #include<stdio.h> #include<string.h> #include<algorithm>using namespace std;typedef struct {char s[35]; }SS;SS S[10005]; map<string ,int>mark;bool camp(SS a ,SS b) {return strcmp(a.s ,b.s) < 0; }int main () {mark.clear();char str[35];int id = 0 ,n = 0;while(gets(str)){if(mark[str] ++ == 0){int len = strlen(str);id ++;for(int i = 0 ;i <= len ;i ++)S[id].s[i] = str[i];}n ++;}sort(S + 1 ,S + id + 1 ,camp);for(int i = 1 ;i <= id ;i ++){printf("%s %.4lf\n" ,S[i].s ,mark[S[i].s] * 100.0 / n);}return 0;}
總結
以上是生活随笔為你收集整理的poj2418map或者字典树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ2296二分2sat
- 下一篇: POJ2406简单KMP