【codeforces 13 C】【DP + 离散化 + 贪心+滚动数组 】C. Sequence【用最小代价把序列变成非严格递增序列】

传送门:C. Sequence

描述:

C. Sequence
time limit per test
1 second
memory limit per test
64 megabytes
input
standard input
output
standard output

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 by 1 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 if a1 ≤ 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 following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.

Output

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

Examples
input
5
3 2 -1 2 11
output
4
input
5
2 1 1 1 1
output
1

题意:

给你n个数,每次操作都可以使某个数加1或者减1,求至少多少次操作使得这n个数是非递减的。非递减定义:

a1 ≤ a2 ≤ ... ≤ aN

思路:

这题是个大原题

原题是POJ3666 题解见Here

不过这题卡空间,需要滚动数组优化一下,秒过_(:зゝ∠)_

还有一个严格递增的版本:CF 714 E   题解见Here

CF改原题真是不亦乐乎,还是要多做题啊

代码:

#include 
#include 
#include 
#define ll __int64
using  namespace  std;
const int N=5005;
int n,a[N],b[N];
ll dp[2][N];

template void read(T&num) {
    char CH; bool F=false;
    for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar());
    for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar());
    F && (num=-num);
}

void solve(){
  for(int i=1; i<=n; i++){
    ll mn=dp[(i-1)&1][1];
    for(int j=1; j<=n; j++){
      mn=min(mn, dp[(i-1)&1][j]);
      dp[i&1][j]=abs(a[i]-b[j])+mn;
    }
  }
  ll ans=dp[n&1][1];
  for(int i=2; i<=n; i++){
    ans=min(ans, dp[n&1][i]);
  }
  printf("%I64d\n",ans);
}

int  main(){
  #ifndef ONLINE_JUDGE
  freopen("in.txt","r",stdin);
  #endif

  read(n);
  for(int i=1; i<=n; i++){
    read(a[i]);
    b[i]=a[i];
  }
  sort(b+1, b+n+1);
  solve();
  return 0;
}


你可能感兴趣的:(online,judge,Codeforces,------多维杂类DP,------离散化,------贪心)