木板牆
考古學家在人跡罕至的一塊平地上發現了由一堆木板拼成的牆。令人驚奇的是這些木板的寬度都相同!地下的部分都已腐爛,而地上的部分也有高有低,甚至有的地方根本沒有木板,所以考古學家決定帶走木板覆蓋的面積最大的長方形回去研究。 輸入: 首先是整數n(1<=n<=100000),表示木板的塊數。接下來是n個整數h1,...,hn, 其中0<=hi<=1000000000,它們按照從左到右的順序表示木板的高度。每塊木板的寬度都是1。
最後一個0表示程序的結束。 輸出: 其中最大長方形的面積。
測試輸入
3 2000 2000 2000 7 1 2 5 6 1 3 3 0
測試輸出
6000 10
源代碼
#include<iostream>
#include <stack>
#include <algorithm>
using namespace std;
#define MAX 100001
struct Node {
int i; //木板的編號
int pre; //木板的前驅
long long high; //木板的高度
}board[MAX];
stack <struct Node> st;
int main( ) {
long long N, i, Max;
struct Node sum;
while (1)
{
cin >> N;
if( N == 0 ) break;
Max = 0;
while(!st.empty())
st.pop();
for( i = 0; i < N; i++ )
{
cin >> board[i].high;
board[i].i = i;
board[i].pre = 0;
}
for( i = 0; i < N; i++)
{
while( !st.empty( ) && board[i].high < st.top().high )
{
sum = st.top( );
st.pop( );
board[i].pre += sum.pre + 1;
Max = max( Max, sum.high * (long long)( i - sum.i + sum.pre ) );
}
st.push( board[i] );
}
while( !st.empty( ) )
{
sum = st.top( );
st.pop( );
Max = max( Max, sum.high * (long long)( N - sum.i + sum.pre ) );
}
cout << Max << endl;
}
return 0;
}