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

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

在输入的时候就对左边记录最大的值,再从右到左遍历记录右边最小的值,这样就可以快速的确定某个位置的元素能否被当作主元。

#include<bits/stdc++.h>
using namespace std;
int main(){
    int N,num[100005],max=0,min=9999999999;
    vector<int>ans;
    cin>>N;
    int mpl[100005],mpr[100005];
    for(int i=0;i<N;i++){
        scanf("%d",&num[i]);
        if(num[i]>max)  max=num[i];
        mpl[i]=max;
    }
    for(int i=N-1;i>=0;i--){
        if(num[i]<min)  min=num[i];
        mpr[i]=min;
    }
    for(int i=0;i<N;i++){
        int is=1;
        if(mpl[i]>num[i]||mpr[i]<num[i])    is=0;
        if(is) ans.push_back(num[i]);
    }
    sort(ans.begin(),ans.end());
    cout<<ans.size()<<endl;
    if(ans.size()==0)cout<<endl;
    for(int i=0;i<ans.size();i++){
        if(i)   printf(" ");
        printf("%d",ans[i]);
    }
    return 0;
}