描述
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.
Input
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.
Output
Print a single integer — the maxumum possible noise Imp can achieve by
changing the order of the strings.
input
4
ssh
hs
s
hhhs
output
18
input
2
h
s
output
1
Note
The optimal concatenation in the first sample is ssshhshhhs.
思路
给出
n
n
<script type="math/tex" id="MathJax-Element-3">n</script>个串,每个串是由包含s,h
这两个字母的字符串组成的,让你用这些串组成一个长串,使得字符串的价值最大。一个字符串的价值是这个字符串中包含sh
的个数(s,h不一定相邻)
统计一下每个字符串出现的s
次数和出现的h
次数,用nums[i]
和numh[i]
来表示.假设有两个字符串a和b,要使字符串的价值最大那就是:比较一下nums[a]*numh[b]
和nums[b]*numh[a]
的大小,哪一个大来决定字符串的顺序,最后就可以通过排序确定一下最终的字符串,然后统计字符串中sh
的个数即可
代码
#include <cstdio>
#include <cstring>
#include <cctype>
#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
#define inf 1000000
#define mem(a,b) memset(a,b,sizeof(a))
const ll N=1e5+7;
string s[N];
ll nums[N],numh[N],id[N];
bool cmp(ll a,ll b)
{
return nums[a]*numh[b]>nums[b]*numh[a];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll n;
cin>>n;
for(ll i=0; i<n; i++)
{
cin>>s[i];
ll len=s[i].length();
for(ll j=0; j<len; j++)
{
if(s[i][j]=='s')
nums[i]++;
if(s[i][j]=='h')
numh[i]++;
}
id[i]=i;
}
sort(id,id+n,cmp);
ll ans=0,cnt=0;
for(ll i=0; i<n; i++)
{
string t=s[id[i]];
ll len=t.size();
for(ll j=0; j<len; j++)
{
if(t[j]=='s') cnt++;
else ans+=cnt;
}
}
cout<<ans<<endl;
return 0;
}