Kindergarten - CodeForces 484 D dp

探讨如何将一排孩子按其魅力值最优地分为连续的几组,以使各组的社会性之和达到最大。通过动态规划求解每组的最大社会性差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Sample test(s)
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.


题意:把序列分成连续的若干组,每组的权值是最大值和最小值的差,问所有组的权值和的最大值。

思路:首先每组肯定是取两边的数进行计算,因为多余的没有用,然后每次记录dp[i]+val[i+1]和dp[i]-val[i+1]表示第i+1个数是加的还是减的,在o(n)的复杂度内每次去这个值的最大值。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
ll num[1000010],ans;
int main()
{
    int T,t,n,m,i,j,k;
    ll ans=0,a=-1e9,b=-1e9,val;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%I64d",&val);
        a=max(a,ans+val);
        b=max(b,ans-val);
        ans=max(ans,a-val);
        ans=max(ans,b+val);
    }
    printf("%I64d\n",ans);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值