【CodeForces - 789C】Functions again(最大子段和变形,dp,思维)
題干:
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function?f, which is defined as follows:
In the above formula,?1?≤?l?<?r?≤?n?must hold, where?n?is the size of the Main Uzhlyandian Array?a, and?|x|?means absolute value of?x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of?f?among all possible values of?l?and?r?for the given array?a.
Input
The first line contains single integer?n?(2?≤?n?≤?105)?— the size of the array?a.
The second line contains?n?integers?a1,?a2,?...,?an?(-109?≤?ai?≤?109)?— the array elements.
Output
Print the only integer?— the maximum value of?f.
Examples
Input
5 1 4 2 3 1Output
3Input
4 1 5 4 7Output
6Note
In the first sample case, the optimal value of?f?is reached on intervals?[1,?2]?and?[2,?5].
In the second case maximal value of?f?is reachable only on the whole array.
題目大意:
第一行包含一個整數?n?(2?≤?n?≤?105)?— 表示數組?a的大小。
第二行包含?n?個整數?a1,?a2,?...,?an?(-109?≤?ai?≤?109)?— 表示數組。
讓你找一段連續區間[l,r],使得a[l]-a[l+1]+a[l+2]-a[l+3]....a[r]最大。
解題報告:
直接dp。分以奇數為結尾和偶數為結尾兩種情況分別討論一下即可,其實這題不用set,因為只需要最大值和最小值,所以可以直接維護前綴最大值最小值即可。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<stack> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; int n; ll a[MAX],b[MAX],sum[MAX],ans=-1e18; set<ll> ss[2]; int main() {cin>>n;for(int i = 1; i<=n; i++) scanf("%lld",a+i);for(int i = 1; i<n; i++) {b[i] = abs(a[i]-a[i+1]);if(i%2 == 0) b[i] = -b[i];sum[i] = sum[i-1] + b[i];ans=max(ans,abs(b[i]));}ss[0].insert(0);ss[1].insert(0);for(int i = 1; i<n; i++) {if(i%2==0) {//還是得分情況,,,不知道自己在寫什么if(ss[i%2].size()) ans = max(ans,sum[i] - *ss[(i%2)].begin());if(ss[!(i%2)].size()) ans = max(ans,-sum[i] + *ss[!(i%2)].rbegin()); }else {if(ss[i%2].size()) ans = max(ans,-sum[i] + *ss[(i%2)].rbegin());if(ss[!(i%2)].size()) ans = max(ans,sum[i] - *ss[!(i%2)].begin());} ss[i%2].insert(sum[i]);}cout << ans << endl;return 0 ; }?
總結
以上是生活随笔為你收集整理的【CodeForces - 789C】Functions again(最大子段和变形,dp,思维)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 拜登当选对黄金有什么影响?未来会继续上涨
- 下一篇: 办信用卡没接到电话怎么办 办信用卡没有回