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. }

你可能感兴趣的:(ACM,uva)