2017.3.13E - Largest Rectangle in a Histogram

    xiaoxiao2021-03-25  63

    又是一个time limitated

    很强

    E - Largest Rectangle in a Histogram

    A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles: Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram. Input The input contains several test cases. Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of. You may assume that 1<=n<=100000. Then follow n integers h1,...,hn, where 0<=hi<=1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. A zero follows the input for the last test case. Output For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line. Sample Input 7 2 1 4 5 1 3 3 4 1000 1000 1000 1000 0 Sample Output 8 4000 Hint Huge input, scanf is recommended.

    这个栈用的太妙不愧是大神,瞬间提高时间

    之前也有有想着num直接接替前方的数值,很好用并且解决了我了前高后矮

    #include <iostream> #include<stack> using namespace std; stack<pair<int,int> > s; int main() { int n; while(cin>>n&&n) { long long ans=0,num=0; for(int i=0;i<n;i++) { long long x; cin>>x; num=0;//归零 while(!s.empty()&&s.top().first>=x)//比当前最左方矮 { num+=s.top().second;//继承前方 ans=max(ans,num*s.top().first); s.pop(); } s.push(make_pair(x,num+1)); } num=0;//重新计算余下的,他们的高度肯定一个大于等于前一个,并且相邻所以num直接加加 while(!s.empty()) { num+=s.top().second; ans=max(ans,num*s.top().first); s.pop(); } cout << ans << endl; } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-38643.html

    最新回复(0)