Codeforces Round #276 (Div. 1)D(貪心+dp)

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.


題意:給出n個數,要求你把它分成若干個連續的區間,每個區間的權值定義爲該區間最大值與最小值的差值,最後求所有區間的最大權值和

思路:寫這個題解前先吐槽一下自己,自從區域賽回來以後忙各種雜事,好久沒刷題了,就拿這道不怎麼難的題來說,想了好久
      
           最後還是看別人代碼才寫出來也是弱成狗,想每天安安靜靜的做題都不行,生活就是這樣啊,何時才成達成自己的目標履行自己的諾言,好了,槽點吐完,下面是題解

           首先注意到,劃分的區間一定滿足單調性,這是一種貪心思想,然後就是dp了

           dp[i]表示前i個數的最優值

           如果a[i-2]<a[i-1]>a[i]     dp[i]=max(dp[i-2]+a[i-1]-a[i],dp[i-1])
 
           如果a[i-2]>a[i-1]>a[i]     dp[i]=dp[i-1]+a[i-1]-a[i]

           還有其它幾種情況類似~

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const int MAXN = 1000010;
typedef long long ll;
int a[MAXN];
ll dp[MAXN];

int main()
{
    int n,x,y;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    dp[0]=0;
    for(int i=1;i<=n;i++){
       if(i==1){
        dp[1]=0;
        continue;
       }
       if(a[i-1]>=a[i-2]&&a[i-1]>=a[i])dp[i]=max(dp[i-2]+a[i-1]-a[i],dp[i-1]);
       else if(a[i-1]<=a[i-2]&&a[i-1]<=a[i])dp[i]=max(dp[i-2]+a[i]-a[i-1],dp[i-1]);
       else if(a[i-2]<=a[i-1]&&a[i-1]<=a[i])dp[i]=dp[i-1]+a[i]-a[i-1];
       else if(a[i-2]>=a[i-1]&&a[i-1]>=a[i])dp[i]=dp[i-1]+a[i-1]-a[i];
    }
    cout<
發佈了147 篇原創文章 · 獲贊 7 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章