hdu 2072 单词数 字典树

来源:互联网 发布:解救吾先生知乎 编辑:程序博客网 时间:2024/06/05 06:08

题目链接


思路:

这个题其实好多方法可以做,map set 都可以搞过去.刚学字典树,所以用一下模板...

这个题只用到了插入,而且把字典树中的cnt稍微改动一下即可,那一个存的是到此位置时以该字符串为前缀的字符串的数量.这里表示的是该单词最后的尾节点在字符串中是否出现过,也就是是否出现过该单词.

#include <stdio.h>  #include <string.h>  #include <iostream>  #include <math.h>  #include <algorithm>  using namespace std;  const int maxn=1e6+10;char s[maxn];  char s2[maxn];  int ch[maxn][26];  int cnt[maxn], tmp, ans;//这里就将cnt数组进行了简单的变化,cnt数组表示最后该单词的尾节点在字典树中是否出现过//未出现过,单词总数就+1,否则不变.  void insert(char *a)  {      int rt = 0;      for (int i = 0; a[i]; i++)      {          int c = a[i] - 'a';          if (ch[rt][c] == 0)          {              cnt[tmp] = 0;               ch[rt][c] = tmp++;          }          rt = ch[rt][c];      }      if (cnt[rt] == 0) ans++;      cnt[rt] = 1;  }    int main()  {      while (gets(s) && strcmp(s, "#"))      {          int i, j, top = 0;          tmp = 1, ans = 0;          cnt[0] = 0;          memset(ch[0], 0, sizeof(ch[0]));          for (i = 0; i <= strlen(s); i++)          {              if (s[i] >= 'a' && s[i] <= 'z')                s2[top++] = s[i];              else              {                  if (top != 0)                  {s2[top] = '\0';                  top = 0;                  insert(s2);}              }          }          printf("%d\n", ans);      }      return 0;  }  


原创粉丝点击