POJ 2945 Trie

链接:

http://poj.org/problem?id=2945

题解:

给你n个字符串,统计出现1~n次的字符串各有多少个

题解:

这道题最快的做法应该就是字典树了吧,边插入边更新答案就行了

代码:

31 int cnt[MAXN];
32 int pi = 1;
33 
34 struct Node {
35     int next[26];
36     int sum;
37 }tree[MAXN * 20];
38 
39 void insert(string keyword) {
40     int index, p, i;
41     for (i = p = 0; keyword[i]; i++) {
42         index = keyword[i] - 'A';
43         if (tree[p].next[index] == 0)
44             tree[p].next[index] = pi++;
45         p = tree[p].next[index];
46     }
47     cnt[tree[p].sum++]--;
48     cnt[tree[p].sum]++;
49 }
50 
51 int main() {
52     int n, m;
53     while (cin >> n >> m, n) {
54         memset(tree, 0, sizeof(tree));
55         memset(cnt, 0, sizeof(cnt));
56         pi = 1;
57         rep(i, 0, n) {
58             string s;
59             cin >> s;
60             insert(s);
61         }
62         rep(i, 1, n + 1) printf("%d\n", cnt[i]);
63     }
64     return 0;
65 }

 

                               

  

posted @ 2017-04-30 20:57  Flowersea  阅读(210)  评论(2编辑  收藏  举报