hdu - 1251 - 统计难题(Trip)

来源:互联网 发布:ubuntu ssh远程登录 编辑:程序博客网 时间:2024/06/06 05:18

题意:Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

——>>叫统计难题,其实是。。。偷笑。。。

只需组织好Trip,并保存每个结点被单词经过的次数。。。询问时沿着Trip走就是。。。

#include <cstdio>#include <cstring>#include <queue>using namespace std;const int maxw = 10 + 5;char name[maxw], pre[maxw];struct node{    int cnt;    node *next[26];    node(){        cnt = 0;        memset(next, 0, sizeof(next));    }};struct Trip{    node *root;    Trip(){        root = new node;    }    int idx(char c){        return c - 'a';    }    void insert(char *s){        int len = strlen(s), i;        node *t = root;        for(i = 0; i < len; i++){            int c = idx(s[i]);            if(!t->next[c]) t->next[c] = new node;            t->next[c]->cnt++;            t = t->next[c];        }    }    void solve(char *s){        int ret = -1;        node *t = root;        int len = strlen(s);        for(int i = 0; i < len; i++){            int c = idx(s[i]);            t = t->next[c];            if(!t){                ret = 0;                break;            }        }        if(ret == -1) ret = t->cnt;        printf("%d\n", ret);    }};int main(){    Trip trip;    while(gets(name)){        if(!strlen(name)) break;        trip.insert(name);    }    while(scanf("%s", pre) == 1){        trip.solve(pre);    }    return 0;}


原创粉丝点击