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.
Examples
inpu
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][0] 表示 i 位置是以递增形式,dp[i][1]表示 i 位置是以递减形式。可根据 a[i] 与 a[i - 1] 的大小获得状态转移方程,具体见 (丑陋) 代码
Code:
#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define ull unsigned LL
#define ls i << 1
#define rs (i << 1) + 1
#define fi first
#define se second
#define ptch putchar
#define CLR(a) while(!(a).empty()) a.pop()
using namespace std;
inline LL read() {
LL s = 0,w = 1;
char ch = getchar();
while(!isdigit(ch)) {
if(ch == '-') w = -1;
ch = getchar();
}
while(isdigit(ch))
s = s * 10 + ch - '0',ch = getchar();
return s * w;
}
inline void write(LL x) {
if(x < 0)
putchar('-'), x = -x;
if(x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
const int maxn = 1e6 + 10;
LL a[maxn];
LL dp[maxn][2]; // 0表示递增,1表示递减
int main() {
//#ifndef ONLINE_JUDGE
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
//#endif
int n;
while(~scanf("%d",&n)){
rep(i,1,n + 1) a[i] = read();
dp[1][0] = dp[1][1] = 0;
for(int i = 2;i <= n;++ i){
if(a[i] > a[i - 1]){
dp[i][0] = max(dp[i - 1][0] + a[i] - a[i - 1],dp[i - 1][1]);
dp[i][1] = max(dp[i - 1][1],dp[i - 1][0]);
}
else {
dp[i][1] = max(dp[i - 1][1] + a[i - 1] - a[i],dp[i - 1][0]);
dp[i][0] = max(dp[i - 1][1],dp[i - 1][0]);
}
}
write(max(dp[n][0],dp[n][1])); ptch('\n');
}
return 0;
}