C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

ヒストグラムで最大の長方形領域を見つけるためのC++プログラム


これは、ヒストグラムで最大の長方形領域を見つけるためのC++プログラムです

関数getArea()のアルゴリズム:

Begin
   Create an empty stack.
   Initialize the largest_area.
   Do a while loop start from first bar for every bar hist[i], where i = 0 to
      less than n:
   If stack is empty or hist[i] is higher than the bar at top of stack, then
      push ‘i’ to stack.
   Else
      this bar is smaller than the top of stack, then keep removing the
      top of stack while top of the stack is greater. Calculate area of
      rectangle with smallest bar. Element before top in stack is left
      index and i is right index for the top.
   Pop the remaining bars from stack if stack is not empty and calculate
      area with every popped bar as the smallest bar.
End

サンプルコード

#include<iostream>
#include<stack>
using namespace std;
int getArea(int hist[], int n)
{
   stack<int> st;
   int largest_area = 0;
   int top;
   int toparea;
   int i = 0;
   while (i < n)
   {
      if (st.empty() || hist[st.top()] <= hist[i])
      st.push(i++);
      else
      {
         top = st.top();
         st.pop();
         toparea = hist[top] * (st.empty() ? i :
         i - st.top() - 1);
         if (largest_area < toparea)
         largest_area = toparea;
      }
   }
   while (st.empty() == false)
   {
      top = st.top();
      st.pop();
      toparea = hist[top] * (st.empty() ? i :
      i - st.top() - 1);
      if (largest_area < toparea)
      largest_area = toparea;
   }
   return largest_area;
}
int main()
{
   int hist[] = {6,7,4,5,3,2};
   int n = sizeof(hist)/sizeof(hist[0]);
   cout << "Largest area is " << getArea(hist, n);
   return 0;
}

出力

Largest area is 16

  1. C++を使用して楕円の領域を見つけるプログラム

    ここでは、C++を使用して楕円の面積を取得する方法を説明します。楕円にはさまざまな部分があります。これらは以下のようなものです。 キーポイント 説明 センター 楕円の中心。また、2つの焦点を結ぶ線分の中心でもあります。 主軸 楕円の最長直径 nmemb これは要素の数であり、各要素のサイズはサイズです。 バイト。 短軸 楕円の最小直径 コード tを指す線分 フォーカス 図で示されている2つのポイント ロータス直腸 蓮の直腸は、焦点を通り、楕円の主軸に垂直な線です。 楕円の面積はΠ𝜋 ∗𝑎a∗b𝑏 サンプルコード #include <iostre

  2. Pythonのヒストグラムの下で最大の長方形の領域を見つけるプログラム

    ヒストグラムの棒の高さを表す数値のリストがあるとします。バーの下に形成できる最大の長方形の領域を見つける必要があります。 したがって、入力がnums =[3、2、5、7]のような場合 その場合、出力は10になります これを解決するには、次の手順に従います- stk:=スタックで、最初に-1を挿入します 高さの最後に0を挿入 ans:=0 0から高さのサイズまでの範囲のiについては、 heights [i]