1101 Quick Sort (25 分)思維
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
嗯這題就哪些是主元
主元的定義就是左邊要比這個數來的小 右邊要比這個數來的大於等於 題目給出說是不想等的
所以 左邊比num小 右邊比num大
1. 那麼如果一直比到這個數所在的下標從左往右 最大的應該是這個數
2. 如果一直比到這個數所在的下表從右往左那麼最小的應該是這個數
3. 而且排序完位置也不能發生變化
所以要滿足3個條件
程式碼
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int digit[N];
int pri[N],maxn[N],minn[N];
int main()
{
int n ;
scanf("%d",&n);
for(int i = 0; i < n; i ++)
{
scanf("%d", &digit[i]);
pri[i] = digit[i];
}
sort(pri, pri + n);
maxn[0] = digit[0];
for(int i = 1 ; i < n ; i ++) //就是挑在它的左邊最大的那個是不是自己
maxn[i] = max(maxn[i - 1],digit[i]);
minn[n - 1] = digit[n - 1];
for(int i = n - 2 ; i >= 0; i --) //就是挑在它的右邊最小的是不是自己
minn[i] = min(minn[i + 1], digit[i]);
vector<int>vec;
for(int i = 0 ; i < n; i ++)
{
if(pri[i] == digit[i] && minn[i] == digit[i] && maxn[i] == digit[i])
vec.push_back(digit[i]);
}
sort(vec.begin(),vec.end());
printf("%d\n",vec.size());
if(vec.size() == 0)
printf("\n") ;
else
for(int i = 0 ; i < vec.size(); i ++)
printf("%d%c",vec[i]," \n"[i == vec.size() - 1]);
//滿足 排序完後和自己原本的順序一樣並且 左邊最大的是自己右邊最大的也是自己的話 那就說明了這個就是住院
return 0;
}