1524: [POI2006]Pal

Description

给出n个回文串s1, s2, …, sn 求如下二元组(i, j)的个数 si + sj 仍然是回文串 规模 输入串总长不超过2M bytes

Input

The first line of input file contains the number of strings n. The following n lines describe each string: The i+1-th line contains the length of the i-th string li, then a single space and a string of li small letters of English alphabet. You can assume that the total length of all strings will not exceed 2,000,000. Two strings in different line may be the same.

Output

Print out only one integer, the number of palindromes

Sample Input

6
2 aa
3 aba
3 aaa
6 abaaba
5 aaaaa
4 abba

Sample Output

14
 
考虑三种情况,两个字符串s1,s2
①len(s1)==len(s2)则s1==s2
②len(s1)<len(s2)则s1是s2的后缀,s2剩下的部分是一个回文串
③len(s1)>len(s2)则s2是s1的前缀,s1剩下的部分是一个回文串
因为每个串都是回文串,所以情况2,3是一样的,而情况1也可以看做是两种情况的一种特殊情况。
所以我们可以构建一棵trie树,枚举每个串,沿着trie树向下走,枚举每个前缀,用hash判断是否构成回文串。。
 1 #include<iostream>
 2 #include<cstdlib>
 3 #include<cmath>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<algorithm>
 7 #include<string>
 8 #include<map>
 9 #include<queue>
10 #include<vector>
11 #include<set>
12 #define inf 1000000000
13 #define maxn 2000000+5
14 #define maxm 2000000+5
15 #define base 131
16 #define eps 1e-10
17 #define ll long long
18 #define for0(i,n) for(int i=0;i<=(n);i++)
19 #define for1(i,n) for(int i=1;i<=(n);i++)
20 #define for2(i,x,y) for(int i=(x);i<=(y);i++)
21 #define for3(i,x,y) for(int i=(x);i>=(y);i--)
22 #define for4(i,x) for(int i=head[x],y=e[i].go;i;i=e[i].next,y=e[i].go)
23 using namespace std;
24 int read(){
25     int x=0,f=1;char ch=getchar();
26     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
27     while(ch>='0'&&ch<='9'){x=10*x+ch-'0';ch=getchar();}
28     return x*f;
29 }
30 int n,tot,t[maxn][27],g[maxn],len[maxm];
31 ll f[maxn],h[maxn],ans,ha[maxm];
32 char s[maxn];
33 string st[maxm];
34 int main(){
35     //freopen("input.txt","r",stdin);
36     //freopen("output.txt","w",stdout);
37     h[0]=1;
38     for1(i,maxn)h[i]=h[i-1]*base;
39     n=read();ans=-n;
40     for1(k,n){
41         len[k]=read();
42         scanf("%s",s+1);st[k]=s+1;
43         int now=0;ll hash=0;
44         for1(i,len[k]){
45             int x=s[i]-'a'+1;
46             if(!t[now][x])t[now][x]=++tot;
47             now=t[now][x];
48             hash=hash*base+x;
49         }
50         ha[k]=hash;
51         f[now]=k;g[now]++;
52     }
53     for1(k,n){
54         int now=0;
55         for0(i,len[k]-1){
56             int x=st[k][i]-'a'+1;
57             now=t[now][x];
58             if(g[now]&&ha[f[now]]*h[len[k]]+ha[k]==ha[k]*h[i+1]+ha[f[now]])ans+=(ll)g[now]*2;
59         }
60     }
61     printf("%lld\n",ans);
62     return 0;
63 }
View Code

ps:似乎可以用拓展kmp来做。。。

posted @ 2016-06-17 16:31  HTWX  阅读(128)  评论(0编辑  收藏  举报