【codeforces 484D】【DP】Kindergarten

来源:互联网 发布:gradle java 版本 编辑:程序博客网 时间:2024/06/06 03:41

传送门:http://codeforces.com/contest/484/problem/D


题意:

给定一个包含n个元素的数组,我们可以把位置连续的数分为一组,每组至少包含一个元素。

每组对答案的贡献是这个组内最大的数和最小的数的差值。

对于单个元素组成的组,差值为0。输出答案的最大值


思路:定义i是峰值点,如果a[i-1]<=a[i]>=a[i+1]或者a[i-1]>=a[i]<=a[i+1],那么每一段中包含的峰值点一定在这一段的端点,否则从峰值点处将区间断开不会使结果变差,这也说明了存在最优解使得每一段是严格单调的,记dp[i]为把前i个数分段的最大得分,考虑i左侧最近的峰值点la,那么只需枚举la属于前一段还是后一段,于是有dp[i]=max(dp[la-1]+labs(a[i]-a[la]),dp[la]+labs(a[i]-a[la+1])),复杂度O(n)


代码:

#include <bits/stdc++.h>using  namespace  std;#define ll __int64const int inf=0x3f3f3f3f;const int N=1e6+10;ll a[N], dp[N];int  main(){    int n;    scanf("%d", &n);    for(int i=1; i<=n; i++)scanf("%I64d", &a[i]);    int la=1;    for(int i=2; i<=n; i++){        dp[i]=max(dp[la-1]+labs(a[i]-a[la]), dp[la]+labs(a[i]-a[la+1]));        if(i<n){            if(a[i-1]<=a[i] && a[i]>=a[i+1])la=i;            if(a[i-1]>=a[i] && a[i]<=a[i+1])la=i;        }    }    printf("%I64d\n", dp[n]);    return 0;}
描述:

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

In a kindergarten, the children are being divided into groups. The teacher put the children in a line and associated each child with his or her integer charisma value. Each child should go to exactly one group. Each group should be a nonempty segment of consecutive children of a line. A group's sociability is the maximum difference of charisma of two children in the group (in particular, if the group consists of one child, its sociability equals a zero).

The teacher wants to divide the children into some number of groups in such way that the total sociability of the groups is maximum. Help him find this value.

Input

The first line contains integer n — the number of children in the line (1 ≤ n ≤ 106).

The second line contains n integers ai — the charisma of the i-th child ( - 109 ≤ ai ≤ 109).

Output

Print the maximum possible total sociability of all groups.

Examples
input
51 2 3 1 2
output
3
input
33 3 3
output
0
Note

In the first test sample one of the possible variants of an division is following: the first three children form a group with sociability 2, and the two remaining children form a group with sociability 1.

In the second test sample any division leads to the same result, the sociability will be equal to 0 in each group.



0 0
原创粉丝点击