PAT A1101 Quick Sort 快速排序【递推】

There is a classical process named partition in the famous quick sort algorithm. In this process we typically choose one element as the pivot. Then the elements less than the pivot are moved to its left and those larger than the pivot to its right. Given N distinct positive integers after a run of partition, could you tell how many elements could be the selected pivot for this partition?

For example, given N=5 and the numbers 1, 3, 2, 4, and 5. We have:

  • 1 could be the pivot since there is no element to its left and all the elements to its right are larger than it;
  • 3 must not be the pivot since although all the elements to its left are smaller, the number 2 to its right is less than it as well;
  • 2 must not be the pivot since although all the elements to its right are larger, the number 3 to its left is larger than it as well;
  • and for the similar reason, 4 and 5 could also be the pivot.

Hence in total there are 3 pivot candidates.

在快速排序算法中有一个经典的过程叫做分区,在这个过程中我们一般会选择一个元素为主元,比主元元素小的元素都会移动到它左边,主元元素右边都是比它大的元素。给出一次分区后的N个不同的正整数,你能告诉我们这个分区有多少个元素可以作为主元吗

举个例子。给出N=5并且数字为1,3,2,4,5

1可以作为主元因为它左边没有元素并且右边的元素都比1大

3不可以作为主元因为尽管它左边的元素都比3小,但是在右边的2也比3小

2不可以作为主元,因为左边有3

4和5可以作为主元

所以一共有3个可以作为主元

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10​^5​​). Then the next line contains N distinct positive integers no larger than 10​^9​​. The numbers in a line are separated by spaces.

每一个测试样例第一行给出正整数N(≤10^5),下一行给出N个不同的正整数,都不超过10^9

Output Specification:

For each test case, output in the first line the number of pivot candidates. Then in the next line print these candidates in increasing order. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.

每一个测试样例,第一行输出主元元素个数,下一行输出这些元素,按递增顺序。两个相邻元素之间用一个空格隔开,每一行的最后没有多余空格。

#include<cstdio>
#include<algorithm>
using namespace std;
const int MAXN=100010;
const int INF=0x3fffffff;
//a为序列,leftMax和rightMin分别为每一位左边最大的数和右边最小的数 
int a[MAXN],leftMax[MAXN],rightMin[MAXN];
//ans记录所有主元,num为主元个数
int ans[MAXN],num=0;
int main(){
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%d",&a[i]);
	}
	leftMax[0]=0;
	for(int i=1;i<n;i++){
		leftMax[i]=max(leftMax[i-1],a[i-1]);
	}
	rightMin[n-1]=INF;
	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;
} 

猜你喜欢

转载自blog.csdn.net/qq_38179583/article/details/86679325
今日推荐