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;
}