Jumping Cows_贪心

Description

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.

Input

* 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.

Output

* Line 1: A single integer that is the maximum possible jump. 

Sample Input

8
7
2
1
8
4
3
5
6

Sample Output

17

【题意】牛想跳上月球,但是他们无法跳跃,巫师发明了n颗药丸,只能使用一次并且按照给出顺序使用,奇数次是增加弹跳高度,偶数次降低,求最大能达到的最大高度。

【思路】求出结果最大的子序列,奇数位置+,偶数位置- 。发现只要找出整个序列的极大值点和极小值点就可,极大值点要+,极小值点要- 。找完后从头到尾扫一遍,根据需要找点(比如当前是奇数位置,那么就要找下一个极大值点;当前是偶数位置,那么就要找下一个极小值点)

参考:http://www.cnblogs.com/naturepengchen/articles/4025344.html

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int N=;
int a[N],vis[N];
int main()
{
int n;
while(scanf("%d",&n))
{
for(int i=;i<=n;i++)
{
scanf("%d",&a[i]);
}
if(a[]>a[]) vis[]=;
else vis[]=-;
for(int i=;i<n;i++)
{
if(a[i]>=a[i-]&&a[i]>=a[i+]) vis[i]=;
else if(a[i]<=a[i-]&&a[i]<=a[i+]) vis[i]=-;
}
if(a[n]>a[n-]) vis[n]=;
else vis[n]=;
int flag=,ans=;
for(int i=;i<=n;i++)
{
if(vis[i]==flag)
{
ans+=flag*a[i];
flag=-flag;
}
} printf("%d\n",ans);
}
return ;
}
上一篇:CodeForces 370C. Mittens


下一篇:【Eclipse+IntelliJ反编译】Eclipse/IntelliJ IDEA反编译查看源码及注释