fork(3) download
  1. #include<iostream>
  2. #include<algorithm>
  3. #include<vector>
  4. #include<functional>
  5. #define COL 4
  6. #define ROW 4
  7. #define KTH 3
  8. using namespace std;
  9. struct hpNd{
  10. int value;
  11. int row;
  12. int col;
  13. bool operator<(const hpNd &d) const{
  14. return d.value<value;
  15. }
  16. };
  17.  
  18. void display(vector<struct hpNd> v){
  19. vector<struct hpNd>::iterator itr;
  20. for(itr=v.begin();itr!=v.end();itr++)
  21. cout<<itr->value<<", "<<itr->row<<", "<<itr->col<<endl;
  22. }
  23. int main(){
  24. int arr[4][4] = { {10, 20, 30, 40},
  25. {15, 25, 35, 45},
  26. {25, 29, 37, 48},
  27. {32, 33, 39, 50},
  28. };
  29. vector<struct hpNd> v;
  30. vector<struct hpNd>::iterator itr;
  31. //make_heap(v.begin(),v.end());
  32. struct hpNd temp;
  33. struct hpNd *temp_ptr;
  34. for(int i=0;i<COL;i++){
  35. temp.value=arr[0][i];
  36. temp.row=0;
  37. temp.col=i;
  38. v.push_back(temp);
  39. push_heap(v.begin(),v.end());
  40. //cout<<endl<<"After insreting "<<arr[0][i]<<" heap is"<<endl;
  41. //display(v);
  42. }
  43. int next_row=0,next_col=0;
  44. for(int i=0;i<KTH-1;i++){
  45. pop_heap(v.begin(),v.end());
  46. temp=v.back();
  47. next_col=temp.col;
  48. next_row=temp.row+1;
  49. v.pop_back();
  50. temp.value=arr[next_row][next_col];
  51. if(next_col>=COL || next_row>=ROW) continue;
  52. temp.row=next_row;
  53. temp.col=next_col;
  54. v.push_back(temp);
  55. push_heap(v.begin(),v.end());
  56. cout<<temp.value<<" is placed."<<endl;
  57. display(v);
  58. }
  59. pop_heap(v.begin(),v.end());
  60. temp=v.back();
  61. cout<<KTH<<" smallest is "<<temp.value<<endl;
  62.  
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
15 is placed.
15, 1, 0
20, 0, 1
30, 0, 2
40, 0, 3
25 is placed.
20, 0, 1
25, 2, 0
30, 0, 2
40, 0, 3
3 smallest is 20