题目
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 (≤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,那么前面不可以有比它大的,后面不可以有比它小的
那么放两个数组来记录就行了,一个记之前最大的,一个记之后最小的,也就是前后都要遍历一遍
时间复杂度算是O(n)级别,挺好
要注意的是N可能为0,没有元素给出,这时需要输出的是0,无元素
测试点2是这个东西。我不知道是我理解的问题还是出题的问题
题中给的是N为positive integer,怎么会为0呢?
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n][3],res[n],cnt=0;
for(int i=0;i<n;i++)
{
cin>>arr[i][0];
arr[i][1] = arr[i][0];
if(i>0 && arr[i-1][1] > arr[i][1])
arr[i][1] = arr[i-1][1];
}
for(int i=n-1;i>=0;i--)
{
arr[i][2] = arr[i][0];
if(i<n-1 && arr[i+1][2] < arr[i][2])
arr[i][2] = arr[i+1][2];
}
for(int i=0;i<n;i++)
{
if(arr[i][0] >= arr[i][1] && arr[i][0] <= arr[i][2])
{
res[cnt++] = arr[i][0];
}
}
cout<<cnt<<endl;
if(cnt)
cout<<res[0];
for(int i=1;i<cnt;i++)
{
cout<<" "<<res[i];
}
cout<<endl;
}