Poj 4088: Set operation
Question: (as for 4089, I did that problem and used the idea of merging, so I didn't write it)
Description
Mr. Zhang needs to select the K-small number from a batch of large positive integers. Because the data volume is too large, it is very difficult to select. I hope you can help him with programming.
Input
The first row in the first row is the number of data N (10 <=n <= 106 ), the second is the serial number K (1 <= k <= 105) of the data to be selected. N and K are separated by spaces;
The second row is followed by N data t (1 <= T <= 109), separated by spaces or line breaks.
Output
Decimal number of K (if there is an order of the same size, for example, for 1, 2, 3, 8, 4th small is 8, 5th small is also 8 ).
Sample Input
10 51 3 8 20 2 9 10 12 8 9
Sample output
8
The solution borrow the fast sorting idea to find the K-small element.
Code
#include <iostream>#include <fstream>using namespace std;void main_solution();void read_data( int *& data,int &n,int &k );int min_k(int *data,int s,int e,int k);int main(){main_solution();system("pause");return 0;}void read_data( int *& data,int &n,int &k ){ifstream reader;reader.open( "data.txt" );reader>>n;reader>>k;data = new int[n];for(int i=0;i<n;i++){reader>>data[i];}reader.close();}int min_k(int *data,int s,int e,int k){int t = s;int another = e;while(t != another){if( t < another ){if( data[t] <= data[another] )another --;else {int d = data[another];data[another] = data[t];data[t] = d;d = another;another = t;t = d;}}else{if( data[t] >= data[another] )another ++;else {int d = data[another];data[another] = data[t];data[t] = d;d = another;another = t;t = d;}}}if( k == t-s+1 )return data[t];else if( k < t-s+1 )return min_k(data,s,t-1,k);else return min_k(data,t+1,e,k - (t-s+1));}void main_solution(){int * data;int n;int k;read_data(data,n,k);cout<<min_k(data,0,n-1,k)<<endl;}
Poj 4088: Set operation