partition写了6行是因为ct8_2居然用普通的快速选择算法过不了,这个是随机快速选择算法。
程序代码:
#include <iostream>
#include <cstdlib>
int s[1000001];
int partition(int *a, int len)
{
int i, j = 0;
std::swap(a[0], a[rand() % len]);
for (i = 1; i < len; ++i)
if (a[i] > a[0]) ++j, std::swap(a[i], a[j]);
std::swap(a[0], a[j]);
return j;
}
int quick_select(int *a, int len, int i)
{
int k = partition(a, len);
if (k == i) return a[k];
return k > i ? quick_select(a, k, i)
: quick_select(&a[k + 1], len - k - 1, i - k - 1);
}
int main(void)
{
int i, n, k;
while (scanf("%d%d", &n, &k) == 2)
{
for (i = 0; i < n; ++i)
scanf("%d", &s[i]);
printf("%d\n", quick_select(s, n, k - 1));
}
return 0;
}
Name: "StarWing" Problem ID "ct8_2"
Submit Time: 2009/9/16-15:28
G++: Compile OK
Test 1: Accepted Time = 0 ms
Test 2: Accepted Time = 21 ms
Test 3: Accepted Time = 3188 ms
Test 4: Accepted Time = 3929 ms
--------------------------------
Problem ID ct8_2
Test Result Accepted
Total Time 7138 ms
Total Memory 4032 Kb / 65000 Kb
Code Length 730 Bytes