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 (≤10^5 ). Then the next line contains N distinct positive integers no larger than 10^9 . 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
题目大意:
在一组数中,若比一个数小的都在该数的左边,比它大的都在右边,则这个数称为主元。
给定一组数,要求输出可能的主元
算法分析:
原解法:扫描一个数左边的数,看有没有比它大的;再扫描其右边,看有没有比它小的,部分测试点未通过,不知道为啥
代码(16分):
#include<bits/stdc++.h>
using namespace std;
string character[100010];
int num;
int ispivot(int index){
for(int i=0;i<=index-1;i++){
if(character[i]>=character[index])
return 0;
}
for(int i=index+1;i<num;i++){
if(character[i]<=character[index])
return 0;
}
return 1;
}
int main()
{
cin>>num;
getchar();
vector<string> v;
for(int i=0;i<num;i++){
cin>>character[i];
}
for(int i=0;i<num;i++){
if(ispivot(i))
v.push_back(character[i]);
}//注意v可能是空的,不能直接取v[0]
sort(v.begin(),v.end());
printf("%d\n",v.size());
for(int i=0;i<v.size();i++){
if(i!=0)
cout<<" ";
cout<<v[i];
}
if(v.size()==0)//当没有主元时要输出回车,不然第二个测试点通不过
printf("\n");
}
后参考网上的解法,对原序列进行排序,当一个数的位置不变,且左边都是小于它的数时,这个数一定是主元
注意当没有主元时,要输出回车,不然第二个测试点通不过
AC代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num;
cin>>num;
vector<int> a(num),b(num),ans;
for(int i=0;i<num;i++){
scanf("%d",&a[i]);
b[i]=a[i];
}
int max=0;
sort(a.begin(),a.end());
for(int i=0;i<num;i++){
if(a[i]==b[i]&&a[i]>max)
ans.push_back(a[i]);
if(b[i]>max)
max=b[i];
}
printf("%d\n",ans.size());
for(int i=0;i<ans.size();i++){
if(i!=0)
printf(" ");
printf("%d",ans[i]);
}
if(ans.size()==0)//当没有主元时,要输出回车
printf("\n");
}