[PAT-A 1101]Quick Sort

在这里插入图片描述

题目大意:找出快排过程中的主元(左边全部比这个小,右边全部比这个大)
思路:用数组leftMax记录每一位左边最大的数(不含本位)用数组rightMin记录每一位右边最小的数
即leftMax[i]表示A[0]-A[i-1]中最大的数,rightMin[i]记录A[i+1]-A[n-1]中最小的数
如果A[i]>leftMax[i]&&A[i]<rightMin[i]成立,即比左边最大的大,比右边最小的小,则为要找的数
直接暴力遍历会超时

AC代码:

//1101Quick Sort (25 分)
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100010;
const int INF = 0x3fffffff;
int a[maxn], leftMax[maxn], rightMin[maxn];
int ans[maxn], num = 0;
int main() {
	int n;
	(void)scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		(void)scanf("%d", &a[i]);
	}
	leftMax[0] = 0,rightMin[n - 1] = INF;
	for (int i = 1; i < n; i++) {
		leftMax[i] = max(leftMax[i - 1], a[i - 1]);//leftMax[i-1]存了前i-2个数中最大的数
	}
	for (int i = n - 2; i >= 0; i--) {
		rightMin[i] = min(rightMin[i + 1], a[i + 1]);//
	}
	for (int i = 0; i < n; i++) {
		if (leftMax[i]<a[i] && rightMin[i]>a[i])ans[num++] = a[i];
	}
	printf("%d\n", num);
	for (int i = 0; i < num; i++) {
		printf("%d", ans[i]);
		if (i < num - 1)printf(" ");
	}
	printf("\n");
	return 0;
}

(A1093)同样的思路
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

即统计左边A左边P的个数与右边T的个数,然后相乘
思路:从左边遍历数组,用leftNumP数组记录到当前位置P的个数,
如果A[i]!='P’则leftNumP[i]=leftNumP[i-1],否则leftNumP[i]=leftNumP[i-1]++;
然后再从右边遍历数组,同样的方法统计到A的时候字母T的个数,相乘即为结果

AC代码:

#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 100010;
const int mod = 1000000007;
char str[maxn];
int leftPNum[maxn] = { 0 };
int main() {
	(void)scanf("%s", str);
	int len = strlen(str);
	for (int i = 0; i < len; i++) {
		if (i > 0) {
			leftPNum[i] = leftPNum[i - 1];
		}
		if (str[i] == 'P')leftPNum[i]++;
	}
	int ans = 0, rightTNum = 0;
	for (int i = len - 1; i >= 0; i--) {
		if (str[i] == 'T')rightTNum++;
		else if (str[i] == 'A')ans = (ans + leftPNum[i] * rightTNum) % mod;
	}
	printf("%d\n", ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值