[POJ 3666] Making the Grade
Posted evenbao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[POJ 3666] Making the Grade相关的知识,希望对你有一定的参考价值。
[题目链接]
http://poj.org/problem?id=3666
[算法]
离散化 + dp
[代码]
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; #define MAXN 2010 typedef long long ll; const ll INF = 1e15; int i,n,len; ll a[MAXN],tmp[MAXN]; ll ans; ll dp[MAXN][MAXN]; ll myabs(ll x) { return x < 0 ? -x : x; } inline ll dp1() { int i,j; ll mn = INF,ret = INF; for (i = 1; i <= n; i++) { for (j = 1; j <= len; j++) { dp[i][j] = INF; } } for (i = 1; i <= len; i++) dp[1][i] = myabs(a[1] - tmp[i]); for (i = 2; i <= n; i++) { mn = INF; for (j = 1; j <= len; j++) { mn = min(mn,dp[i-1][j]); dp[i][j] = mn + myabs(a[i] - tmp[j]); } } for (i = 1; i <= len; i++) ret = min(ret,dp[n][i]); return ret; } inline ll dp2() { int i,j; ll mn = INF,ret = INF; for (i = 1; i <= n; i++) { for (j = 1; j <= len; j++) { dp[i][j] = INF; } } for (i = 1; i <= len; i++) dp[1][i] = myabs(a[1] - tmp[i]); for (i = 2; i <= n; i++) { mn = INF; for (j = len; j >= 1; j--) { mn = min(mn,dp[i-1][j]); dp[i][j] = mn + myabs(a[i] - tmp[j]); } } for (i = 1; i <= len; i++) ret = min(ret,dp[n][i]); return ret; } int main() { scanf("%d",&n); for (i = 1; i <= n; i++) { scanf("%lld",&a[i]); tmp[i] = a[i]; } sort(tmp+1,tmp+n+1); len = unique(tmp+1,tmp+n+1) - tmp - 1; ans = min(dp1(),dp2()); printf("%lld ",ans); return 0; }
以上是关于[POJ 3666] Making the Grade的主要内容,如果未能解决你的问题,请参考以下文章