【PAT】A1093 Count PAT's(高效技巧)

【PAT】A1093 Count PAT’s(高效技巧)

@(PAT)

链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805373582557184

思路:
1. PAT的数量可以巧妙地认为是每个A的左边的P的数量乘以右边T的数量。
2. 用两个数组来记录每个位置左边P的数量和右边T的数量,在记录时,遍历到的位置为P或者T,其下一个位置的数量就为前一个的数量+1,否则和前一个位置的数量相同。
3. 最后遍历每个A,累加结果得到答案。
4. 注意题目中,output the result moded by 1000000007因为测试样例结果过大,需要将结果取模,但是如果是在最后取模,因为在中间过程已经越界,结果还是不对的,导致最后两个测试点过不去。正确的做法应该是在遍历每个A的时候就取模,有效防止越界。

My AC code:

#define _CRT_SECURE_NO_DEPRECATE

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>

#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>

using namespace std;

#define N 100001

char str[N];

int main()
{
    string str;
    cin >> str;
    int len = str.length();
    int res = 0;
    vector<int> p(len);
    vector<int> t(len);
    for (int i = 0; i <= len- 2; i++) {
        if (str[i] == 'P') {
            p[i + 1] = p[i] + 1;
        }
        else {
            p[i + 1] = p[i];
        }
    }
    /*for (int i = 0; i < len; i++) {
        cout << p[i] << endl;
    }*/
    for (int i = len - 1; i >= 1; i--) {
        if (str[i] == 'T') {
            t[i - 1] = t[i] + 1;
        }
        else {
            t[i - 1] = t[i];
        }
    }
    /*for (int i = 0; i < len; i++) {
        cout << t[i] << endl;
    }*/
    for (int i = 0; i < len; i++) {
        if (str[i] == 'A') {
            res = (res+ p[i] * t[i]) % 1000000007;
        }
    }
    printf("%d", res);
}

猜你喜欢

转载自blog.csdn.net/timso1997/article/details/80503929