http://acm.hdu.edu.cn/showproblem.php?pid=6040
std::nth_element
default (1)
template < class RandomAccessIterator >
void nth_element (RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last);
custom (2)
template < class RandomAccessIterator, class Compare >
void nth_element (RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last, Compare comp);
Sort element in range
Rearranges the elements in the range [first,last), in such a way that the element at the nth position is the element that would be in that position in a sorted sequence.
The other elements are left without any specific order, except that none of the elements preceding nth are greater than it, and none of the elements following it are less.
The elements are compared using operator< for the first version, and comp for the second.
nth_element 大法好,这个复杂度 o(n)
#include<stdio.h>
#include<algorithm>
using namespace std;
const int MAXN = 10000009;
int b[105], pos[105],n, m;
unsigned a[MAXN], ans[105];
unsigned x, y, z;
inline unsigned rng61() {
unsigned t;
x ^= x << 16;
x ^= x >> 5;
x ^= x << 1;
t = x;
x = y;
y = z;
z = t ^ x ^ y;
return z;
}
bool cmp(int X, int Y) {
return b[X] < b[Y];
}
int main()
{
for(int Case = 1; scanf("%d%d%u%u%u", &n, &m, &x, &y, &z) == 5; ++Case) {
for(int i = 0; i < n; ++i) {
a[i] = rng61();
}
for(int i = 0; i < m; ++i) {
scanf("%d", b + i);
pos[i] = i;
}
sort(pos , pos + m, cmp);
b[pos[m] = m] = n;
a[n] = -1;
for(int i = m - 1; i >= 0; --i) {
nth_element(a, a + b[pos[i]], a + b[pos[i + 1]]);
ans[pos[i]] = a[b[pos[i]]];
}
printf("Case #%d:", Case);
for(int i = 0; i < m; ++i) {
printf(" %u", ans[i]);
}
putchar('\n');
}
return 0;
}

本文介绍了一种利用C++标准库中的nth_element函数实现高效选择算法的方法。该算法可以在O(n)的时间复杂度内找到部分排序序列中的指定元素,适用于大数据集的快速查找场景。文章通过一个具体的示例程序展示了如何在实际应用中使用这一技巧。
402

被折叠的 条评论
为什么被折叠?



