博客
关于我
1093 Count PAT‘s (25分) 含DP做法
阅读量:369 次
发布时间:2019-03-05

本文共 1906 字,大约阅读时间需要 6 分钟。

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 10 ^ ​5 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左边的P个数*右边的T,构造两个数组分别存储在字符串i位置左边P的个数和右边T的个数,然后遍历字符串将合理位置的两个数组的数乘起来相加即可,不要忘了最后模1000000007,设字符串长度N ,整个复杂度就是遍历了三遍字符串所以还是O(N)的,不会超时。这种做法比较直接,也比较容易想到

AC代码

#include<iostream>#include<algorithm>#include<vector>using namespace std;#define N 1000000007typedef long long LL;string m;int main(){       LL res=0;    cin >> m;    vector<int> a(m.size(),0);    vector<int> b(m.size(),0);    for(int i=1;i<m.size();i++)        if(m[i-1]=='P')            a[i]=a[i-1]+1;        else            a[i]=a[i-1];    for(int i=m.size()-2;i>=0;i--)        if(m[i+1]=='T')            b[i]=b[i+1]+1;        else            b[i]=b[i+1];    for(int i=0;i<m.size();i++)    {           if(m[i]=='A')            res=(res+a[i]*b[i])%N;    }    printf("%lld",res);    return 0;}

方法二:DP

#include<iostream>#include<algorithm>#include<cstring>using namespace std;#define N 1000000007char s[100010],p[]=" PAT";int f[100010][4];int main(){       cin >> s+1;    int n=strlen(s+1);    f[0][0]=1;    for(int i=1;i<=n;i++)        for(int j=0;j<=3;j++)        {               f[i][j]=f[i-1][j];            if(s[i]==p[j])                f[i][j]=(f[i][j]+f[i-1][j-1])%N;        }    cout << f[n][3];    return 0;}

转载地址:http://azbwz.baihongyu.com/

你可能感兴趣的文章
杭电 2007 平方和与立方和(输入数据的大小顺序并不能默认)
查看>>
十大排序算法之三:插入排序(Python)
查看>>
利用Python实现循环队列
查看>>
利用递归实现二叉树的前中后序遍历(Python)
查看>>
Python刷题输入输出
查看>>
冒泡排序又来啦(C/C++版本)
查看>>
python负数存储
查看>>
求二维数组中最大值的位置
查看>>
python中sort和sorted的区别
查看>>
vue中echart数据动态切换,一看就懂
查看>>
Python3.6爬虫记录
查看>>
搞清楚Spring Cloud架构原理的这4个点,轻松应对面试
查看>>
1月份2月份GitHub上最热门的23个Java开源项目
查看>>
maven安装
查看>>
2020第十五届全国大学生智能汽车竞赛——4X4矩阵键盘+Flash调参系统
查看>>
合并两个有序数组
查看>>
Ubuntu 环境下使用中文输入法
查看>>
小白学习Vue(?)--model选项的使用(自定义组件文本框双向绑定)
查看>>
聊聊我的五一小假期
查看>>
面向对象之异常处理:多路捕获
查看>>