Transmission Door
Description
give you n integers, please output the number of the first m large in order from large to small.
Input
each set of test data has two lines, the first row has two number n,m (0<n,m<1000000), the second row contains n each are different, and are in the interval [ -500000,500000] integer.
Output
outputs the number of previous m large for each set of test data in order from large to small.
Sample Input
3-35 92 213-644
Sample Output
213 92 3
1. Use the built-in sort function
#include <iostream> #include <algorithm> #include <cstdio>using namespace Std;int ans[1000001];int Main () { int n,m; while (scanf ("%d%d", &n,&m)! = EOF) { for (int i = 0;i < n;i++) { scanf ("%d", &ans[i]); } Sort (Ans,ans + N); printf ("%d", ans[n-1]); for (int i = n-2;m > 1;m--, i--) { printf ("%d", ans[i]); } printf ("\ n"); }
2. Use the built-in priority queue
#include <iostream> #include <queue> #include <cstdio>using namespace Std;int main () { int n,m; while (~SCANF ("%d%d", &n,&m)) { priority_queue<int>que; BOOL first = true; int tmp; while (n--) { scanf ("%d", &tmp); Que.push (TMP); } while (m--) { first?printf ("%d", Que.top ()):p rintf ("%d", que.top ()); Que.pop (); First = false; } printf ("\ n"); } return 0;}
3. Using internal heap functions
#include <cstdio> #include <algorithm>using namespace std;static int A[1000000];int main () { int i,n,m;< C1/>while (EOF! = scanf ("%d%d", &n,&m)) {for (i=0;i<n;i++) scanf ("%d", &a[i]); Make_heap (a,a+n); printf ("%d", a[0]); for (i=1;i<m;i++) { pop_heap (a,a+n-i+1); printf ("%d", a[0]); } printf ("\ n"); } return 0;}
4, handwritten heap sorting
#include <stdio.h> #include <string.h>const int maxn = 1000005;int Heap[maxn],sz = 0;void push (int x) { int i = sz++; while (i > 0) { int p = (i-1)/2; if (Heap[p] >= x) break ; Heap[i] = heap[p]; i = P; } Heap[i] = x;} int pop () { int ret = heap[0]; int x = Heap[--sz]; int i = 0; while (I*2+1<sz) { int a = I*2+1,b = i*2+2; if (b < sz && heap[b]>heap[a]) a = B; if (Heap[a] <= x) break ; Heap[i] = Heap[a]; i = A; } Heap[i] = x; return ret;} int main () { int n,m,tmp; while (~SCANF ("%d%d", &n,&m)) { sz = 0; memset (heap,0,sizeof (heap)); for (int i = 0;i < n;i++) scanf ("%d", &tmp), push (TMP); for (int i = 1;i < m;i++) printf ("%d", pop ()); printf ("%d\n", Pop ()); } return 0;}
HDU 1425 Sort (heap sort/quick Row)