题目链接:
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.
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).
Print the maximum possible total sociability of all groups.
5
1 2 3 1 2
3
3
3 3 3
0
题意:
把n个数分成一段一段的,每段的值为这段的最大值与最小值之差,现在要分段使值得和最大,最大是多少;
思路:
不会做,看别人说要dp,然后瞎搞了一个dp,然后就过了;
哈哈,真是搞不懂自己怎么写的,反正就是一个上升段的在一起,一个下降段在一起,对于转折点就判断一下把它分到哪个段才能使值得和最大,然后就哈哈哈了;
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <bits/stdc++.h> #include <stack> #include <map> using namespace std; #define For(i,j,n) for(int i=j;i<=n;i++) #define mst(ss,b) memset(ss,b,sizeof(ss)); typedef long long LL; template<class T> void read(T&num) { char CH; bool F=false; for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar()); for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar()); F && (num=-num); } int stk[70], tp; template<class T> inline void print(T p) { if(!p) { puts("0"); return; } while(p) stk[++ tp] = p%10, p/=10; while(tp) putchar(stk[tp--] + '0'); putchar(' '); } const LL mod=1e9+7; const double PI=acos(-1.0); const int inf=1e9; const int N=1e6+20; const int maxn=1e6+220; const double eps=1e-12; int n,a[N]; LL dp[N][2]; int main() { read(n); For(i,1,n)read(a[i]); dp[0][0]=dp[0][1]=0; dp[1][0]=dp[1][1]=0; for(int i=2;i<=n;i++) { if(a[i]>a[i-1]) { dp[i][1]=max(dp[i][1],dp[i-1][1]+a[i]-a[i-1]); dp[i][1]=max(dp[i][1],dp[i-2][0]+a[i]-a[i-1]); } else { dp[i][0]=max(dp[i][0],dp[i-1][0]+a[i-1]-a[i]); dp[i][0]=max(dp[i][0],dp[i-2][1]+a[i-1]-a[i]); } dp[i][0]=max(dp[i][0],dp[i-1][0]); dp[i][1]=max(dp[i][1],dp[i-1][1]); // cout<<i<<" "<<dp[i][0]<<" "<<dp[i][1]<<endl; } cout<<max(dp[n][0],dp[n][1])<<endl; return 0; }