chocolates
B. Chocolatestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou 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, 0≤xi≤ai0≤xi≤ai), then for all 1≤j<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 ai≥xiai≥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.InputThe first line contains an integer nn (1≤n≤2⋅1051≤n≤2⋅105), denoting the number of types of chocolate.The next line contains nn integers aiai (1≤ai≤1091≤ai≤109), denoting the number of chocolates of each type.OutputPrint the maximum number of chocolates you can buy.ExamplesinputCopy5
1 2 1 3 6
outputCopy10inputCopy5
3 2 5 4 10
outputCopy20inputCopy4
1 1 1 1
outputCopy1NoteIn 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.
心得:开始读不清楚题目的意思,后来受数组大小坑的的影响。其实只需倒着比较大小,前一个一定要比后一个小,直到它等于零时跳出循环。
代码如下
#include<cstdio>
#include<cstring>
int main() {
long long int n, a[200005];
scanf("%lld", &n);
for (int i = 0; i < n; i++) {
scanf("%lld", &a[i]);
}
long long int ans = a[n - 1];
for (int i = n - 2; i >= 0; i--){
if (a[i] < a[i + 1]) { //比较前后两数的大小并做出调整
ans += a[i];
}
else {
a[i] = a[i + 1] - 1;
ans += a[i];
}
if (a[i] == 0)break;
}
printf("%lld\n", ans);
return 0;
}