PAT-ADVANCED-1093-Count PAT's

The string APPAPT contains two PAT's as substrings. The first one is formed by the 2nd, the 4th, and the 6th characters, and the second one is formed by the 3rd, the 4th, and the 6th characters.

Now given any string, you are supposed to tell the number of PAT's contained in the string.

Input Specification:

Each input file contains one test case. For each case, there is only one line giving a string of no more than 105characters containing only P, A, or T.

Output Specification:

For each test case, print in one line the number of PAT's contained in the string. Since the result may be a huge number, you only have to output the result moded by 1000000007.

Sample Input:

APPAPT

Sample Output:

2

核心思想是统计每个字符A的左侧有多少个P,右侧有多少个T..
为了减少遍历次数,我们第一次遍历获得整个串中有多少个T
第二次从左往右遍历串,遇见P则numP++,代表下一个A之前有多少个P,遇见T则numT--,代表下一个A之后还有多少个T..
最后注意一下LL和MOD就可以了..

#include <bits/stdc++.h>
#define LL long long
#define MAXN 100000+50
#define MOD 1000000007
using namespace std;

char str[MAXN];
LL res = 0;
LL numP = 0, numT = 0;
int  main(){
    scanf("%s", str);
    int len = strlen(str);
    for(int i = 0; i < len; ++i){
        if(str[i] == 'T'){
            numT++;
        }
    }
    for(int i = 0; i < len; ++i){
        if(str[i] == 'P'){
            numP++;
        }
        else if(str[i] == 'A'){
            res = (res+numP*numT)%MOD;
        }
        else if(str[i] == 'T'){
            numT--;
        }
    }
    cout << res << endl;
    return 0;
}
CAPOUIS'CODE

 

posted @ 2015-09-08 10:20  CAPOUIS  阅读(137)  评论(0)    收藏  举报