OJ:Jumping Cows(C++)

描述

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

————————————————————————————————

思路:相当于一个数字序列,按先加后减的顺序挑选一个子序列,使得和最大。用贪心算法,每次加取波峰,减取波谷。需要注意的是,减的最后一个数字必须在倒数第二个内。

Code:

#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<iomanip>
using namespace std;
int main(){
	int n;int sum=0;
	int a[150000];//疑问,如果这里写int a[n],那n的值会被a[n-1]覆盖掉,不知为什么 
	bool flag=true;//判断加还是减 
	(cin>>n).get();	
	for(int i=0;i<n;i++){
		(cin>>a[i]).get();//获取药水序列 
	}
	for(int i=0;i<n;i++){
		if(flag){
		while(i<n&&a[i]<=a[i+1]){
			i++;
		}
		sum = sum+a[i];
		flag = false;
	}
	if(!flag){
		while(i<n&&a[i]>=a[i+1]) i++;
		if(i<(n-1)) {
		sum = sum-a[i];
		}
		flag = true;
	}
	}
	cout<<sum<<endl;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值