Let's call two strings similar if there exists a bijective mapping over characters, which, when applied to the characters of the first string, makes it equal to the second string. For example, «abacaba» and «tetatet» are similar strings, but «test» and «bear» — are not. Given the set of strings, find the number of pairs of similar strings.
The first line contains one integer n — the number of strings.
Next n lines contain non-empty strings of lowercase Latin letters. The sum of lengths of these strings does not exceed106.
Output the only integer —the number of pairs of similar strings.
4 abacaba tetatet test bear
1
4 jury code will pass
2
4 your code wont pass
3
把字符串转换成一种标准形式,来快速查找以前出现的次数。
我用的对应规则是按字母出现的顺序进行标号,然后将字符串转换成一串数码。
example:
a b a c a b a
1 2 1 3 1 2 1
t e t a t e t
1 2 1 3 1 2 1
它们转换出的数码都是一样的,所以这两个字符串是一对。
t e s t
1 2 3 1
b e a r
1 2 3 4
它们转换出的数码不是一样的,所以这两个字符串不是是一对。
p.s.一定要把strlen(s);放在for循环外部,strlen(s);是一个O(n)的过程。
还有如果哈希表能开静态的就不要开map,map是O(logn)的复杂度。
#include<vector>
#include<map>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
int N;
map<vector<int>,LL> Map;
vector<int> q;
char s[1000100];
LL Letter[30];
inline int Find_Num(char c) {return c-96;}
int main()
{
LL ans=0;
scanf("%d",&N);
for(int i=1;i<=N;i++)
{
scanf("%s",s);
int num=0; q.clear();
memset(Letter,0,sizeof(Letter));
int len=strlen(s);
for(int i=0;i<len;i++)
if(Letter[Find_Num(s[i])]) q.push_back(Letter[Find_Num(s[i])]);
else {Letter[Find_Num(s[i])] = ++num; q.push_back(Letter[Find_Num(s[i])]);}
ans+=Map[q]++;
//Map[q]++;
}
printf("%I64d",ans);
while(1);
return 0;
}