现在的位置: 首页 > 综合 > 正文

nyoj 贪心(动态规划也可,重点是贪心策略)Jumping Cows

2018年01月14日 ⁄ 综合 ⁄ 共 2073字 ⁄ 字号 评论关闭

7 2 1 8 4 3 5 6  可分成 7 (2 1) 8 (4 ,3) (5 6);  在奇数时间取上升序列中最大的,在偶数时间取下降序列中最小的。不过最后有一点需要注意,当整个序列进行完时,最后肯定是加上一个数,7 (2 1) 8 (4 3) (5 6) 1

给你n个数,找一些数(可以不连续,但顺序不可乱),奇数位置的数+,偶数位置的数-。最后得出的最大结果是?
从前往后搜,交替执行:
(1)找一个比相邻两个数都大的数,+;
(2)找一个比相邻两个数都小的数,-;

Jumping Cows

时间限制:3000 ms  |           内存限制:65535 KB
难度:2
描述
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.

输入
The first line consist only one integer N, indicates N cases follows. In each case, there are two lines:
* 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.

输出
For each case
* Line 1: A single integer that is the maximum possible jump.
样例输入
1
8
7
2
1
8
4
3
5
6
样例输出
           17
           
//7 2 1 8 4 3 5 6  可分成 7 (2 1) 8 (4 ,3) (5 6);  在奇数时间取上升序列中最大的,在偶数时间取下降序列中最小的。不过最后有一点需要注意,当整个序列进行完时,最后肯定是加上一个数,7 (2 1) 8 (4 3) (5 6) 1 
//给你n个数,找一些数(可以不连续,但顺序不可乱),奇数位置的数+,偶数位置的数-。最后得出的最大结果是?
//从前往后搜,交替执行:
//(1)找一个比相邻两个数都大的数,+;
//(2)找一个比相邻两个数都小的数,-;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		int cases=scanner.nextInt();
		while(cases--!=0)
		{
			int number=scanner.nextInt();
			int result[]=new int[number+2];
			for(int i=1;i<=number;i++)
				result[i]=scanner.nextInt();
			int flag=1,sum=0;
			for(int j=1;j<=number;j++)
			{
				if(flag==1)
				{
					if(result[j]>=result[j-1]&&result[j]>=result[j+1])
					{
						sum+=result[j];flag=0;
					}
				}
				else {
					if(result[j]<=result[j-1]&&result[j]<=result[j+1])
					{
						sum-=result[j];flag=1;
					}
				}
			}
			System.out.println(sum);
		}
	}
}
                                                        
                        

抱歉!评论已关闭.