寻找前K大数

Problem Description

Input

n和m同时为0时表示输入结束.

Output

Sample Input
3 1 2 5 -1 5 3 1 2 3 4 5 0 0

Sample Output
5 5 4 3

code：

//
//  k_biggest_num.c
//  ACM
//  Find the k biggest number in an array
//
//  Created by Rachel on 14-2-13.
//

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <functional>
#include <utility>
using namespace std;
#define N 100010
#define K 11
typedef int DT;//datatype: DT
DT A[N];
DT kbig[K];
DT partition_r[N],partition_l[N];

void swap(DT* a, DT* b)
{
DT t = *a;
*a = *b;
*b = t;
}

pair<int,int> findKbig(int left, int right, int k)
{
int l = left, r = right, m = (l+r)/2;
DT key = A[m];
while(l<=r)
{
while(A[l]<key) l++;
while(A[r]>key) r--;
if(l<=r)
{
swap(&A[l],&A[r]); l++; r--;
}
}
/*
for(int i = left; i<=right; i++)
cout<<A[i]<<" ";
cout<<endl;
*/

int n = right-l+1; //#elements > key
pair<int, int> lr = make_pair(l,right);
if(right-left+1==k)
{
lr.first = left;
return lr;
}
else if(n==k)
return lr;
else if(n>k)
return findKbig(l,right,k);
else
{
lr.first = findKbig(left,l-1,k-n).first;
return lr;
}
}

int main()
{
int i,n,k;
while (true) {
cin>>n>>k;

if (n==0 && k==0) {
break;
}
k = k>n?n:k;
for (i=0; i<n; i++) {
cin>>A[i];
}
pair<int,int> P = findKbig(0,n-1,k);
int l = P.first, r = P.second;
DT res[K];
memset(res,0,sizeof(res));
for(i = l; i<=r ; i++)
res[i-l] = A[i];
sort(res, res+K,greater<int>());
for (i = 0; i<k-1; i++) {
cout<<res[i]<<" ";
}
cout<<res[i]<<endl;
}
return 0;
}


some typical testing samples：

6 3

2 4 6 9 1 2

10 3

2 3 4 1 53 23 52 32 32 32

4 2

24 34 24 24

5 6

1 2 3 4 5

5 3

5 3 1 4 2

5 3

1 2 1 1 1

5 3

1 2 3 4 5

10 4

2 5 3 6 2 7 8 7 4 3

---------------------------------------------------

T(N) = T(N/2) + N

= T(N/4) + N + N/2

= ...

= T(1) + N + N/2 + N/4 + ...

∴T(N) = N + N/2 + N/4 + ... = 2N

//
//  k_biggest_num.c
//  ACM
//  Find the k biggest number in an array
//
//  Created by Rachel on 14-2-16.
//

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <functional>
#include <utility>
using namespace std;
#define N 100010
#define K 12
typedef int DT;//datatype: DT
DT kbig[K];//minheap

inline void swap(DT* a, DT* b)
{
DT t = *a;
*a = *b;
*b = t;
}

{
int left = idx*2+1;
int right = idx*2+2;
int pos; // the position of smaller child
if(left>k-1) return;
else if(right>k-1) pos = left;
else pos = kbig[left]<kbig[right]?left:right;

if(kbig[pos]<kbig[idx])
{
swap(&kbig[pos],&kbig[idx]);
}
}

void BuildHeap(int k)
{
int nonleaf_idx = (k-2)/2;
for (int i = nonleaf_idx; i>=0; i--)
}

int main()
{
int i,n,k,tmp;
while (scanf("%d%d",&n,&k)!=EOF) {

if (n==0 && k==0)
break;

k = k>n?n:k;
for (i=0; i<k; i++)
scanf("%d",&kbig[i]);
BuildHeap(k);
for (i=k; i<n; i++)
{
scanf("%d",&tmp);
if(tmp>kbig[0])
{
kbig[0] = tmp;
}
}
sort(kbig,kbig+k,greater<int>());
for (i = 0; i<k-1; i++)
printf("%d ",kbig[i]);
cout<<kbig[i]<<endl;
}
return 0;
}