1093 Count PAT's (25分)

本文介绍了一种高效算法,用于在给定字符串中查找并计数特定子串'PAT'的出现次数,即使部分字符位置不同也视为独立组合。通过遍历字符串,利用计数变量记录'P'和'T'的数量,结合'PAT'结构特性,实现快速计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 10​5​​ characters containing only PA, 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固定,A前面有cnt_p个P,就有p个PA组合,后面有t个T,就有t个AT组合,那么一共就会有p * t 个PAT组合,只需要遍历一次,用cnt_t来计数T的个数,cnt_p来计数P的个数,遇到一个A就把当前的cnt_p、cnt_t的值及其A的下标保存起来,遍历完后,P和T的总数量为cnt_p、cnt_t respectively,每个A前的P数为当时保存的cnt_p的值,A后的T数为cnt_t - 当时保存的cnt_t的值,乘积做累加,对1000000007取模后便是结果。

#include<iostream>

#include<vector>

using namespace std;
struct node
{
    int cnt_p;
    int cnt_t;
    int index_a;
};

int main(){
    vector<node> vec;
    string s;
    cin >> s;
    int cnt_p = 0;
    int cnt_t = 0;
    for(int i = 0; i < s.length(); i++){
        if(s[i] == 'A'){
            node temp;
            temp.cnt_p = cnt_p; 
            temp.cnt_t = cnt_t; 
            temp.index_a = i;
            vec.push_back(temp);
        }
        if(s[i] == 'T'){
            cnt_t++;
        }
        if(s[i] == 'P'){
            cnt_p++;
        }

    }
    int cnt = 0;
    for(int i = 0; i < vec.size(); i++){
        cnt += vec[i].cnt_p * (cnt_t - vec[i].cnt_t);
        cnt = cnt % 1000000007;
    }

    cout << cnt << endl;
    

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值