Advertisement
Guest User

Untitled

a guest
Jul 21st, 2013
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <climits>
  4. #include <cassert>
  5. #include <unordered_map>
  6.  
  7. using namespace std;
  8.  
  9. int trie[1000000][12];
  10. int64_t countWords[1000000];
  11. int tFree = 2;
  12.  
  13. int modA = 1000000007;
  14. int modB = 1000000009;
  15.  
  16. unordered_map<int64_t, int64_t> sufMap;
  17.  
  18. int main() {
  19.   int n;
  20.   cin >> n;
  21.   string s[n];
  22.   for (int it = 0; it < n; ++it) {
  23.     cin >> s[it];
  24.     int cur = 1;
  25.     for (int i = 0; i < s[it].size(); ++i) {
  26.       int c = s[it][i] - 'a';
  27.       if (!trie[cur][c]) {
  28.         trie[cur][c] = tFree++;
  29.       }
  30.       cur = trie[cur][c];
  31.     }
  32.     countWords[cur]++;
  33.   }
  34.   int64_t ans = 0;
  35.   for (int it = 0; it < n; ++it) {
  36.     int counts[s[it].size() + 1];
  37.     int cur = 1;
  38.     for (int i = 0; i < s[it].size(); ++i) {
  39.       int c = s[it][i] - 'a';
  40.       if (!trie[cur][c]) {
  41.         trie[cur][c] = tFree++;
  42.       }
  43.       cur = trie[cur][c];
  44.       counts[i] = countWords[cur];
  45.     }
  46.     counts[s[it].size() - 1] = 0;
  47.     int64_t hash = 0;
  48.     for (int i = s[it].size() - 1; i >= 0; --i) {
  49.       if (counts[i]) {
  50.         //cerr << s[it] << " " << i << " " << counts[i] << endl;
  51.         ans += sufMap[hash] * counts[i];
  52.         sufMap[hash] += counts[i];
  53.       }
  54.       hash = 47 * hash + s[it][i];
  55.     }
  56.   }
  57.   cout << ans << endl;
  58.   return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement