Pushok the dog has been chasing Imp for a few hours already.

Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and and
.
The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.
Help Imp to find the maximum noise he can achieve by changing the order of the strings.
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of strings in robot's memory.
Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.
4 ssh hs s hhhs
18
2 h s
1
The optimal concatenation in the first sample is ssshhshhhs.
题意改变字符串的顺序,看最多能有多少个i,j使得i<j,ti==‘s',tj=='h',是改变这几个字符串之间的顺序,而内部顺序是不能变的。
我们假设TA和TB分别为两个字符串,
如果顺序是TATB的话,这种情况下的'sh'数就是 A的‘sh'数+B的’sh‘数+B的'h'数 * A的‘s'数 即 Ash+Bsh+Bh*As
如果是TBTA的顺序的话, 总数为 A的‘sh'数+B的’sh‘数+A的'h'数 * B的‘s'数,即 Ash+Bsh+Ah*Bs
比较之后得到,如果 Bh*As>Ah*Bs ,就把A排在前面,如果 Bh*As<Ah*Bs 就把B放在前面
那相等的情况呢,我们很容易就能想到,s多的串放在前面当然就可以让答案更大。
所以我们创建这样的一个结构体
- struct node
- {
- long long ns; //s的个数
- long long nh; //h的个数
- long long ans; //该串的sh数
- };
- #include <bits/stdc++.h>
- #include <cstring>
- using namespace std;
- char s[100005];
- struct node
- {
- long long ns;
- long long nh;
- long long ans;
- }arr[100005];
- bool comp(node a,node b)
- {
- if(a.nh*b.ns<a.ns*b.nh)
- return true;
- else if(a.nh*b.ns>a.ns*b.nh)
- return false;
- else
- {
- if(a.ns>b.ns)
- return true;
- if(a.ns<b.ns)
- return false;
- return a.nh<b.nh;
- }
- }
- int main()
- {
- int n;
- scanf("%d ",&n);
- char c;
- for(int i=0;i<n;i++)
- {
- arr[i].nh=arr[i].ns=arr[i].ans=0;
- while(1)
- {
- scanf("%c",&c);
- if(c=='\n')
- break;
- if(c=='s')
- arr[i].ns++;
- else
- {
- arr[i].nh++;
- arr[i].ans+=arr[i].ns;
- }
- }
- }
- sort(arr,arr+n,comp);
- long long ans=0;
- long long num=0;
- for(int i=0;i<n;i++)
- {
- ans+=arr[i].ans+arr[i].nh*num;
- num+=arr[i].ns;
- }
- printf("%I64d\n",ans);
- return 0;
- }