# 甲级1101. Quick Sort (25)

200 ms

65536 kB

16000 B

Standard

CAO, Peng

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 (<= 105). Then the next line contains N distinct positive integers no larger than 109. The numbers in a line are separated by spaces.

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.

Sample Input:
5
1 3 2 4 5

Sample Output:
3
1 4 5

# 乙级1045. 快速排序(25)

200 ms

65536 kB

8000 B

Standard

CAO, Peng

1的左边没有元素，右边的元素都比它大，所以它可能是主元；

5
1 3 2 4 5


3
1 4 5

#### 注意点：

（1）只使用暴力搜索会超时

（2）如果没有主元，在输出0之后还要输出一个空行，否则会有一个测试点不能通过

（3）虽然题目要求按递增顺序输出，但并不需要再按递增顺序进行一次排序。因为按照主元性质，左侧主元一定比右侧主元小，所以只要按照序列中的顺序输出主元，主元本身就是按照递增顺序排序好的。

#### c++代码：

#include<bits/stdc++.h>
using namespace std;
int main(){
int N;
scanf("%d",&N);
int a[N],leftMax[N]={0},rightMin[N]={0};//定义存储序列的数组，存储相应位置左侧最大值的数组，存储相应位置右侧最小值的数组
rightMin[N-1]=INT_MAX;
for(int i=0;i<N;++i)
scanf("%d",&a[i]);
for(int i=1;i<N;++i)//遍历查找相应位置左侧最大值
leftMax[i]=max(leftMax[i-1],a[i-1]);
for(int i=N-2;i>=0;--i)//遍历查找相应位置右侧最小值
rightMin[i]=min(rightMin[i+1],a[i+1]);
vector<int>result;//存储主元的vector
for(int i=0;i<N;++i)//查找主元
if(a[i]>leftMax[i]&&a[i]<rightMin[i])
result.push_back(a[i]);
printf("%d\n",result.size());
//下面的排序语句可有可无
//    sort(a,a+N,[](const int n1,const int n2){
//        return n1>n2;
//    });
if(result.size()==0)//如果没有这样的主元，输出一个空行
printf("\n");
else
for(int i=0;i<result.size();++i){
if(i>0)
printf(" ");
printf("%d",result[i]);
}
return 0;
}

• 擅长领域：
• 算法