Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <set>
- #include <map>
- #include <algorithm>
- #include <cstdio>
- #include <cstring>
- using namespace std;
- #define forn(i,j,z) for(int i = (j); i < (z); i++)
- typedef long long int ll;
- #define P 100000007LL
- string wrds[100100];
- set<ll> dict;
- map<ll,int> pre;
- int main () {
- int n;
- ll hsh = 0;
- while(scanf("%d", &n)==1 and n!=0) {
- dict.clear();
- pre.clear();
- forn(i,0,n) {
- char str[33];
- scanf("%s", str);
- wrds[i] = string(str);
- hsh = 0; for(int j = wrds[i].size()-1; j>= 0; j--) hsh = (hsh*27+wrds[i][j]-'a'+1)%P;
- // cout << wrds[i] << " : "<< hsh << endl;
- dict.insert(hsh);
- }
- ll r = 0, hshsuf[33], hshpre[33];
- forn(i,0,n) {
- hsh = 0; for(int j = wrds[i].size()-1; j>= 0; j--) hsh = (hsh*27+wrds[i][j]-'a'+1)%P, hshsuf[j] = hsh;
- ll pw=1;
- 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;
- forn(j,1,wrds[i].size())
- if(dict.count(hshsuf[j]))
- pre[hshpre[j-1]]++;
- }
- forn(i,0,n) {
- hsh = 0; for(int j = wrds[i].size()-1; j>= 0; j--) hsh = (hsh*27+wrds[i][j]-'a'+1)%P, hshsuf[j] = hsh;
- ll pw=1;
- 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;
- forn(j,0,wrds[i].size()-1)
- if(dict.count(hshpre[j]))
- r+=pre[hshsuf[j+1]];
- }
- printf("%lld\n", r);
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment