POJ 3666 Making the Grade (DP+离散化)
2015-03-13 09:52
344 查看
题目地址:POJ3666
dp[i][j]表示第i位时,值为j时的最小代价。因为j太大,由于要改变值的话,变到与之最近的值相同是最优的,所以可以离散化,这样,j对应了各个值得下标。复杂度O(n^2)。
代码如下:
dp[i][j]表示第i位时,值为j时的最小代价。因为j太大,由于要改变值的话,变到与之最近的值相同是最优的,所以可以离散化,这样,j对应了各个值得下标。复杂度O(n^2)。
代码如下:
#include <iostream> #include <string.h> #include <math.h> #include <queue> #include <algorithm> #include <stdlib.h> #include <map> #include <set> #include <stdio.h> using namespace std; #define LL long long #define pi acos(-1.0) const int mod=1e9+7; const int INF=1E15; const double eqs=1e-9; const int MAXN=2000+10; LL a[MAXN], dp[MAXN][MAXN], b[MAXN]; LL Abs(LL x) { return x>0?x:-x; } int main() { int n, i, j; LL min1, ans1, ans2; scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%lld",&a[i]); b[i]=a[i]; } sort(a+1,a+n+1); memset(dp,0,sizeof(dp)); for(i=1;i<=n;i++){ min1=INF; for(j=1;j<=n;j++){ min1=min(min1,dp[i-1][j]); dp[i][j]=Abs(a[j]-b[i])+min1; } } ans1=INF; for(i=1;i<=n;i++){ ans1=min(ans1,dp [i]); } memset(dp,0,sizeof(dp)); for(i=1;i<=n;i++){ min1=INF; for(j=n;j>=1;j--){ min1=min(min1,dp[i-1][j]); dp[i][j]=Abs(a[j]-b[i])+min1; } } ans2=INF; for(i=1;i<=n;i++){ ans2=min(ans2,dp [i]); } printf("%lld\n",min(ans1,ans2)); return 0; }
相关文章推荐
- POJ3666 Making the Grade [DP,离散化]
- POJ 3666 Making the Grade dp + 离散化
- poj 3666 Making the Grade(dp离散化)
- 【POJ 3666】Making the Grade(离散化+DP)
- [POJ 3666] Making the Grade (序列DP+离散化)
- POJ 3666 Making the Grade——DP + 离散化
- poj 3666 Making the Grade (离散化+动态规划)
- POJ 3666 Making the Grade 【DP + 离散化 + 贪心 】
- poj 3666 Making the Grade (有序序列,离散化dp)
- [poj 3666] Making the Grade (离散化 线性dp)
- poj 3666 Making the Grade dp 离散化
- poj 3666 Making the Grade(dp离散化)
- POJ 3666 Making the Grade 【DP+离散化】
- POJ 3666-Making the Grade (DP+离散化)
- Making the Grade poj 3666(离散化+滚动数组+dp)
- A-Making the Grade(POJ 3666)
- POJ 3666--Making the Grade(dp)
- POJ 3666 Making the Grade
- poj 3666 Making the Grade(dp)
- POJ 3666 Making the Grade