After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it’s a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let’s say “aab” and “abcac”, and you concatenate them into “aababcac”, we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation “aabccbaa”).
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j)
is considered the same as the pair (j,i).
Input
The first line contains a positive integer N ( ), representing the length of the input array.
Eacg of the next N
lines contains a string (consisting of lowercase English letters from ‘a’ to ‘z’) — an element of the input array.
The total number of characters in the input array will be less than .
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
给你n个字符串,统计两两字符串中的有多少字符串的字符若能组成回文字符串(回文字符串和原字符串中的字符顺序无关)
//如果将字符进行预处理,用二进制来存储某个字母是否有偶数个,1表示奇数个,0表示偶数个
//两个字符串能构成回文数必须在合并后只有一个或零个字母是奇数个
//如果遍历比较,时间复杂度为O(n^2),还是超时
//因此可以先找状态一样的字符串,再找只有一个状态不同的字符串
//用二分查找,首先得将状态进行排序,那么复杂度就只有O(nlogn)
//二分查找可以用官方函数lower_bound(begin,end,num)和upper_bound(begin,end,num),分别返回第一个小于或等于num,大于num的位置
//注意lower_bound是小于等于num的位置,upper_bound是返回大于num的位置
#include <iostream>
#include <algorithm>
#include <string>
#define maxn 100005
using namespace std;
int dp[maxn] = {0};
int main()
{
int k;
string str;
unsigned long long ans = 0;
cin>>k;
//字符预处理
for (int i = 0; i < k; i++)
{
cin >> str;
for (int j = 0; j < str.size(); j++)
{
dp[i] ^= 1 << (str[j] - 'a');
}
}
//状态排序
sort(dp, dp + k);
for (int i = 0; i < k; i++)
{
int *l, *r;
l = lower_bound(dp, dp + k, dp[i]);
r = upper_bound(dp, dp + k, dp[i]);
ans += r - l-1; //统计一样的状态,要减去自身的一种
for (int j = 0; j < 26; j++) //统计只有一个不一样的状态
{
l = lower_bound(dp, dp + k, dp[i] ^ (1 << j));
r = upper_bound(dp, dp + k, dp[i] ^ (1 << j));
ans += r - l;
}
}
//ans中存在一半重复,要除2
cout<<ans/2<<endl;
return 0;
}