Description:
-
Enter n Integers to find the minimum K number. For example, if you enter the 8 numbers, the minimum four digits are, and ,.
-
Input:
-
Each test case contains two rows:
The first row contains two integers, n, and k (1 <= n, k <= 200000), indicating the length of the array.
The second row contains n integers, indicating the n number. The value range of the number in the array is [000].
-
Output:
-
For each test case, the minimum k number is output and printed in ascending order.
-
Sample input:
8 44 5 1 6 2 7 3 8
-
Sample output:
1 2 3 4
Solution:
We passFind the k number in the fast sorting, and all smaller than him are on the left, and all bigger than him are on the right..
void getNumber(int n,int m){ int i; int begin = 0; int end = n-1; int index = patition(begin,end); while(index != m-1){ if(index > m-1){ end = index -1; index = patition(begin,end); }else{ begin = index+1; index = patition(begin,end); } }}
In a fast sorting, the array is output in an ordered manner.
void Qsort(int begin,int end){ if(begin >= end) return ; else{ int middle = patition(begin,end); Qsort(begin,middle-1); Qsort(middle+1,end); }}
The code for quick sort is as follows:
int patition(int begin,int end){ int index,small; small = begin-1; for(index = begin;index < end;index++){ if(gArr[index] < gArr[end]){ small++; if(small != index) swap(index,small); } } small++; swap(small,end); return small;}void swap(int i,int j){ int tmp = gArr[j]; gArr[j] = gArr[i]; gArr[i] = tmp;}
All code:
#include <stdio.h>#include <stdlib.h>#define MAXSIZE 200000int gArr[MAXSIZE]={0};void getNumber(int n,int m);void Qsort(int begin,int end);int patition(int begin,int end);void swap(int i,int j);int main(){ int n,m,i; while(scanf("%d %d",&n,&m)!=EOF && n>=1 && n<=200000){ for(i=0;i<n;i++) scanf("%d",&gArr[i]); getNumber(n,m); Qsort(0,m-1); for(i=0;i<m-1;i++){ printf("%d ",gArr[i]); } printf("%d\n",gArr[m-1]); } return 0;}void Qsort(int begin,int end){ if(begin >= end) return ; else{ int middle = patition(begin,end); Qsort(begin,middle-1); Qsort(middle+1,end); }}void getNumber(int n,int m){ int i; int begin = 0; int end = n-1; int index = patition(begin,end); while(index != m-1){ if(index > m-1){ end = index -1; index = patition(begin,end); }else{ begin = index+1; index = patition(begin,end); } }}int patition(int begin,int end){ int index,small; small = begin-1; for(index = begin;index < end;index++){ if(gArr[index] < gArr[end]){ small++; if(small != index) swap(index,small); } } small++; swap(small,end); return small;}void swap(int i,int j){ int tmp = gArr[j]; gArr[j] = gArr[i]; gArr[i] = tmp;}/************************************************************** Problem: 1371 User: xhalo Language: C Result: Accepted Time:950 ms Memory:1696 kb****************************************************************/