POJ3666 making the grade dp+前缀+离散化
来源:互联网 发布:咸鱼卖家申请淘宝介入 编辑:程序博客网 时间:2024/06/06 14:25
/* 题目描述:给出一个包含n个数的序列a1,a2,...,an,先要把该序列修改成不严格单增的序列,假设修改成 b1,b2,...,bn的花费为 |a1 - b1|+|a2 - b2|+...+|an - bn|,问最小花费是多少? 方法:要做这道题,首先要明白一点,修改后的数一定是原序列中的一个数,为什么?因为修改一个数, 其根本目的是让一个过大或过小的数落到已存在的某个区间[x , y]当中,那么从区间外修改后到区间内, 最节省花费的方法无疑是修改到x或y,即一个已经存在的数,也就是原序列中的数字。 明白了这一点,可以使用dp解决这个问题了,首先将a[i]中所有元素装到b数组中,然后对b数组排序并 去重,那么dp[i][j]含义为修改到第i个元素时以b[j]结尾的最小的花费,这里用j表示第b[j]个元素,是有 离散化的思想在里面的,这么一来,就有了转移方程 dp[i][j] = min(dp[i - 1][k]) + abs(b[j] - a[i]) (k<=j ,也就是说,i个时的结尾的元素>=i - 1 个的结尾的元素) 在转移时,要用到前缀和的思想,在第i次循环时用prefix数组维护min(dp[i][k]),具体见代码*/#pragma warning(disable:4786)#pragma comment(linker, "/STACK:102400000,102400000")#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<stack>#include<queue>#include<map>#include<set>#include<vector>#include<cmath>#include<string>#include<sstream>#define LL long long#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)#define mem(a,x) memset(a,x,sizeof(a))#define lson l,m,x<<1#define rson m+1,r,x<<1|1using namespace std;const int INF = 0x3f3f3f3f;const int mod = 1e9 + 7;const double PI = acos(-1.0);const double eps=1e-6;const int maxn = 2000 + 5 ;int dp[maxn][maxn] ;int a[maxn] , b[maxn] , prefix[maxn];int main(){ int n ; scanf("%d",&n); for(int i = 1 ; i<= n ; i++){ scanf("%d",&a[i]); b[i] = a[i] ; } sort( b + 1 , b + n + 1 ); for(int i = 1 ; i<= n ; i++){ prefix[i] = 0; for(int j = 1 ; j<= n ; j++){ dp[i][j] = INF; } } int len = unique(b + 1 , b + n + 1 ) - b - 1 ; for(int i = 1 ; i <= n ; i++){ for(int j =1 ; j <= len ; j++){ dp[i][j] = min(dp[i][j] , prefix[j ] + abs(a[i] - b[j]) ) ; } prefix[1] = dp[i][1] ; for(int j = 2 ; j<= len ; j++){ prefix[j] = min(prefix[j - 1] , dp[i][j]) ; //第i次循环中prefix[j]表示dp[i][k](k<=j)的最小值,用于第i+1次循环时dp[i+1][j]的更新 } } int ans = INF ; for(int i = 1 ; i<= len ; i++){ ans = min(ans , dp[n][i]); } printf("%d\n",ans); return 0;}
0 0
- POJ3666 making the grade dp+前缀+离散化
- POJ3666 Making the Grade [DP,离散化]
- POJ3666 Making the Grade [DP,离散化]
- POJ3666 Making the Grade [DP,离散化]
- POJ3666 Making the Grade 离散化+DP
- POJ3666 Making the Grade(DP,离散化 待整理)
- poj3666 Making the Grade dp
- POJ3666-Making the Grade-dp
- 线性DP POJ3666 Making the Grade
- POJ3666---Making the Grade
- poj3666 Making the Grade
- poj3666 Making the Grade
- POJ3666-Making the Grade
- 【POJ3666】Making the Grade
- POJ3666 Making the Grade题解-动态规划dp
- POJ 3666 Making the Grade (DP+离散化)
- poj 3666 Making the Grade dp 离散化
- [POJ 3666] Making the Grade (序列DP+离散化)
- 安卓自定义view之仿极客学院动态加载
- 数组中重复的数字
- Magenta源代码笔记(3) —— 内存管理
- 得到一个对象的方法与属性(重要)
- java 字节流和字符流的区别
- POJ3666 making the grade dp+前缀+离散化
- oracle常用的数据字典
- JS在父页面写子页面的按钮响应事件
- 稳扎稳打JS——“继承”
- NYOJ-35-表达式求值(中缀式转后缀式 逆波兰表达式)
- android studio Butterknife的基本用法
- poj 1061 青蛙的约会(扩展欧几里得)
- 线程概述
- 面试算法问题