CodeForces 13C Sequence

来源:互联网 发布:山东大学知乎 编辑:程序博客网 时间:2024/05/08 20:25

C - Sequence

Crawling in process...Crawling failedTime Limit:1000MS    Memory Limit:65536KB   64bit IO Format:%I64d & %I64u

SubmitStatusPracticeCodeForces 13C

Description

Little Petya likes to play very much. And most of all he likes to play the following game:

He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help.

The sequence a is called non-decreasing ifa1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.

Input

The first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The followingN lines contain one integer each — elements of the sequence. These numbers do not exceed109 by absolute value.

Output

Output one integer — minimum number of steps required to achieve the goal.

Sample Input

Input
53 2 -1 2 11
Output
4
Input
52 1 1 1 1
Output
1

 

///状态转移方程  f[i][j]=min(f[i-1][j]+abs(a[i]-b[j]),f[i][j-1])///f[i][j]表示把前i个数变成递增序列,第i个数变成b[j]的最少步数。///为什么把序列中的数变成原序列中的数能得到最优解,这个猜想还不太明白的说。#include<iostream>#include<cstdlib>#include<stdio.h>#include<math.h>#include<algorithm>using namespace std;long long  f[5005];int a[5005],b[5005];int main(){   int n;   while(scanf("%d",&n)!=EOF)   {       for(int i=0;i<=n;i++)       f[i]=0;       for(int i=1;i<=n;i++)       {           scanf("%d",&a[i]);           b[i]=a[i];       }       sort(b+1,b+1+n);       for(int i=1;i<=n;i++)       for(int j=1;j<=n;j++)       {           f[j]+=abs(a[i]-b[j]);           if(j>1)           f[j]=min(f[j-1],f[j]);       }       cout<<f[n]<<endl;   }}


 

 

 

原创粉丝点击