HDU 1251 统计难题

来源:互联网 发布:华策影视 知乎 编辑:程序博客网 时间:2024/06/05 20:08

PS: 每每学到一个知识点,要多多练习知道非常熟悉,信手拈来, 以后多多练习一下强大的指针操作。

此题目开内存蛮大的。

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;struct Trie {    Trie* next[26];    int num;};//Accepted125178MS43796K1182 BC++AchiberTrie* root;void Insert(char *str) {    Trie* now = root;    int len = strlen(str);    for(int i = 0; i < len; i++) {        int id = str[i]-'a';        if(now->next[id]==NULL) {            Trie* p = new Trie;            p->num = 0;            memset(p->next, NULL, sizeof(p->next));            now->next[id] = p;        }        now = now->next[id];        now->num++;    }}int query(char* str) {    Trie* now = root;    int counter = 0;    int len = strlen(str);    for(int i = 0; i < len; i++) {        int id = str[i]-'a';        if(now->next[id]==NULL) {            return 0;        } else {            now = now->next[id];            counter = now->num;        }    }    return counter;}int main(){    root = new Trie;    memset(root->next, NULL, sizeof(root->next));    char str[20];    while(gets(str) && str[0]) Insert(str);    while(gets(str)) {        int res = query(str);        printf("%d\n", res);    }    return 0;}

0 0
原创粉丝点击