fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. /*Helper array for my method*/
  5. int maxval[100];
  6.  
  7. /*Helper array for dtldarek's method*/
  8. int b[10][10];
  9.  
  10. /*Helper 2-D array for saving output*/
  11. int op[10][10];
  12.  
  13. /*Helper function to print output*/
  14. void print(int n){
  15. for(int i=1;i<=n;i++){
  16. for(int j=1;j<=n;j++){
  17. cout << op[i][j] << " ";
  18. }
  19. cout << endl;
  20. }
  21. }
  22.  
  23.  
  24. void myMethod(int val[], int n){
  25. cout << "My Method:" << endl;
  26.  
  27. for(int i = 1; i<=n; i++)
  28. maxval[i] = val[i];
  29.  
  30. for(int gap = 2; gap<=n; gap++){
  31. for(int i = 1, j = gap; j<=n; i++, j++){
  32. maxval[i] = max(maxval[i],val[j]);
  33. op[i][j] = maxval[i];
  34. }
  35. }
  36. print(n);
  37. cout << endl;
  38. }
  39.  
  40. void dtldarekMethod(int val[], int n){
  41.  
  42. cout << "dtldarek's Method:" << endl;
  43.  
  44. int limit = (int)log2(n);
  45.  
  46. for(int i = 1; i<=n; i++){
  47. for(int j = 1; j<=limit; j++){
  48. b[i][j]=val[i];
  49. int tempLimit = i+(int)pow(2,j)-1;
  50. for(int k = i+1; k<=tempLimit; k++){
  51. b[i][j] = max(b[i][j],val[k]);
  52. }
  53. }
  54. }
  55. for(int x=1;x<=n;x++){
  56. for(int y=x+1;y<=n;y++){
  57. int z = (int)log2(y-x+1);
  58. int ans = max(b[x][z], b[y-(int)pow(2,z)+1][z]);
  59. op[x][y] = ans;
  60. }
  61. }
  62. print(n);
  63. cout << endl;
  64. }
  65.  
  66. int main(){
  67. /*One-based index*/
  68. int val[6] = {0,2,3,7,4,1};
  69. int n = 5;
  70.  
  71. cout << "Original Array:";
  72. for(int i=1;i<=5;i++)
  73. cout << val[i] << " ";
  74.  
  75. cout << endl;
  76.  
  77. myMethod(val,n);
  78. dtldarekMethod(val,n);
  79.  
  80. return 0;
  81. }
  82.  
Success #stdin #stdout 0s 2688KB
stdin
Standard input is empty
stdout
Original Array:2 3 7 4 1 
My Method:
0 3 7 7 7 
0 0 7 7 7 
0 0 0 7 7 
0 0 0 0 4 
0 0 0 0 0 

dtldarek's Method:
0 3 7 7 7 
0 0 7 7 7 
0 0 0 7 7 
0 0 0 0 4 
0 0 0 0 0