PAT A1101 Quick Sort

分析快速排序中主元的选择条件,给出一个正整数序列,找出可能作为主元的元素数量及其值。示例输入:5,1 3 2 4 5,输出:3,1 4 5。易错点包括内存管理、比较操作、数组大小及变量声明顺序等。
摘要由CSDN通过智能技术生成

1101. Quick Sort (25)-PAT甲级真题

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

题目大意:

快速排序中,我们通常采用某种方法取一个元素作为主元,通过交换,把比主元小的元素放到它的左边,比主元大的元素放到它的右边。 给定划分后的N个互不相同的正整数的排列,请问有多少个元素可能是划分前选取的主元?例如给定N = 5, 排列是1、3、2、4、5。则:
1的左边没有元素,右边的元素都比它大,所以它可能是主元;
尽管3的左边元素都比它小,但是它右边的2它小,所以它不能是主元;
尽管2的右边元素都比它大,但其左边的3比它大,所以它不能是主元;
类似原因,4和5都可能是主元。
因此,有3个元素可能是主元。
给N个数,第一行输出可能是主元的个数,第二行输出这些元素

分析:

对原序列sort排序,逐个比较,当当前元素没有变化并且它左边的所有值的最大值都比它小的时候就可以认为它一定是主元。

易错点:

1.输出时候v[0]是非法内存。
2.“=”和“==”容易搞错。
3.数组要开的够大,不然无法过某些测试点。
4.声明变量的顺序要注意(在main函数下面第二三行的位置被坑了十分钟)。

代码片段:

#include<bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <vector>
int v[100000];
using namespace std;

int main(){
	int n,max=0,cnt=0;
	scanf("%d",&n);
	vector<int> a(n),b(n);
	for(int i = 0;i < n;i++){
		scanf("%d",&a[i]);
		b[i]=a[i];
	}
	sort(a.begin(),a.end());
	for(int i = 0;i < n;i++){
		if(a[i] == b[i]&&b[i]>max) //若原序列按从小到大排布 
		v[cnt++]=b[i];
		if(b[i]>max) //若当前数字比max里面存的数字更大 
		max = b[i]; 
	}
	printf("%d\n",cnt); //输出主元个数 
	for(int i = 0;i < cnt;i++){
		if(i != 0) printf(" ");
		printf("%d",v[i]);
	}
	printf("\n");
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值