Mountain Subsequences

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.

Sample Input

4abca

Sample Output

4

Hint

The 4 mountain subsequences are:

aba, aca, bca, abca

Source

2013 The Fourth ACM College Student Programming Competition in Shandong Province 


Ideas from the Internet

#include <iostream>
#include<string.h>
using namespace std;
char str1[110000];
int str2[110000];
int dangqian[110000];
int youbian[110000];
int zuobian[110000];
int mod=2012 ;
int main()
{
    int n;
    while(cin>>n)
    {
        cin>>str1;
        for(int i=0;i<n;i++)
            str2[i]=str1[i]-'a';
        memset (dangqian,0,sizeof(dangqian));
        memset(zuobian,0,sizeof(zuobian));
         memset(youbian,0,sizeof(youbian));
        for(int i=0;i<n;i++)// For the increment up to s[i]
        {
            for(int j=0;j<str2[i];j++) //traverse left and right smaller than s[i], we can accumulate them
            {
                zuobian[i]=(zuobian[i]+dangqian[j])%mod;//Currently refers to what each j has now, this is not final, because it will change with
            }
            dangqian[str2[i]]= (dangqian[str2[i]]+zuobian[i]+1)%mod;//Change the existing ones
        }
       memset(dangqian,0,sizeof(dangqian));
        for(int i=n-1;i>= 0;i--)//Increase up to s[i]
        {
            for(int j=0;j<str2[i];j++)
            {
                youbian[i]=(youbian[i]+dangqian[j]) %mod;
            }
            dangqian[str2[i]]=(dangqian[str2[i]]+youbian[i]+1)%mod;
        }
        int ans=0;
        for(int i=0;i<n;i++)
        {
           ans=(ans+youbian[i]*zuobian[i])%mod;
        }
        cout<<ans%mod<<endl;
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324651389&siteId=291194637