Time Limit: 2 second(s) | Memory Limit: 64 MB |
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 shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3 measured in units where the width of the rectangles is 1.
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
Input starts with an integer T (≤ 20), denoting the number of test cases.
Each case contains a line with an integer N (1 ≤ N ≤ 30000) denoting the number of rectangles. The next line contains N space separated positive integers (≤ 30000) denoting the heights.
Output
For each case, print the case number and the largest rectangle that can be made.
Sample Input |
Output for Sample Input |
2 7 2 1 4 5 1 3 3 5 4 4 3 2 4 |
Case 1: 8 Case 2: 10 |
Note
Dataset is huge; use faster I/O methods.
1 #include<stdio.h> 2 #include<algorithm> 3 #include<iostream> 4 #include<string.h> 5 #include<stdlib.h> 6 #include<queue> 7 #include<stack> 8 using namespace std; 9 typedef long long LL; 10 typedef struct pp 11 { 12 int x; 13 int id; 14 } ss; 15 ss ans[400000]; 16 stack<ss>sta; 17 int main(void) 18 { 19 int i,j,k; 20 int s; 21 int n; 22 scanf("%d",&k); 23 for(s=1; s<=k; s++) 24 { 25 while(!sta.empty()) 26 sta.pop(); 27 scanf("%d",&n); 28 for(i=1; i<=n; i++) 29 { 30 scanf("%d",&ans[i].x); 31 ans[i].id=i; 32 } 33 ans[n+1].x=0; 34 ans[n+1].id=n+1; 35 LL maxx=ans[1].x; 36 sta.push(ans[1]); 37 for(i=2; i<=n+1; i++) 38 { 39 while(!sta.empty()) 40 { 41 ss mm=sta.top(); 42 if(mm.x>ans[i].x) 43 { 44 sta.pop(); 45 LL ak=(LL)mm.x*(LL)(i-mm.id); 46 maxx=max(ak,maxx); 47 ans[i].id=mm.id; 48 } 49 else break; 50 } 51 sta.push(ans[i]); 52 } 53 printf("Case %d: %lld ",s,maxx); 54 } 55 return 0; 56 }