1. 程式人生 > 其它 >1093 Count PAT's (25 分)(數學問題)

1093 Count PAT's (25 分)(數學問題)

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

分析:

要想知道構成多少個PAT,那麼遍歷字串後對於每一A,它前面的P的個數和它後面的T的個數的乘積就是能構成的PAT的個數。然後把對於每一個A的結果相加即可辣麼就簡單啦,只需要先遍歷字串數一數有多少個T然後每遇到一個T呢~countt–;每遇到一個P呢,countp++;然後一遇到字母A呢就countt * countp把這個結果累加到result中最後輸出結果就好啦~對了別忘記要對10000000007取餘哦~

為什麼要對1000000007取模?
原文連結:https://blog.csdn.net/liuchuo/article/details/51985909

題解

#include <bits/stdc++.h>

using namespace std;

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif
    string s;
    cin>>s;
    int n=0,cntp=0,cnta=0,cntt=0;
    for(int i=0;i<s.size();i++){
        if(s[i]=='T') cntt++;
    }
    for(int i=0;i<s.size();i++){
        if(s[i]=='P') cntp++;
        if(s[i]=='A'){
			//注意這句的正確寫法
            n=(n+cntp*cntt%1000000007)%1000000007;
        }
        if(s[i]=='T') cntt--;
    }
    cout<<n;
    return 0;
}

本文來自部落格園,作者:勇往直前的力量,轉載請註明原文連結:https://www.cnblogs.com/moonlight1999/p/15758590.html