B. Chocolates

B. Chocolates

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You went to the store, selling n types of chocolates. There are ai chocolates of type i 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 xi chocolates of type i (clearly, 0≤xi≤ai), then for all 1≤j<i at least one of the following must hold:

xj=0 (you bought zero chocolates of type j)
xj<xi (you bought less chocolates of type j than of type i)
For example, the array x=[0,0,1,2,10] satisfies the requirement above (assuming that all ai≥xi), while arrays x=[0,1,0], x=[5,5] and x=[3,2] don’t.

Calculate the maximum number of chocolates you can buy.

Input

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

The next line contains n integers ai (1≤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+6 chocolates.

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

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

解题思路:

		总体思路的话是从后往前进行依次相加到sum,如果前面的大于后面的,前面的等于后面的减一,直到有一个是零,就break。

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
using namespace std;
int main()
{
	long long n;
	while(cin>>n)
	{
		long long a[200030]int sum=0;//设一个变量来储存。
		for(int i=0;i<n;i++)
			cin>>a[i];
		sum=a[n-1];//首先将最后一位数放入sum
		for(int i=n-2;i>=0;i--)
		{
			if(a[i]>=a[i+1])
				a[i]=a[i+1]-1;//一旦有前面的大于后面的数,只需将前面的数变成符合条件的后面的数的减一位。
			if(a[i]==0)
				break;//如果有等于零的数,就说明减到不能再减的,前面的就不用再管了
			sum+=a[i];//存储
		}
		printf("%d\n",sum);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44417851/article/details/88730864
今日推荐