Codeforces 13C

来源:互联网 发布:云梦网络建站怎么样 编辑:程序博客网 时间:2024/05/01 01:13

题意:

意思就是给你一个序列,每次可以让其中一个元素加1或者减1,问你最少需要多少步,使得这个序列变成非递减序列。有一个猜想,就是把其中的数字变成这个序列中原有的数字是最少的,具体为什么,我也不清楚。考虑DP,dp[i][j]表示把前i个数变成非降序列,并且第i个数变成原序列中从小到大第j个数所用的最少步数。所以dp[i][j]=min(abs(a[i]-b[j]),dp[i][j-1]).具体看代码。

AC代码:

////  Created by  CQU_CST_WuErli//  Copyright (c) 2015 CQU_CST_WuErli. All rights reserved.//// #include<bits/stdc++.h>#include <iostream>#include <cstring>#include <cstdio>#include <cstdlib>#include <cctype>#include <cmath>#include <string>#include <vector>#include <list>#include <map>#include <queue>#include <stack>#include <set>#include <algorithm>#include <sstream>#define CLR(x) memset(x,0,sizeof(x))#define OFF(x) memset(x,-1,sizeof(x))#define MEM(x,a) memset((x),(a),sizeof(x))#define For_UVa if (kase!=1) cout << endl#define BUG cout << "I am here" << endl#define lookln(x) cout << #x << "=" << x << endl#define SI(a) scanf("%d",&a)#define SII(a,b) scanf("%d%d",&a,&b)#define SIII(a,b,c) scanf("%d%d%d",&a,&b,&c)#define rep(flag,start,end) for(int flag=start;flag<=end;flag++)#define Rep(flag,start,end) for(int flag=start;flag>=end;flag--)#define Lson l,mid,rt<<1#define Rson mid+1,r,rt<<1|1#define Root 1,n,1#define BigInteger bigntemplate <typename T> T gcd(const T& a,const T& b) {return b==0?a:gcd(b,a%b);}const int MAX_L=2005;// For BigIntegerconst int INF_INT=0x3f3f3f3f;const long long INF_LL=0x7fffffff;const int MOD=1e9+7;const double eps=1e-9;const double pi=acos(-1);typedef long long  ll;using namespace std;int n;int a[5005];int b[5005];ll dp[5005];int main(){#ifdef LOCAL    freopen("C:\\Users\\john\\Desktop\\in.txt","r",stdin);//  freopen("C:\\Users\\john\\Desktop\\out.txt","w",stdout);#endif    while (SI(n)==1) {        rep(i,1,n) SI(a[i]);        rep(i,1,n) b[i]=a[i];        sort(b+1,b+1+n);        CLR(dp);        rep(i,1,n) {            rep(j,1,n) {                dp[j]+=abs(a[i]-b[j]);                if (j>1) dp[j]=min(dp[j],dp[j-1]);            }        }         cout << dp[n] << endl;     }    return 0;}
0 0
原创粉丝点击