• 算法初步——其他高效技巧与算法B1040/A1093.有几个PAT


    暴力:

    #include <bits/stdc++.h>
    #include<math.h>
    #include <string>
    using namespace std;
    const int N = 100005;
    long int temp[N];
    int main(){
        char temp[N];
        cin>>temp;
        int len = strlen(temp);
        int result = 0;
        vector<int> res(2);
        for(int i=0;i<len;++i){
            if(temp[i] == 'P'){
                int j = i;
                for(j++;j<len;++j){
                    if(temp[j] == 'A'){
                        int s = j;
                        for(s++;s<len;++s){
                            if(temp[s] == 'T'){
                                result++;
                            }
                        }
                    }
                }
            }
        }
        cout<<result<<endl;
        system("pause");
        return 0;
    } 

    换个角度思考问题:

    对于一个确定位置的A来说,以它形成的PAT的个数等于它左边P的个数乘以它右边T的个数。

    #include <bits/stdc++.h>
    #include<math.h>
    #include <string>
    using namespace std;
    const int MAXN = 100005;
    const int MOD = 1000000007;
    char str[MAXN];
    int leftNumP[MAXN] = {0};
    int main(){
        cin>>str;
        int len = strlen(str);
        for(int i=0;i<len;++i){
            if(i > 0){//如果不是0号位
                leftNumP[i] = leftNumP[i - 1];//继承上一位的结果
            }
            if(str[i] == 'P'){
                leftNumP[i]++;
            }
        }
        //ans为答案,rightNumT记录右边T的个数
        int ans = 0,rightNumT= 0;
        for(int i=len-1;i>=0;--i){
            if(str[i] == 'T'){
                rightNumT++;
            }else if(str[i] =='A'){//当前位为A
                ans = (ans+leftNumP[i] * rightNumT) % MOD;
            }
        }
        cout<<ans<<endl;
        system("pause");
        return 0;
    } 
  • 相关阅读:
    离散型随机变量及其分布列
    建立概率模型
    几何概型习题
    古典概型习题
    含绝对值符号的问题
    临界状态在数学中的应用
    古典概型中的几何体计数
    条件概率
    创建可以滚动的表格
    NoSQL数据库种类
  • 原文地址:https://www.cnblogs.com/JasonPeng1/p/12194079.html
Copyright © 2020-2023  润新知