1596: Jumping Cows
描述
Farmer John's cows would like to jump over the moon, just like the cows in their favorite nursery rhyme. Unfortunately, cows can not jump.
The local witch doctor has mixed up P (1 <= P <= 150,000) potions to aid the cows in their quest to jump. These potions must be administered exactly in the order they were created, though some may be skipped.
Each potion has a 'strength' (1 <= strength <= 500) that enhances the cows' jumping ability. Taking a potion during an odd time step increases the cows' jump; taking a potion during an even time step decreases the jump. Before taking any potions the cows' jumping ability is, of course, 0.
No potion can be taken twice, and once the cow has begun taking potions, one potion must be taken during each time step, starting at time 1. One or more potions may be skipped in each turn.
Determine which potions to take to get the highest jump.
输入
* Line 1: A single integer, P
* Lines 2..P+1: Each line contains a single integer that is the strength of a potion. Line 2 gives the strength of the first potion; line 3 gives the strength of the second potion; and so on.
输出
* Line 1: A single integer that is the maximum possible jump.
样例输入
8
7
2
1
8
4
3
5
6
样例输出
17
题目来源
题目链接:http://tzcoder.cn/acmhome/problemdetail.do?&method=showdetail&id=1596
题目大意:给牛注册跳跃试剂,奇数次注射药剂会增加跳跃能力,偶数次注射会减少跳跃能力,问最后的跳跃能力最大是多少。
要最大的话,在奇数次选择,一串连续的数字递增,最优的应该就是选择这连续的数字里最大的那一个,偶数次相反。
这里要注意,奇数次选了一个数字后,后面的数字都是递减的,那么我们不需要在减去最后一个数字,而偶数有相反
例如
输入:3 3 2 1 输出应该是3
输入:3 1 2 3 输出也应该是3
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
bool f=1;
int n,a[150005],i,s=0;
cin>>n;
for(i=0;i<n;i++)cin>>a[i];
a[n]=0;
//将最后一项的后一项赋值为最小值,这样在奇数次的时候,就会选择最后一项,偶数次不会
for(i=0;i<n;i++)
{
if(f)
{
if(a[i]>a[i+1])
{
s+=a[i];
f=0;
}
}
else
{
if(a[i]<a[i+1])
{
s-=a[i];
f=1;
}
}
}
cout<<s<<endl;
}