码迷,mamicode.com
首页 > 其他好文 > 详细

【POJ 3666】Making the Grade

时间:2015-09-18 23:23:44      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

Making the Grade
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 4962   Accepted: 2348

Description

A straight dirt road connects two fields on FJ‘s farm, but it changes elevation more than FJ would like. His cows do not mind climbing up or down a single slope, but they are not fond of an alternating succession of hills and valleys. FJ would like to add and remove dirt from the road so that it becomes one monotonic slope (either sloping up or down).

You are given N integers A1, ... , AN (1 ≤ N ≤ 2,000) describing the elevation (0 ≤ Ai ≤ 1,000,000,000) at each of N equally-spaced positions along the road, starting at the first field and ending at the other. FJ would like to adjust these elevations to a new sequence B1, . ... , BN that is either nonincreasing or nondecreasing. Since it costs the same amount of money to add or remove dirt at any position along the road, the total cost of modifying the road is

|AB1| + |AB2| + ... + |AN - BN |

Please compute the minimum cost of grading his road so it becomes a continuous slope. FJ happily informs you that signed 32-bit integers can certainly be used to compute the answer.

Input

* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer elevation: Ai

Output

* Line 1: A single integer that is the minimum cost for FJ to grade his dirt road so it becomes nonincreasing or nondecreasing in elevation.

Sample Input

7
1
3
2
4
5
3
9

Sample Output

3

Source

 
我觉得是DP题吧。但是看status的那些大神跑到了0MS,,,,我不知道他们怎么做的。
先说说我的做法吧。
f[i, j]是前i个元素做成单调不上升(不下降),最后一个高度为b[j]的时候的最小值。b是a的值排序后的数组。
然后,明显 f[i,j] = min{f[i - 1, k] | 0 <= k <= j} + | a[i] - b[j] |
加滚动数组优化空间。
搞定,挺简单的。
时间复杂度O(N2)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

const int MAXN = 2005;

int n, cur, a[MAXN], b[MAXN];
long long f[2][MAXN];

int myabs(int x)
{
    return x < 0 ? -x : x;
}

long long solve(int st, int ed, int delta)
{
    long long best;
    memset(f, 0, sizeof(f));
    cur = 0;
    for (int i = st; i != ed; i += delta)
    {
        best = 0x7fffffff;
        for (int j = 0; j < n; ++j)
        {
            best = min(best, f[cur ^ 1][j]);
            f[cur][j] = best + myabs(b[j] - a[i]);
        }
        cur ^= 1;
    }
    cur ^= 1;
    best = 0x7fffffff;
    for (int i = 0; i < n; ++i) best = min(best, f[cur][i]);
    return best;
}

int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n; ++i)
    {
        scanf("%d", &a[i]);
        b[i] = a[i];
    }
    sort(b, b + n);
    cout << min(solve(0, n, 1), solve(n - 1, -1, -1)) << endl;
    return 0;
}

 

【POJ 3666】Making the Grade

标签:

原文地址:http://www.cnblogs.com/albert7xie/p/4820550.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!