POJ2313 Sequence

Sequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 3885 Accepted: 1537

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

Source

POJ Monthly,Minkerui


显然b[i]对于最后最优值产生影响的有三项|a[i]-b[i]|,|b[i]-b[i-1]|,|b[i]-b[i+1]|, 反应在数轴上要使得这三项最小,那么取值应该是这三数居中的那个,则b[i]=mid(b[i - 1], a[i], b[i + 1]),直到没有以上所说的i,所得的b数列即为所求,按公式求sum, 输出。。读者可自行证明。

#include<stdio.h>
#include<string.h>
#include<math.h>
#define INF 0x3fffffff
#include<iostream>
using namespace std;
int mad(int a,int b,int c)
{//取三个数的中间值
    int ma=a,mi=a;
    ma=max(a,b);
    ma=max(ma,c);
    mi=min(a,b);
    mi=min(mi,c);
    return a+b+c-mi-ma;
}
int main()
{
    int a[1000];
    int b[1000];
    int  n;
    int s=0;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
        b[i]=a[i];
    }
    for(int i=1; i<n-1; i++)
    {
        b[i]=mad(b[i-1],a[i],b[i+1]);
    }
    for(int i=0; i<n; i++)
    {
        s+=fabs(a[i]-b[i]);
    }
    for(int i=1; i<n; i++)
        s+=fabs(b[i]-b[i-1]);
    printf("%d\n",s);
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值