Mountain Subsequences(山东省第四届ACM大学生程序设计竞赛)

来源:互联网 发布:js调用电脑摄像头拍照 编辑:程序博客网 时间:2024/06/04 18:08

Problem 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.

Example Input

4abca

Example Output

4

Hint

The 4 mountain subsequences are:

aba, aca, bca, abca


题意:给定长度为n的由小写字母组成的字符串,求有多少个字符串满足严格递增再递减,注意abba,那么 aba ,aba算两个不同的串,因为下标不一样。


思路:正着dp一遍,反着一遍就行了


#include<iostream>#include<cstdio>#include<cstring>#include<string>#define maxn 100010#define INF 0x3f3f3f3f#define mod 2012using namespace std;int dp[maxn],f[30],n;  //f是装的是以字母'a'+i为结尾的子序列的个数;dp是以第i个字母结尾的递增子序列的个数;char s[maxn];int x;int main(){    while(scanf("%d",&n)!=EOF){        scanf("%s",s);        memset(f,0,sizeof(f));        for(int i=0;i<n;i++){  //正着来一遍;            x=s[i]-'a';  //提取数字;            dp[i]=0;            for(int j=0;j<x;j++){                dp[i]+=f[j];                dp[i]=dp[i]%mod;            }            f[x]+=(dp[i]+1);  //+1是因为要加上s[i]单个字符;            f[x]=f[x]%mod;        }        memset(f,0,sizeof(f));        long long sum=0,ans=0;        for(int i=n-1;i>=0;i--){  //反着来一遍;            x=s[i]-'a';            sum=0;            for(int j=0;j<x;j++){                sum+=f[j];                sum=sum%mod;            }            f[x]=f[x]+sum+1;            f[x]=f[x]%mod;            ans=ans+sum*dp[i];  //组合,所以要乘;            ans=ans%mod;        }        cout<<ans<<endl;  //输出最好是用cout,它能自己调输出格式,不会出现输出错误;    }    return 0;}


阅读全文
0 0
原创粉丝点击