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.
题意:给你n个只有s和h组成的字符串,让你拼接成一个字符串,使得子序列为sh的数量尽可能多,输出最大数量。
题解:一道水题,死于打错变量。。。一个假算法是让s尽可能的靠左,使得h尽可能的在s的后边,但是有一个很简单的样例就能hack掉该方法,比如说两个字符串:hhss和hshh,按照上述方法排序后组成的串为hshhhhss,答案变成4了,但是显而易见hhsshshh更优,答案是8,因此很容易想到我们可以按照当前两字符串的相对位置对答案的贡献排序,也就是假设当前只有这两个字符串,比较谁排前谁排后更优,这也就是你要快排的先后次序的条件了。。
#include<string>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
struct node
{
int sum,flag,as;
string s;
}a[100005];
ll n,ans,num,num1;
bool comp(node a,node b)
{
if(a.sum*(b.s.size()-b.sum)>b.sum*(a.s.size()-a.sum))
return 1;
return 0;
}
int main(void)
{
scanf("%lld",&n);
for(int i=1;i<=n;i++)
{
cin >> a[i].s;
for(int j=0;j<a[i].s.size();j++)
{
if(a[i].s[j]=='s')
a[i].sum++;
else
a[i].as+=a[i].sum;
}
}
sort(a+1,a+n+1,comp);
//for(int i=1;i<=n;i++)
//cout << s[i] << endl;
for(int i=1;i<=n;i++)
{
num1=a[i].s.size()-a[i].sum;
ans+=num*num1+a[i].as;num+=a[i].sum;
//printf("%d\n",a[i].s.size());
}
printf("%lld\n",ans);
return 0;
}