POJ 2181Jumping Cows 动态规划DP

本文介绍了一道经典的动态规划问题——跳跃奶牛。问题要求从一系列数值中选择若干个,按照奇数次选择加、偶数次选择减的原则进行操作,目标是使最终结果最大化。文章通过动态规划的方法给出了最优解,并提供了两种实现方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Jumping Cows
Time Limit:1000MS Memory Limit:65536K
Total Submissions:4477 Accepted:2705

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
题意是给你一系列数,按顺序选择几个,选择的时候,若是第奇数次选择就加这个要选择的数,相反就减去相应的值,求如何选择使得
后的结果最大
DP解决,这是看了DISCUSS后才搞明白的,学习DP已经两个周了,慢慢体会DP思想内涵
opt_odd[i]表示前i个数的选择方式中,选择步数为奇数的最大结果
opt_even[i]表示前i个数的选择方式中,选择步数为偶数的最大结果
#include<stdio.h>
int opt_odd[150001];
int opt_even[150001];
int c[150001];

int max(int a,int b)
{
    return a>b?a:b;
}
int main()
{
    int n,i;
    freopen("input","r",stdin);
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&c[i]);
    }
    for(i=1;i<=n;i++)
    {
            opt_odd[i]=max(opt_odd[i-1],opt_even[i-1]+c[i]);
            opt_even[i]=max(opt_even[i-1],opt_odd[i-1]-c[i]);
    }

    printf("%d",max(opt_even[n],opt_odd[n]));
}
由于在动态规划中,这个opt[]这个值只用一次,所以可以用个变量代替,以便减小空间复杂度,优化后的代码
Memory:944K Time:79MS Language:GCC Result:Accepted

#include<stdio.h>
int opt_odd;//[150001];
int opt_even;//[150001];
int c[150001];

int max(int a,int b)
{
    return a>b?a:b;
}
int main()
{
    int n,i;
    //freopen("input","r",stdin);
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&c[i]);
    }
    for(i=1;i<=n;i++)
    {
            opt_odd=max(opt_odd,opt_even+c[i]);
            opt_even=max(opt_even,opt_odd-c[i]);
    }

    printf("%d",max(opt_even,opt_odd));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值