Guest User

Untitled

a guest
Jan 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <set>
  3. #include <map>
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <cstring>
  7.  
  8. using namespace std;
  9.  
  10. #define forn(i,j,z) for(int i = (j); i < (z); i++)
  11.  
  12. typedef long long int ll;
  13. #define P 100000007LL
  14. string wrds[100100];
  15. set<ll> dict;
  16. map<ll,int> pre;
  17. int main () {
  18.     int n;
  19.     ll hsh = 0;
  20.     while(scanf("%d", &n)==1 and n!=0) {
  21.         dict.clear();
  22.         pre.clear();
  23.         forn(i,0,n) {
  24.             char str[33];
  25.             scanf("%s", str);
  26.             wrds[i] = string(str);
  27.             hsh = 0; for(int j = wrds[i].size()-1; j>= 0; j--) hsh = (hsh*27+wrds[i][j]-'a'+1)%P;
  28. //          cout << wrds[i] << " : "<< hsh << endl;
  29.             dict.insert(hsh);
  30.         }
  31.         ll r = 0, hshsuf[33], hshpre[33];
  32.         forn(i,0,n) {
  33.             hsh = 0; for(int j = wrds[i].size()-1; j>= 0; j--) hsh = (hsh*27+wrds[i][j]-'a'+1)%P, hshsuf[j] = hsh;
  34.             ll pw=1;
  35.             hsh = 0; for(int j = 0; j < wrds[i].size();j++,pw*=27,pw%=P) hsh = (hsh+(wrds[i][j]-'a'+1)*pw)%P, hshpre[j] = hsh;
  36.             forn(j,1,wrds[i].size())
  37.                 if(dict.count(hshsuf[j]))
  38.                     pre[hshpre[j-1]]++;
  39.         }
  40.         forn(i,0,n) {
  41.             hsh = 0; for(int j = wrds[i].size()-1; j>= 0; j--) hsh = (hsh*27+wrds[i][j]-'a'+1)%P, hshsuf[j] = hsh;
  42.             ll pw=1;
  43.             hsh = 0; for(int j = 0; j < wrds[i].size();j++,pw*=27,pw%=P) hsh = (hsh+(wrds[i][j]-'a'+1)*pw)%P, hshpre[j] = hsh;
  44.             forn(j,0,wrds[i].size()-1)
  45.                 if(dict.count(hshpre[j]))
  46.                     r+=pre[hshsuf[j+1]];
  47.         }
  48.         printf("%lld\n", r);
  49.     }
  50.     return 0;
  51. }
Add Comment
Please, Sign In to add comment