Basic Level 1045 Quick Sort (20 points)

topic

There is a classic division process in the well-known quick sort algorithm: we usually adopt a certain method to take an element as the pivot, and through exchange, put the element smaller than the pivot to its left, and the element larger than the pivot to the To its right. Given the arrangement of N different positive integers after division, how many elements may be the pivot selected before division?

For example, given N = 5 N = 5N=5 , the arrangement is 1 , 3 , 2 , 4 , 5 . then:

1 left no elements, the elements on the right than it is large, so it could be PCA;
although left element 3 than it is small, but its right than two hours it, so it can not be a principal component;
although 2 The elements on the right are larger than it, but the 3 on the left is larger than it, so it cannot be a pivot; for
similar reasons, both 4 and 5 may be pivots.
Therefore, 3 elements may be pivots.

Input format:

Enter a positive integer N (≤ 1 0 5) N (≤ 10^5) in the first lineN105 ); The second line is N different positive integers separated by spaces, each number does not exceed1 0 9 10^9109
​​ 。

Output format:

In the first line, output the number of elements that may be the pivot; in the second line, output these elements in increasing order, separated by a space, and there must be no extra spaces at the beginning and end of the line.

Input sample:

5
1 3 2 4 5

Sample output:

3
1 4 5

Code:

#include <iostream>
#include <algorithm>

using namespace std;

const int MAXN = 100010;
int q_1[MAXN], q_2[MAXN], n, a[MAXN], k = 0, Max = 0;

int main(){
    
    
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
    
    
        scanf("%d", &q_1[i]);
        q_2[i] = q_1[i];
    }
    sort(q_1, q_1 + n);
    for(int i = 0; i < n; i++){
    
    
        if(q_1[i] == q_2[i] && q_2[i] > Max) a[k++] = q_2[i];
        if(q_2[i] > Max) Max = q_2[i];
    }
    printf("%d\n", k);
    for(int i = 0; i < k; i++) printf("%s%d", i ? " " : "", a[i]);
    printf("\n");
    return 0;
}

PAT_BasicLevel

Guess you like

Origin blog.csdn.net/zy440458/article/details/113805797