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 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.
For each case please output the number of the mountain subsequences module 2012.
The 4 mountain subsequences are:
aba, aca, bca, abca
1 #include <iostream>
2 #include <sstream>
3 #include <ios>
4 #include <iomanip>
5 #include <functional>
6 #include <algorithm>
7 #include <vector>
8 #include <string>
9 #include <list>
10 #include <queue>
11 #include <deque>
12 #include <stack>
13 #include <set>
14 #include <map>
15 #include <cstdio>
16 #include <cstdlib>
17 #include <cmath>
18 #include <cstring>
19 #include <climits>
20 #include <cctype>
21 using namespace std;
22 #define XINF INT_MAX
23 #define INF 0x3FFFFFFF
24 #define MP(X,Y) make_pair(X,Y)
25 #define PB(X) push_back(X)
26 #define REP(X,N) for(int X=0;X<N;X++)
27 #define REP2(X,L,R) for(int X=L;X<=R;X++)
28 #define DEP(X,R,L) for(int X=R;X>=L;X--)
29 #define CLR(A,X) memset(A,X,sizeof(A))
30 #define IT iterator
31 typedef long long ll;
32 typedef pair<int,int> PII;
33 typedef vector<PII> VII;
34 typedef vector<int> VI;
35 #define MAXN 100010
36 int dp[1010];
37 int a[MAXN];
38 int dp1[MAXN],dp2[MAXN];
39 int main()
40 {
41 ios::sync_with_stdio(false);
42 int n;
43 char s;
44 while(cin>>n){
45 for(int i=0;i<n;i++){
46 cin>>s;
47 a[i]=s-‘a‘;
48 }
49 CLR(dp,0);
50 CLR(dp1,0);
51 for(int i=0;i<n;i++){
52 for(int j=0;j<a[i];j++) dp1[i]+=dp[j];
53 while(dp1[i]>=2012)dp1[i]-=2012;
54 dp[a[i]]+=dp1[i]+1;
55 while(dp[a[i]]>=2012)dp[a[i]]-=2012;
56 }
57 CLR(dp,0);
58 CLR(dp2,0);
59 for(int i=n-1;i>=0;i--){
60 for(int j=0;j<a[i];j++) dp2[i]+=dp[j];
61 while(dp2[i]>=2012)dp2[i]-=2012;
62 dp[a[i]]+=dp2[i]+1;
63 while(dp[a[i]]>=2012)dp[a[i]]-=2012;
64 }
65 int ans=0;
66 for(int i=0;i<n;i++){
67 ans=(ans+dp1[i]*dp2[i])%2012;
68 }
69 cout<<ans<<endl;
70 }
71 return 0;
72 }