Codeforces Round #276 (Div. 1)D.Kindergarten DP贪心

本文针对幼儿园孩子分组的问题进行了解析,通过贪心算法思想解决如何将孩子们划分成若干连续区间,使得每个区间内最大最小值之差的总和最大。文章提供了详细的算法思路及C++实现代码。
D. Kindergarten
 
 

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
 
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.

题意:给你n个连续的数,让你划分成连续的区间,每个区间的价值为此区间内最大最小值之差,问你这n个数形成的最大价值是多少

题解:贪心的一个思想就是单调必须在同一区间,知道这个就好做了

        考虑v形倒v形就好了

///1085422276

#include<bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
#define mem(a) memset(a,0,sizeof(a))
#define pb push_back
inline ll read()
{
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')f=-1;ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        x=x*10+ch-'0';ch=getchar();
    }return x*f;
}
//****************************************
const int  N=1000000+50;
#define mod 10000007
#define inf 1000000001
#define maxn 10000

int a[N];
ll dp[N];

int main() {
    int n=read();a[1]=0;
    for(int i=1;i<=n;i++) {
        scanf("%d",&a[i]);
    }dp[1]=0;
    for(int i=2;i<=n;i++) {
       if(a[i]>=a[i-1]&&a[i-1]>=a[i-2]) dp[i]=dp[i-1]+a[i]-a[i-1];
       else if(a[i]<=a[i-1]&&a[i-1]<=a[i-2]) dp[i]=dp[i-1]+a[i-1]-a[i];
       else if(a[i]>=a[i-1]&&a[i-1]<=a[i-2]) dp[i]=max(dp[i-2]+a[i]-a[i-1],dp[i-1]);
       else if(a[i]<=a[i-1]&&a[i-1]>=a[i-2]) dp[i]=max(dp[i-2]+a[i-1]-a[i],dp[i-1]);
    }
    cout<<dp[n]<<endl;

    return 0;
}
代码

 

转载于:https://www.cnblogs.com/zxhl/p/4965120.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值