先上题目:
The Little Elephant loves sortings.
He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 ≤ l ≤ r ≤ n) and increase ai by 1 for all i such thatl ≤ i ≤ r.
Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1 ≤ i < n) ai ≤ ai + 1 holds.
The first line contains a single integer n (1 ≤ n ≤ 105) — the size of array a. The next line contains n integers, separated by single spaces — array a (1 ≤ ai ≤ 109). The array elements are listed in the line in the order of their index's increasing.
In a single line print a single integer — the answer to the problem.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64dspecifier.
3
1 2 3
0
3
3 2 1
2
4
7 4 1 47
6
In the first sample the array is already sorted in the non-decreasing order, so the answer is 0.
In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]).
In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47].
题意:给出一个序列,每次可以将一个区间里面的数都加一,最终使整个序列非递减,问最少的操作数的多少。
一开始想的是单调栈,于是一直想不出可以通过自己的数据的思路。
后来想了一下其实可以扫描序列,记录下已扫描的部分的最大值,然后如果当前位置的值比前一个数小,说明需要加上两者的差值才能保证前方是非递减的,然后就是如果当前值比前一个值大,那么如果当前值比最大值还要大,那么就说明前面的部分统计的次数可以加入ans了,因为后面是和前面分开的,如果当前值比最大值小,那么说明在区间增加的一定次数(比统计值小的次数)就可以达到最大值,当达到最大值以后这个位置后面的序列就不能再和前面的序列一起加一了,但是因为需要统计前面的次数,所以修改次数那里需要减少前方修改多出来的那部分次数。
最后统计一下就可以了。说起来可能有点模糊,详细见代码。
上代码:
1 #include <cstdio> 2 #include <cstring> 3 #define MAX 100002 4 #define ll long long 5 using namespace std; 6 7 ll s[MAX]; 8 9 int main() 10 { 11 int n; 12 ll ans,q,m; 13 //freopen("data.txt","r",stdin); 14 while(scanf("%d",&n)!=EOF){ 15 for(int i=1;i<=n;i++){ 16 scanf("%I64d",&s[i]); 17 } 18 ans=q=0; 19 m=s[1]; 20 for(int i=2;i<=n;i++){ 21 if(s[i-1]>=s[i]){ 22 q+=s[i-1]-s[i]; 23 } 24 else{ 25 if(m<s[i]){ 26 m=s[i]; 27 ans+=q; 28 q=0; 29 }else{ 30 ans+=q-(m-s[i]); 31 q=m-s[i]; 32 } 33 } 34 } 35 ans+=q; 36 printf("%I64d ",ans); 37 } 38 return 0; 39 }