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=150010;
int a[N],vis[N];
int main()
{
    int n;
    while(scanf("%d",&n))
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        if(a[1]>a[2]) vis[1]=1;
        else vis[1]=-1;
        for(int i=2;i<n;i++)
        {
            if(a[i]>=a[i-1]&&a[i]>=a[i+1]) vis[i]=1;
            else if(a[i]<=a[i-1]&&a[i]<=a[i+1]) vis[i]=-1;
        }
        if(a[n]>a[n-1]) vis[n]=1;
        else vis[n]=0;
        int flag=1,ans=0;
       for(int i=1;i<=n;i++)
        {
            if(vis[i]==flag)
            {
                ans+=flag*a[i];
                flag=-flag;
            }
        }

        printf("%d
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/iwantstrong/p/5943806.html