fork download
  1. #include<bits/stdc++.h>
  2. #include<string.h>
  3. #define ll long long int
  4. #define fio ios_base::sync_with_stdio(false); cin.tie(NULL);
  5. #define MAX_LIMIT 10000000
  6. #define haha(x) x.begin(),x.end()
  7. #define rs resize
  8. #define remove_zero(str) str.erase(0, str.find_first_not_of('0'));
  9. #define br break
  10. const long long kot = LLONG_MAX;
  11. #define pb push_back
  12. #define pi 3.14159265358979323846
  13. #define pp pop_back
  14. #define pf pop_front
  15. using kk = long double;
  16. #define endl "\n"
  17. using namespace std;
  18. ll mini(ll a,ll b){
  19. return (a<b)?a:b;
  20. }
  21.  
  22. ll check(string s1,string s2){
  23. ll m=mini(s1.length(),s2.length());
  24. ll r=-1,i=0,c=0;
  25. while(i<m && r>=-m && s1[i]==s2[i] && s1[r]==s2[r]){
  26. c++;
  27. i++;
  28. r--;
  29. }
  30. return c;
  31. }
  32. void solve(){
  33. fio;
  34. ll T=1;
  35. cin>>T;
  36. while(T--){
  37. ll n;
  38. cin>>n;
  39. vector<string>v(n);
  40. map<string,ll>mp;
  41. ll i;
  42. for(i=0;i<n;i++){
  43. cin>>v[i];
  44. mp[v[i]]++;
  45. }
  46. /*for(auto it=mp.begin();it!=mp.end();it++){
  47.   cout<<it->first<<" "<<it->second<<" "<<endl;
  48.   }*/
  49. cout<<endl;
  50. ll ans=0;
  51. string s;
  52. ll x;
  53. v.clear();
  54.  
  55. for(auto it=mp.begin();it!=mp.end();it++){
  56. s=it->first;
  57. // cout<<s<<endl;
  58. x=it->second;
  59. // cout<<x<<endl;
  60. if(x%2==0){
  61. //cout<<x<<endl;
  62. ans+=(s.length())*(s.length())*(x/2);
  63. }
  64. else{
  65. ans+=(s.length())*(s.length())*(x/2);
  66. v.pb(s);
  67. }
  68. }
  69. /* for(i=0;i<v.size();i++){
  70.   cout<<v[i]<<endl;
  71.   }*/
  72. map<ll,pair<string,string>,greater<ll>>mo;
  73. ll j,k;
  74. for(i=0;i<v.size();i++){
  75. for(j=0;j<v.size();j++){
  76. if(i!=j){
  77. k=check(v[i],v[j]);
  78. if(k>0){
  79. mo.insert(make_pair(k,make_pair(v[i],v[j])));
  80. }
  81. }
  82. }
  83. }
  84. /*for(auto it=mo.begin();it!=mo.end();it++){
  85.   //cout<<"1"<<endl;
  86.   cout<<it->first<<" "<<it->second.first<<" "<<it->second.second<<" "<<endl;
  87.   }*/
  88. //cout<<endl;
  89. set<string>se;
  90. for(auto it=mo.begin();it!=mo.end();it++){
  91. if(se.find(it->second.first)!=se.end() and se.find(it->second.second)!=se.end()){
  92. ans+=(it->first)*(it->first);
  93. se.insert(it->second.first);
  94. se.insert(it->second.second);
  95. }
  96. }
  97. cout<<ans<<endl;
  98. }
  99. }
  100. /*
  101. 1
  102. 6
  103. nan
  104. noon
  105. nan
  106. noon
  107. apple
  108. noon
  109.  
  110. 1
  111. 6
  112. abcdefghijkl
  113. chef
  114. world
  115. code
  116. abcxyzhijkl
  117. word
  118. */
  119.  
  120.  
  121. int main()
  122. {
  123. fio;
  124. solve();
  125. }
  126.  
  127.  
Success #stdin #stdout 0s 4552KB
stdin
1
6
abcdefghijkl
chef
world
code
abcxyzhijkl
word
stdout
0