1101 Quick Sort (排序)

1101 Quick Sort (25 分)

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

解题思路:

原思路:

本题涉及快速排序,题面的要求是统计并且找出给定序列中的主元(排序前元素的位置与排序后元素的位置一致),本题原始解题方法是遍历序列并记录访问元素左边的最大值,若左边的最大值小于访问元素,则将其收入set,再次逆序遍历序列并记录元素右边的最小值,若右边的最小值小于访问元素,则将访问元素从set中擦除(但是只通过了两个测试,大批量的测试点不能通过......,沉思了很长时间,发现若set中不存在该元素,怎么能擦除(erase)),然后加上erase前的find判断测试点全部通过.
注意:在erase之前一定要判断是否待erase的元素是否存在,在pop之前一定要判断队列堆栈中是否为空

博客思路浮现:

查看了柳婼的解题思路,发现有可取之处,先将将原序列存在两个数组中(设定数组a和数组b),对数组a进行排序,然后对数组b进行遍历,并且存下访问元素左边最大值max,若max的值小于访问元素,则将访问元素收入输出结果中,同层再更新max为访问元素左边(包括访问元素)最大值。

原解题思路代码:
#include 
#include 
#include 
using namespace std;
vector v;
int main(){
    int n;
    cin>>n;
    v.resize(n);
    set ans;
    int maxnum=-1;
    int cnt=0;
    for(int i=0;i>v[i];
        if(maxnum=0;i--){
        if(minnum>v[i]){
            minnum=v[i];
        }else if(ans.find(v[i])!=ans.end()){
            ans.erase(v[i]);
            cnt--;
        }
    }
    cout<
博客浮现代码:
#include 
#include 
using namespace std;
int a[100000],b[100000];
int main(){
    int n;
    cin>>n;
    for(int i=0;i>a[i];
        b[i]=a[i];
    }
    sort(a,a+n);
    int cnt=0,max=0;
    int ans[100000];
    for(int i=0;i

你可能感兴趣的:(1101 Quick Sort (排序))