hdu 1251 统计难题(数据结构:trie)

来源:互联网 发布:数据采集器下载 编辑:程序博客网 时间:2024/05/14 14:04

我的方法是建立trie的过程中,记录某个序列中每个字母出现的个数

如输入:

banana

band

bee

后,b的次数为3次,ba的次数为2次

这样的话在深搜一下就可以了

这个题很坑的地方是没说数组要开多大,我开了100,000还是WA, 改成400,000就过了

代码如下:

#include <cstdio>#include <cstring>#include <iostream>#define MAXN 400010using namespace std;int sz, ans, len;char str[12];int ch[MAXN][30];int val[MAXN];int id(char ch) {    return ch-'a';}void insert(char s[], int v) {    int u = 0, n = strlen(s);    for(int i=0; i<n; ++i) {        int c = id(s[i]);        if(!ch[u][c]) {            ch[u][c] = sz++;        }        val[ch[u][c]]++;        u = ch[u][c];    }}void dfs(int u, int depth) {    if(depth == len){        ans += val[u];        return ;    }    for(int i=0; i<26; ++i) {        if(ch[u][i] && i+'a'==str[depth]) {            dfs(ch[u][i], depth+1);        }    }}int main(void) {    sz = 1;    memset(ch, 0, sizeof(ch));    memset(val, 0, sizeof(val));    while(gets(str), *str) {        insert(str, 1);//        for(int i=0; i<sz; ++i)            //printf("%d\n", val[i]);        memset(str, 0, sizeof(str));    }    while(scanf("%s", str)!=EOF) {        ans = 0;        len = strlen(str);        dfs(0, 0);        printf("%d\n", ans);        memset(str, 0, sizeof(str));    }    return 0;}



0 0