- 快速排序(25)
时间限制
200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CAO, Peng
著名的快速排序算法里有一个经典的划分过程:我们通常采用某种方法取一个元素作为主元,通过交换,把比主元小的元素放到它的左边,比主元大的元素放到它的右边。 给定划分后的N个互不相同的正整数的排列,请问有多少个元素可能是划分前选取的主元?
例如给定N = 5, 排列是1、3、2、4、5。则:
1的左边没有元素,右边的元素都比它大,所以它可能是主元;
尽管3的左边元素都比它小,但是它右边的2它小,所以它不能是主元;
尽管2的右边元素都比它大,但其左边的3比它大,所以它不能是主元;
类似原因,4和5都可能是主元。
因此,有3个元素可能是主元。
输入格式:
输入在第1行中给出一个正整数N(<= 105); 第2行是空格分隔的N个不同的正整数,每个数不超过109。
输出格式:
在第1行中输出有可能是主元的元素个数;在第2行中按递增顺序输出这些元素,其间以1个空格分隔,行末不得有多余空格。
输入样例:
5
1 3 2 4 5
输出样例:
3
1 4 5
有一个用例格式错误,我也不清楚是怎么回事啊。
格式错误的原因是要在最后加一个换行符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <map>
#include <iostream>
using namespace std;
int cmp(const void *a, const void *b){
return *(int*)a - *(int*)b;
}
int main() {
freopen("input.txt", "r", stdin);
int n;
scanf("%d", &n);
int *nums = new int[n];
bool *tags = new bool[n];
for (int i = 0; i < n; i++){
scanf("%d", &nums[i]);
tags[i] = true;
}
int snum = nums[0];
int cc = n;
for (int i = 0; i < n; i++){
if (nums[i]>=snum){
snum = nums[i];
}
else{
tags[i] = false;
cc--;
}
}
snum = nums[n - 1];
for (int i = n-1; i >=0; i--){
if (nums[i] <= snum){
snum = nums[i];
}
else{
tags[i] = false;
cc--;
}
}
int finalnum[100001];
int j = 0;
for (int i = 0; i < n; i++){
if (tags[i] == true){
finalnum[j++]= nums[i];
}
}
cout << j << endl;
qsort(finalnum, 0, j,cmp);
for (int i = 0; i < j; i++){
cout << finalnum[i];
if (i != j - 1){
cout << " ";
}
}
cout<<endl;
}