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 105 characters 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
1 #include<cstdio> 2 #include<iostream> 3 #include<string.h> 4 using namespace std; 5 char str[100001]; 6 int pnum[100001] = {0, 0}, tnum[100001] = {0, 0}; 7 int main(){ 8 long long cntp = 0, cntt = 0, ans = 0; 9 scanf("%s", str); 10 for(int i = 0; str[i] != '\0'; i++){ 11 if(str[i] == 'P') 12 cntp++; 13 else if(str[i] == 'A') 14 pnum[i] = cntp; 15 } 16 for(int i = strlen(str) - 1; i >= 0; i--){ 17 if(str[i] == 'T') 18 cntt++; 19 else if(str[i] == 'A') 20 tnum[i] = cntt; 21 } 22 for(int i = 0; str[i] != '\0'; i++){ 23 if(str[i] == 'A') 24 ans += tnum[i] * pnum[i]; 25 } 26 printf("%lld", ans % 1000000007); 27 cin >> str; 28 return 0; 29 }
总结:
1、方法为,统计每个A左边的P个数和右边的T个数,则这个A能组成的PAT即为P个数乘T个数。为避免n^2复杂度,应设置记录数组,在遍历时记录P数和T数。
2、答案要模1000000007。