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.

著名的快速排序算法里有一个经典的划分过程:我们通常采用某种方法取一个元素作为主元,通过交换,把比主元小的元素放到它的左边,比主元大的元素放到它的右边。 给定划分后的 N 个互不相同的正整数的排列,请问有多少个元素可能是划分前选取的主元?

例如给定 N = 5, 排列是1、3、2、4、5。则:

  • 1 的左边没有元素,右边的元素都比它大,所以它可能是主元;
  • 尽管 3 的左边元素都比它小,但其右边的 2 比它小,所以它不能是主元;
  • 尽管 2 的右边元素都比它大,但其左边的 3 比它大,所以它不能是主元;
  • 类似原因,4 和 5 都可能是主元。

因此,有 3 个元素可能是主元。

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.

输入在第 1 行中给出一个正整数 N(≤10^​5​​); 第 2 行是空格分隔的 N 个不同的正整数,每个数不超过 10^​9​​。

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.

在第 1 行中输出有可能是主元的元素个数;在第 2 行中按递增顺序输出这些元素,其间以 1 个空格分隔,行首尾不得有多余空格。

Sample Input:

5
1 3 2 4 5

Sample Output:

3
1 4 5

解题思路

  1. 读入待排序序列;
  2. 从左向右遍历找出每个位置左侧的最大值,并记录;
  3. 从右向左遍历找出每个位置右侧的最小值,并记录;
  4. 对比原序列及两个遍历,对应位置相等的即为可能的主元取值,将其记录;
  5. 输出结果并返回零值。

代码

#include<stdio.h>

#define maxn 100010

int seq[maxn];//序列 
int left[maxn];//左侧最大值
int right[maxn];//右侧最小值
int N;
int res[maxn],num;

int main(){
    int i,temp; 
    scanf("%d",&N);
    for(i=0;i<N;i++){
        scanf("%d",&seq[i]);
    }
    temp=-1;
    for(i=0;i<N;i++){
        if(seq[i]>temp){
            temp=seq[i];
        }
        left[i]=temp;
    }
    temp=2000000000;
    for(i=N-1;i>=0;i--){
        if(seq[i]<temp){
            temp=seq[i];
        }
        right[i]=temp;
    }
    for(i=0;i<N;i++){
        if((left[i]==seq[i])&&(right[i]==seq[i])){
            res[num++]=seq[i];
        }
    }
    printf("%d\n",num);
    for(i=0;i<num;i++){
        printf("%d",res[i]);
        if(i<num-1){
            printf(" ");
        }
    }
    printf("\n");
    return 0;
} 

运行结果

PAT-A1101/B1045 Quick Sort/快速排序 题目内容及题解

 

相关文章: