B. Chocolates

B. Chocolates

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You went to the store, selling nn types of chocolates. There are aiai chocolates of type ii in stock.

You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy xixi chocolates of type ii (clearly, 0xiai0≤xi≤ai), then for all 1j<i1≤j<i at least one of the following must hold:

  • xj=0xj=0 (you bought zero chocolates of type jj)
  • xj<xixj<xi (you bought less chocolates of type jj than of type ii)

For example, the array x=[0,0,1,2,10]x=[0,0,1,2,10] satisfies the requirement above (assuming that all aixiai≥xi), while arrays x=[0,1,0]x=[0,1,0], x=[5,5]x=[5,5] and x=[3,2]x=[3,2] don't.

Calculate the maximum number of chocolates you can buy.

Input

The first line contains an integer nn (1n21051≤n≤2⋅105), denoting the number of types of chocolate.

The next line contains nn integers aiai (1ai1091≤ai≤109), denoting the number of chocolates of each type.

Output

Print the maximum number of chocolates you can buy.

Examples

input

5
1 2 1 3 6

output

10

input

5
3 2 5 4 10

output

20

input

4
1 1 1 1

output

1

Note

In the first example, it is optimal to buy: 0+0+1+3+60+0+1+3+6 chocolates.

In the second example, it is optimal to buy: 1+2+3+4+101+2+3+4+10 chocolates.

In the third example, it is optimal to buy: 0+0+0+10+0+0+1 chocolates.

题意:假如从后往前看,就是找最后一颗巧克力,然后每次前面的那颗巧克力至少比当前这颗少一,求至少可以取多少颗巧克力。就是从后面往前面贪心过去就行。这里有一个要注意的地方就是数据类型要用long long不用数据会超范围。我就是 这样WA了一发...

#include<iostream>
#include<cstdio>

using namespace std;

long long a[1000005];

int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",a+i);
    int i=n-2;
    long long x=a[n-1]-1,sum=a[n-1];    //直接把最后一颗巧克力加入总和中,记录下一颗巧克力最多能拿多少
    while(i>=0)
    {
        if(x<=0)        //当所取的巧克力小于等于0时,就可以跳出循环了
            break;
        else
        {
            x=min(a[i],x);        //找到当前至少能去多少颗巧克力
            sum+=x;                //加入总和
            x--;                //记录下一次索取的最大值
            i--;
        }
    }
    cout<<sum<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/buhuiflydepig/p/10638778.html