POJ-2796-FeelGood
题目描述:
Bill is developing a new mathematical theory for human emotions. His recent investigations are dedicated to studying how good or bad days influent people’s memories about some period of life.
A new idea Bill has recently developed assigns a non-negative integer value to each day of human life.
Bill calls this value the emotional value of the day. The greater the emotional value is, the better the daywas. Bill suggests that the value of some period of human life is proportional to the sum of the emotional values of the days in the given period, multiplied by the smallest emotional value of the day in it. This schema reflects that good on average period can be greatly spoiled by one very bad day.
Now Bill is planning to investigate his own life and find the period of his life that had the greatest value. Help him to do so.
输入:
The first line of the input contains n - the number of days of Bill’s life he is planning to investigate(1 <= n <= 100 000). The rest of the file contains n integer numbers a1, a2, … an ranging from 0 to 106 - the emotional values of the days. Numbers are separated by spaces and/or line breaks.
输出:
Print the greatest value of some period of Bill’s life in the first line. And on the second line print two numbers l and r such that the period from l-th to r-th day of Bill’s life(inclusive) has the greatest possible value. If there are multiple periods with the greatest possible value,then print any one of them.
输入示例:
1 | 6 |
输出示例:
1 | 60 |
题目大意:
给定一串数字,求一区间,使得区间内的每个数之和乘以区间内最小值最大,并求出区间范围。
思路:
初次看,只能暴力枚举每一个区间,复杂度为O(n2)。
然后我们思考对于每个数,如果把它当做最小数,我们看他能向左右延伸到的最长区间范围,然后在这些区间内选一个符合条件最大的即可。
这就将问题转化为求每一个数左/右边尽可能远的大于等于该数的数的位置,进一步转化为求每个数的左右边遇到的第一个小于该数的位置,再往延伸的反方向退一格。这明显是单调栈问题。所以可以将复杂度降到O(n)。
Solution:
1 | /* |
这里由于是单调递增栈,所以在循环最后给他压进一个最小值,让栈内元素都弹出,做到代码简化。