【PAT】1093. Count PAT's (25)

来源:互联网 发布:java单例模式添加数据 编辑:程序博客网 时间:2024/05/19 17:27

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

分析:以字母A为核心,计算在这个A左边的字母P的个数以及在这个A的右边的字母T的个数,两者相乘即以这个A为核心可以组建的PAT组合的个数。对每个A进行以上操作,结果相加即可。

#include <iostream>#include <vector>#include <string>using namespace std;struct node{node(int p, int t){numP = p;numT = t;}int numP;//在这个字母A左边的P的个数 int numT;//在这个字母A右边的T的个数 };int main(int argc, char** argv) {string str;cin>>str;int i;vector<node> vecA;int cntP=0, cntA=0, cntT=0;for(i=0; i<str.size(); i++){ if(str[i]== 'P'){ cntP++;}else if(str[i]=='A'){vecA.push_back( node(cntP,0));}}int index = vecA.size()-1;for(i=str.size()-1; i>=0; i--){if(str[i]=='T'){cntT++;}else if(str[i]=='A'){vecA[index--].numT = cntT;}}long long  total = 0, t=1000000007;for(i=0; i<vecA.size(); i++){total = (total+vecA[i].numP*vecA[i].numT)%t;}  printf("%lld\n",total);return 0;}


同样的思路,另一种写法:

#include <iostream>#include <string>#include <vector>using namespace std;int main(int argc, char** argv) {string str;cin>>str;int len = str.size();vector<int> cntP(len);vector<int> cntT(len);int i;if(str[0]=='P'){cntP[0] = 1;}else{cntP[0] = 0;}int tmp;for(i=1; i<len; i++){if(str[i] == 'P'){tmp = 1;}else{tmp = 0;}cntP[i] = cntP[i-1] + tmp;}if(str[len-1]=='T'){cntT[len-1] = 1;}else{cntT[len-1] = 0;}for(i=len-2; i>=0; i--){if(str[i]=='T'){tmp=1;}else{tmp=0;}cntT[i] = cntT[i+1] + tmp;}long total = 0;for(i=1; i<str.size()-1; i++){if(str[i] == 'A'){total += cntP[i-1]*cntT[i+1];total %= 1000000007;}}printf("%ld\n",total);return 0;}


0 0
原创粉丝点击