PAT1101 Quick Sort (25)(逻辑)
题意:
快速排序中,我们通常采用某种方法取一个元素作为主元,通过交换,把比主元小的元素放到它的左边,比主元大的元素放到它的右边。 给定划分后的N个互不相同的正整数的排列,请问有多少个元素可能是划分前选取的主元?例如给定N = 5, 排列是1、3、2、4、5。则:
1的左边没有元素,右边的元素都比它大,所以它可能是主元;
尽管3的左边元素都比它小,但是它右边的2它小,所以它不能是主元;
尽管2的右边元素都比它大,但其左边的3比它大,所以它不能是主元;
类似原因,4和5都可能是主元。
因此,有3个元素可能是主元。
给N个数,第一行输出可能是主元的个数,第二行输出这些元素
思路:
这题一看就卡时间,基本思路就是先按顺序排一遍,如果排序后的数的位置与排序前的数的位置相同并且该数大于它之前的数的最大值,则该数为主元。
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<queue>
#include<map>
#include<set>
using namespace std;
const int maxn = 100050;
int n;
int a[maxn],b[maxn];
bool vis[maxn];
int main() {
scanf("%d", &n);
for (int i = 0; i < n;i++) {
scanf("%d", &a[i]);
b[i] = a[i];
}
sort(b, b + n);
vector<int> res;
int max = 0;
for (int i = 0; i < n; i++) {
if (a[i] == b[i]&&a[i]>max) {
res.push_back(a[i]);
}
if (a[i] > max) {
max = a[i];
}
}
printf("%d\n", res.size());
for (int i = 0; i < res.size(); i++) {
if (i != 0) printf(" ");
printf("%d", res[i]);
}
printf("\n");
return 0;
}