Poi2006 Palindromes

时间:2022-09-24 12:43:30

2780: Poi2006 Palindromes

Time Limit: 10 Sec  Memory Limit: 512 MB
Submit: 15  Solved: 5
[Submit][Status][Web Board]

Description

A word is called a palindrome if we read from right to left is as same as we read from left to right. For example, "dad", "eye" and "racecar" are all palindromes, but "odd", "see" and "orange" are not palindromes. 
Given n strings, you can generate n × n pairs of them and concatenate the pairs into single words. The task is to count how many of the so generated words are palindromes. 
给出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

3
1 a
2 ab
2 ba

Sample Output

5
//The 5 palindromes are:aa aba aba abba baab

HINT

 

Source

题解:

  这个怎么写呢,一脸懵比。。。。。。。

  (龙老师说:)我们先把所有串插入一个trie树,然后统计每个串的hash,然后再枚举每个串,沿trie树向下走,枚举每一个前缀,判断他们俩连起来的字符串正着和                     反着是否一样,

   直接hash判断即可。

#include<iostream>
#include<cstring>
#include<cstdio>
#define ll long long
#define maxn 2000000
#define base 199
using namespace std;
int n,k;
ll hashmod,ans,tot;
ll h[maxn],ha[maxn];
int son[maxn][],sum[maxn],f[maxn],len[maxn];
string s[maxn],ch;
int main()
{
h[]=;
for (int i=; i<=maxn+; i++) h[i]=h[i-]*base;
cin>>n;
ans=-n;
for (int i=; i<=n; i++)
{
cin>>len[i];
cin>>ch;
s[i]=' '+ch;
int p=; hashmod=;
for (int j=; j<=len[i]; j++)
{
int x=s[i][j]-'a'+;
if (!son[p][x]) son[p][x]=++tot;
p=son[p][x];
hashmod=hashmod*base+x;
}
//cout<<hashmod<<endl;
ha[i]=hashmod;
f[p]=i; sum[p]++;
}
//cout<<tot;
for (int i=; i<=n; i++)
{
int p=;
for (int j=; j<=len[i]; j++)
{
int x=s[i][j]-'a'+;
p=son[p][x];
// cout<<p<<endl;
//if (sum[p] && ha[f[p]]*h[len[i]]+ha[i]==ha[i]*h[j+1]+ha[f[p]]) ans+=(ll)sum[p]*2;
if(son[p]&&ha[f[p]]*h[len[i]]+ha[i]==ha[i]*h[j]+ha[f[p]])ans+=(ll)sum[p]*;
}
}
printf("%lld\n",ans); return ;
}