【PAT甲级A1101】1101 Quick Sort (25分)(c++)

1101 Quick Sort (25分)

作者:CHEN, Yue
单位:浙江大学
代码长度限制:16 KB
时间限制:200 ms
内存限制:64 MB

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

题意:

快速排序过程中,一般会选择一个元素,将这个元素置为左边元素都小于它,右边元素都大于它的位置。问有哪些元素可能是这个被选的值。

思路:

如果是,那么这个元素一定在升序所对应的位置,所以只要将数列升序,比较它是否在对应位置相等。且保证它是从左到右最大的那个数即可(单单位置对不能确保它是被选的值)。(注意:当没有一个数是被选的数时,即全员乱序,输出元素的那行要输出‘\n’一个空行。)

参考代码:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    int n, maxn = -1;
    scanf("%d", &n);
    vector<int> v(n), temp, candidate;
    for (int i = 0; i < n; i++)scanf("%d", &v[i]);
    temp = v;
    sort(v.begin(), v.end());
    for (int i = 0; i < n; i++) {
        if (v[i] == temp[i] && v[i] > maxn)
            candidate.push_back(v[i]);
        maxn = max(temp[i], maxn);
    }
    printf("%d\n", candidate.size());
    for (int i = 0; i < candidate.size(); i++) {
        if (i != 0)printf(" ");
        printf("%d", candidate[i]);
    }
    printf("\n");
    return 0;
}

如有错误,欢迎指正

上一篇:输入一个数字,通过++或者--将其变为Fiboncci数,最小需要几步???


下一篇:linux c 内核 warning: the frame size of 1040 bytes is larger than 1024 bytes