【codeforces 484D】【DP】Kindergarten

阅读: 评论:0

【codeforces 484D】【DP】Kindergarten

【codeforces 484D】【DP】Kindergarten

传送门:


题意:

给定一个包含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 __int64
const 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("%I64dn", 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
5
1 2 3 1 2
output
3
input
3
3 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.



本文发布于:2024-01-27 16:35:02,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/17063445021456.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:codeforces   Kindergarten   DP
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23