PAT A1101 Quick Sort (25 分)

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.
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.

Output Specification:

Sample Input:

5
1 3 2 4 5

Sample Output:

3
1 4 5

实现思路:

看似是一道快排题,实际只是找快排的枢纽,因为每一轮快排都要通过一个枢纽值来划分排序,一轮排序后至少一个位置数据会固定下来,左边所有数都不大于该固定数,右边则不小于。
采用双数组,一个保存当前数组位置i之前所有数中最大值MAX,一个保存i下标位置之后所有数据中的最小值MIN,只要数组i位置的数大于MAX小于MIN那么就是一个合法的枢纽值,端点值单独考虑即可。

AC代码:

#include <iostream>
#include <vector>
using namespace std;
const int N=100010;
int L[N],R[N];//L数组保存L[i]之前所有数中的最大数 R数组保存R[i]数之后数中的最小数

int main() {
	int n,val,LMAX,RMIN,size;
	cin>>n;
	L[0];//初始化端点
	R[n-1]=(1<<30)-1;//初始化端点
	vector<int> sq,ans;
	while(n--) {
		scanf("%d",&val);
		sq.push_back(val);
	}
	LMAX=sq[0];
	for(int i=1; i<sq.size(); i++) {
		L[i]=LMAX;//在数组下标0~i-1中查找最大值存到L[i]表示L[i]之前的最大值
		if(sq[i]>LMAX) LMAX=sq[i];
	}
	size=sq.size();//vector.size()进行加减时尽量单独保存数值再减 有出错情况
	RMIN=sq[size-1];
	for(int i=size-2; i>=0; i--) {
		R[i]=RMIN;//在数组下标i+1~数组最后一个数中找到最小的值表示R[i]之后的最小值
		if(sq[i]<RMIN) RMIN=sq[i];
	}
	for(int i=0; i<sq.size(); i++) {
		//单独讨论端点情况 中间只要大于左边最大小于右边最小则可以作为快排的枢纽
		if((i==0&&R[i]>sq[i])||(i==size-1&&L[i]<sq[i])||(L[i]<sq[i]&&sq[i]<R[i]))
			ans.push_back(sq[i]);
	}
	cout<<ans.size()<<endl;
	for(int i=0; i<ans.size(); i++) {
		printf("%d",ans[i]);
		if(i<ans.size()-1) printf(" ");
	}
	cout<<endl;
	return 0;
}
上一篇:NW.js 入门教程


下一篇:Qt-类库模块划分详解