POJ 2313 Sequence (贪心)

Description

Given a sequence with N integers A(1), A(2), ..., A(N), your task is to find out a sequence B(1), B(2), ..., B(N), such that 
V = (|A(1) – B(1)| + |A(2) – B(2)| + ... + |A(N) – B(N)|) + (|B(1) – B(2)| + |B(2) – B(3)| + ... +|B(N-1) – B(N)|)

is minimum.

Input

The first line in the input contains an integer N (1 <= N <= 100). Then follow N lines, the i-th of which contains an integer A(i) (-10000 <= A(i) <= 10000).

Output

The output only contains an integer, which is the minimum value of V.

Sample Input

3
3
5
8

Sample Output

5

分析:
考虑 B的N为1 2 3 4 5 。。。N时,对于每个i 我们如果已知前边的i-1时的最小值,那么这个时候只需要确定|A(i) – B(i)|+|B(i-1) – B(i)|的最小值, A(i)和B(i-1)是从前边已经算出来的。这就是在求一个点B(i)到两点A(i) 和B(i-1)的距离的和的最小值,那么B(i)一定在 他们之间。这里就要确定B(i)。其实 可以发现对于每个i  加上的最小是 就是|A[i]-B[i-1]|,所以 确定的B[i]要使得A[i+1]-B[i]之间的值最小,那么在下一次求i+1时  就可以保证得到的结果最小了。

转载于:https://www.cnblogs.com/AbandonZHANG/archive/2012/07/18/2598410.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值