当前位置:   article > 正文

左神算法学习日记——单调栈_单调栈 左神模版

单调栈 左神模版

单调栈,一种可以找到左右边界的数据结构 

  1. //利用单调栈找到一个数的左边最近的比他小的数(左边界)和右边最近的比他小的数(右边界)
  2. int maxhist(vector<int> hist)
  3. {
  4. stack<int> max;
  5. int res = INT_MIN;
  6. for (int i = 0; i < hist.size(); i++)
  7. {
  8. //栈从小到大排列,当当前数比栈顶数小时,则弹出栈顶数,结算当前结点,当前数就是他的右边界,弹出后的栈顶数就是他的左边界
  9. while (!max.empty() && hist[max.top()] >= hist[i])
  10. {
  11. int h = hist[max.top()];
  12. max.pop();
  13. int l = max.size() == 0 ? -1 : max.top();
  14. res = std::max(res, (i - l - 1)*h);
  15. }
  16. max.push(i);
  17. }
  18. //在将数组中所有的数都建立单调栈后,如果数组中还有元素的话说明栈中数的右边界是整个数组的右边界
  19. while (!max.empty())
  20. {
  21. int h = hist[max.top()];
  22. max.pop();
  23. int l = max.size() == 0 ? -1 : max.top();
  24. res = std::max(res, (int)(hist.size() - l - 1)*h);
  25. }
  26. return res;
  27. }
  28. int maxmat(vector<vector<int>> mat)
  29. {
  30. vector<int> hist = mat[0];
  31. int res = maxhist(hist);
  32. //求矩阵中的最大矩阵面积,按行遍历矩阵,转化为矩阵高的数组,利用单调栈求矩阵的面积
  33. for (int i = 1; i < mat.size(); i++)
  34. {
  35. for (int j = 0; j < hist.size(); j++)
  36. hist[j] = mat[i][j] == 0 ? 0 : hist[j] + 1;
  37. res = std::max(res, maxhist(hist));
  38. }
  39. return res;
  40. }
  41. //当环形山峰中有重复元素时,求出其组合数就是相邻且高度相同的可以互相看到的山峰个数
  42. int getteam(int time)
  43. {
  44. return time>1 ? time*(time - 1) / 2 : 0;
  45. }
  46. //一个环形山峰,找出能互相看见彼此的山峰对数
  47. int getneigh(vector<int> arr)
  48. {
  49. int maxindex;
  50. for (int i = 0; i < arr.size(); i++)
  51. {
  52. maxindex = arr[maxindex] < arr[i] ? i : maxindex;//找出最高的山峰
  53. }
  54. int res=0;
  55. stack<pair<int, int>> dull;
  56. dull.push({ arr[maxindex], 1 });//环形山峰,左边界无法确定,从最高山峰开始遍历,保证其他山峰一定有左边界
  57. int index=(maxindex+1)%arr.size();
  58. while (index != maxindex)
  59. {
  60. while (arr[index]>dull.top().first)//当当前山峰比栈顶山峰大时,找到右边界,求出栈顶山峰所在范围内的可以互相看到的山峰对,只找出与小山峰对应的高山峰就可以找出所有可以互相看到的山峰对数
  61. {
  62. pair<int, int> temp = dull.top();
  63. dull.pop();
  64. res += getteam(temp.second) + 2 * temp.second;
  65. }
  66. if (arr[index] == dull.top().first)
  67. dull.top().second++;
  68. else
  69. dull.push({ arr[index], 1 });
  70. index = (index + 1) % arr.size();
  71. }
  72. while (!dull.empty())
  73. {
  74. pair<int, int> temp = dull.top();
  75. dull.pop();
  76. res += getteam(temp.second);
  77. if (!dull.empty())
  78. {
  79. res += temp.second;
  80. if (dull.size() > 1)//栈大于2时,通过当前山峰可以找到两对山峰
  81. res += temp.second;
  82. else//栈小于2时,如果最高峰有两座,则有两对山峰,否则只有一对山峰
  83. res += dull.top().second > 1 ? temp.second:0;
  84. }
  85. }
  86. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/404593
推荐阅读
相关标签
  

闽ICP备14008679号