题目链接:http://www.patest.cn/contests/pat-a-practise/1101
题面:
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 (<= 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
题目大意:
给定一序列,是快排后的结果,问有几个元素可以作为基准元素,即有几个元素其左边都比他小,右边都比他大。
解题:
数据量为100000,显然n^2是不行的,最高复杂度为N*log(N)。其实,很好想,只要从左到右O(N)记录下到每个元素位置的最大值,从右到左记录到每个元素的最小值,然后再判断某个元素是否大于其左边最大值,小于其右边最小值即可。(上述寻最值过程可以通过下标调整合并处理),最后再排序即可。
坑点:
其实也算不上什么坑点,不存在基准元素的时候,输出需注意。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#define arraysize 100010
using namespace std;
int minn[arraysize],maxn[arraysize],store[arraysize],ans[arraysize];
int main()
{
int n,tmp,mi,ma,cnt=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&tmp);
store[i]=tmp;
}
store[0]=-1;
store[n+1]=1e9+1;
ma=-1;
mi=1e9+1;
for(int i=1;i<=n;i++)
{
maxn[i]=ma,minn[n-i+1]=mi;
if(store[i]>ma)
ma=store[i];
if(store[n-i+1]<mi)
mi=store[n-i+1];
}
for(int i=1;i<=n;i++)
{
if(store[i]>maxn[i]&&store[i]<minn[i])
ans[cnt++]=store[i];
}
sort(ans,ans+cnt);
printf("%d\n",cnt);
if(cnt>0)
printf("%d",ans[0]);
for(int i=1;i<cnt;i++)
printf(" %d",ans[i]);
printf("\n");
return 0;
}