UVa 11732 - strcmp() Anyone? (Trie + 邻接表)

思路

为了节省空间,用了邻接表。

记录一下在每个节点是否有单词结束,

然后边插入边比较

参考了ShoutMoon的代码

代码

 
 
  1. #include <cstdio>
  2. #include <stack>
  3. #include <set>
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. #include <queue>
  8. #include <functional>
  9. #include <cstring>
  10. #include <algorithm>
  11. #include <cctype>
  12. #include <ctime>
  13. #include <cstdlib>
  14. #include <fstream>
  15. #include <string>
  16. #include <sstream>
  17. #include <map>
  18. #include <cmath>
  19. #define LL long long
  20. #define SZ(x) (int)x.size()
  21. #define Lowbit(x) ((x) & (-x))
  22. #define MP(a, b) make_pair(a, b)
  23. #define MS(arr, num) memset(arr, num, sizeof(arr))
  24. #define PB push_back
  25. #define F first
  26. #define S second
  27. #define ROP freopen("input.txt", "r", stdin);
  28. #define MID(a, b) (a + ((b - a) >> 1))
  29. #define LC rt << 1, l, mid
  30. #define RC rt << 1|1, mid + 1, r
  31. #define LRT rt << 1
  32. #define RRT rt << 1|1
  33. #define BitCount(x) __builtin_popcount(x)
  34. const double PI = acos(-1.0);
  35. const int INF = 0x3f3f3f3f;
  36. using namespace std;
  37. const int MAXN = 4000 * 1000 + 5;
  38. const int MOD = 20071027;
  39. typedef pair<int, int> pii;
  40. typedef vector<int>::iterator viti;
  41. typedef vector<pii>::iterator vitii;
  42. char str[1010];
  43. struct TRIE
  44. {
  45. int head[MAXN], next[MAXN], ch[MAXN], val[MAXN];
  46. int sz;
  47. LL ans;
  48. void init()
  49. {
  50. sz = 1; ans = 0; ch[0] = 0; head[0] = next[0] = val[0] = 0;
  51. }
  52. void insert(char *s)
  53. {
  54. int len = strlen(s), u = 0, p;
  55. for (int i = 0; i <= len; i++)
  56. {
  57. for (p = head[u]; p; p = next[p])
  58. if (ch[p] == s[i]) break;
  59. if (!p)
  60. {
  61. p = sz++;
  62. ch[p] = s[i];
  63. next[p] = head[u];
  64. head[u] = p;
  65. head[p] = 0;
  66. val[p] = 0;
  67. }
  68. ans += (val[u] - val[p]) * (2 * i + 1);
  69. if (i == len)
  70. {
  71. ans += val[p] * (2 * (i + 1));
  72. val[p]++;
  73. }
  74. val[u]++;
  75. u = p;
  76. }
  77. }
  78. }trie;
  79. int main()
  80. {
  81. //ROP;
  82. int n, i, j, cases = 0;
  83. while (scanf("%d%*c", &n), n)
  84. {
  85. trie.init();
  86. while (n--)
  87. {
  88. scanf("%s", str);
  89. trie.insert(str);
  90. }
  91. printf("Case %d: %lld\n", ++cases, trie.ans);
  92. }
  93. return 0;
  94. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值