瑶瑶的第K大 (快排+选择一半快排)

来源:互联网 发布:vba range.offset 数组 编辑:程序博客网 时间:2024/04/29 20:35
瑶瑶的第K大Time Limit: 4000/2000MS (Java/Others)Memory Limit: 256000/128000KB (Java/Others)SubmitStatisticNext ProblemProblem Description一天,萌萌的妹子--瑶瑶(tsyao)很无聊,就来找你玩。可是你们都不知道玩什么。。。尴尬了一阵子,机智的瑶瑶就提议:“这样吧,你说N个整数xi,然后在随意说一个数字k,我能够快速地说出这些数字里面第 k 大的数字。”Input第1行 两个整数N, K以空格隔开;第2行 有N个整数(可出现相同数字,均为随机生成),同样以空格隔开。0 < n ≤ 5*10^6 , 0 < k ≤ n1 ≤ xi ≤ 10^8Output输出第 k 大的数字。Sample Input5 25 4 1 3 1Sample Output4Hint如2,2,1中三个数字中第一大数字为2,第二大数字也为2,第三大数字为1 。SourcetsyaoManagertsyao#include <iostream>#include <algorithm>#include <string>#include <cstdio>#include <cstring>#include <cstdlib>#include <cmath>#include <vector>#include<map>#include<queue>using namespace std;const int maxn=100001;const int base=31700;const int INF=9999999;const int MIN=-INF;int a[5000005];int n, k, ans;int read (){    int x = 0;    char ch = ' ';    while (ch < '0' || ch > '9')        ch = getchar ();    while (ch >= '0' && ch <= '9')        x = x * 10 + ch - '0', ch = getchar ();    return x;}void sort (int l, int r){    int last = l;    swap (a[l], a[(l + r) >> 1]);    for (int i = l + 1; i <= r; ++ i)        if (a[l] < a[i])            swap (a[++ last], a[i]);    swap (a[l], a[last]);    if (last == k)        ans = a[k];    else if (k < last)        sort (l, last - 1);    else        sort (last + 1, r);}int main(){    int m,i,j,t;     while (~scanf ("%d%d", &n, &k))    {        for (int i = 1; i <= n; ++ i)            a[i] = read ();        sort (1, n);        printf ("%d\n", ans);    }    return 0;}

0 0
原创粉丝点击