Mountain Subsequences | ||||||
| ||||||
Description | ||||||
Coco is a beautiful ACMer girl living in a very beautiful mountain. There are many trees and flowers on the mountain, and there are many animals and birds also. Coco like the mountain so much that she now name some letter sequences as Mountain Subsequences.
A Mountain Subsequence is defined as following: 1.If the length of the subsequence is n, there should be a max value letter, and the subsequence should like this, a1 < ...< ai < ai+1 < Amax > aj > aj+1 > ... > an 2.It should have at least 3 elements, and in the left of the max value letter there should have at least one element, the same as in the right. 3.The value of the letter is the ASCII value.
Given a letter sequence, Coco wants to know how many Mountain Subsequences exist.
| ||||||
Input | ||||||
Input contains multiple test cases. For each case there is a number n (1<= n <= 100000) which means the length of the letter sequence in the first line, and the next line contains the letter sequence. Please note that the letter sequence only contain lowercase letters.
| ||||||
Output | ||||||
For each case please output the number of the mountain subsequences module 2012. | ||||||
Sample Input | ||||||
4 abca | ||||||
Sample Output | ||||||
4 | ||||||
Hint | ||||||
The 4 mountain subsequences are: aba, aca, bca, abca | ||||||
Source | ||||||
HCPC2014校赛训练赛 2 |
题目大意(窝只会刷水啊):
给你一个长度为N的字符串(只包含小写字母),让你找一共有多少个子序列,是山形的。
思路:
1、计数问题,考虑dp;
①设定dp【26】表示dp到当前位子以第i个字母结尾的子序列的个数。
②设定dppre【i】表示以a【i】结尾的递增子序列个数。
③设定dpback【i】表示以a【i】结尾的逆序递增子序列个数。
那么不难想到,此时ans=dppre【i】*dpback【i】;
2、那么接下来考虑状态转移方程:
①对于dppre【i】:dppre【i】+=dp【j】(字母j小于字母a【i】);(解决了暴力O(n^2)处理会超时的情况)
如果上述状态转移方程我们暴力去写,就是dppre【i】+=dppre【j】(a【j】<a【i】);进一步递推得到Σdppre【j】==Σdp【j】;
②对于dp【i】:dp【i】=dppre【i】+1;
对于dpback【i】;逆序同理。
3、别忘了取摸。
Ac代码:
#include<stdio.h>
#include<string.h>
using namespace std;
#define ll long long int
#define mod 2012
ll dp[30];
ll dppre[100500];
ll dpback[100500];
char a[100500];
int main()
{
int n;
while(~scanf("%d",&n))
{
ll output=0;
memset(dppre,0,sizeof(dppre));
memset(dp,0,sizeof(dp));
memset(dpback,0,sizeof(dpback));
scanf("%s",a);
for(int i=0;i<n;i++)
{
for(int j=0;j<26;j++)
{
if(a[i]-'a'>j)
{
dppre[i]+=dp[j];
dppre[i]%=mod;
}
else break;
}
dp[a[i]-'a']+=dppre[i]+1;
dp[a[i]-'a']%=mod;
}
memset(dp,0,sizeof(dp));
for(int i=n-1;i>=0;i--)
{
for(int j=0;j<26;j++)
{
if(a[i]-'a'>j)
{
dpback[i]+=dp[j];
dpback[i]%=mod;
}
else break;
}
dp[a[i]-'a']+=dpback[i]+1;
dp[a[i]-'a']%=mod;
}
for(int i=0;i<n;i++)
{
output=(output+dppre[i]*dpback[i])%mod;
}
printf("%lld\n",output);
}
}