POJ2313 Sequence

来源:互联网 发布:js bigdecimal 计算 编辑:程序博客网 时间:2024/06/05 12:48
Sequence
Time Limit: 1000MS Memory Limit: 65536KTotal 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

3358

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
原创粉丝点击