题意:
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤105). Then the next line contains N distinct positive integers no larger than 109. 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
分析:
pivot:枢轴/中心点。其实pivot应该就是我们所说的快排中的 “哨兵”。快排中,任选一个元素为哨兵,然后对于其他的元素,小于哨兵的移动到哨兵的左边,大于的则挪到右边。
其实在这里,可以对于每一个元素左边和右边分别sort(),然后比较这个元素是否大于左边的最大值并且小于右边的最小值。但是这样做肯定会超时!!!所以必须换种思路。
我们可以先对整个序列sort(),然后把原序列的每一个元素与排序后的新序列进行比较:
1. 设一个变量max=0.
2. 1)比较排序前的元素和排序后元素的位置是否是一样的(快排的哨兵在一次快排后在序列中的位置和序列进行完整排序后是一致的呦~,因为哨兵大于它前的所有元素的最大值,且小于它后边所有元素的最小值!); 2)排序前的元素>max吗?如果 1)、2)都符合,则它可以是哨兵
3. 如果 循环到的 (未排序)序列的元素 > max,max=此元素~
代码:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
int n,max=0,cnt=0;
cin>>n;
vector<int> v1(n),v2(n),v3;//int: -2147483648~2147483647
for(int i=0;i<n;i++){
cin>>v1[i];
v2[i]=v1[i];
}
sort(v2.begin(),v2.end());
for(int i=0;i<n;i++){
if(v1[i]==v2[i]&&v1[i]>max){
cnt++;
v3.push_back(v1[i]);
}
if(v1[i]>max) max=v1[i];
}
printf("%d\n",cnt);
for(int i=0;i<cnt;i++){
if(i>0) printf(" ");
printf("%d",v3[i]);
}
cout<<endl;
return 0;
}
总结:
考点:快速排序,考察对快排的核心内容的理解
逻辑题