POJ-3666 Making the Grade
2016-08-13 16:55
295 查看
题目大意是给定一串序列,变成非严格递增或非严格递减,总代价是修改单个值变化的总和。
思路:
DP、离散化
首先离散化ai 所有可能的取值,使之成为一个单调的序列b
状态转移方程为 d(i, j) = min{d(i - 1, k), k <= j} + |ai - bj|
其中d(i, j) 代表前 i 个数 离散化后的第j小的数 bj
此时复杂度是O(n ^ 3)
可用一个变量 Min 代表当前最小优化时间复杂度 到 O(n ^ 2)
思路:
DP、离散化
首先离散化ai 所有可能的取值,使之成为一个单调的序列b
状态转移方程为 d(i, j) = min{d(i - 1, k), k <= j} + |ai - bj|
其中d(i, j) 代表前 i 个数 离散化后的第j小的数 bj
此时复杂度是O(n ^ 3)
可用一个变量 Min 代表当前最小优化时间复杂度 到 O(n ^ 2)
#include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; int n; const int maxn = 2000 + 10; const int INF = 1000000100; int d[maxn][maxn]; int s[maxn]; int dp(int *a){ memset(d, 0, sizeof(d)); for(int i = 1; i <= n; ++i){ int Min = d[i - 1][1]; for(int j = 1; j <= n; ++j){ Min = min(Min, d[i - 1][j]); d[i][j] = abs(s[j] - a[i]) + Min; } } int Min = d [1]; for(int j = 1; j <= n; ++j){ Min = min(Min, d [j]); } return Min; } int main() { while(scanf("%d", &n) == 1){ int a[maxn]; for(int i = 1; i <= n; ++i){ scanf("%d", &a[i]); s[i] = a[i]; } sort(s + 1, s + n + 1); int res = dp(a); for(int i = 1; i <= n / 2; ++i){ swap(a[i], a[n - i + 1]); } res = min(res, dp(a)); printf("%d\n", res); } return 0; }
相关文章推荐
- POJ3666 Making the Grade [DP,离散化]
- POJ 3666 Making the Grade
- 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
- poj3666 Making the Grade dp
- POJ 3666 Making the Grade
- POJ 3666 Making the Grade (dp)
- POJ 3666 Making the Grade
- poj 3666 Making the Grade (动态规划)
- POJ 3666 Making the Grade
- POJ 3666 Making the Grade [DP]
- POJ 3666 Making the Grade 滚动数组+状态压缩DP
- poj 3666 Making the Grade
- DP:Making the Grade(POJ 3666)
- poj 3666--Making the Grade
- POJ 3666 Making the Grade
- POJ 3666 Making the Grade (DP+离散化)