首页 > 代码库 > BZOJ 1592 Usaco 2008 Feb Making the Grade 路面修整 DP

BZOJ 1592 Usaco 2008 Feb Making the Grade 路面修整 DP

题目大意:给出一个不整齐的路面,可以将一个路面升高或者降低,都需要话费|x - x‘|的费用,把路面修正成单调不降或单调不升的最小花费是多少。


思路:路面的高度跨度有点大啊,先离散化。之后f[i][j] 表示到i为止路面保证单调不降并且最高高度为j的最小花费是多少,利用一个前缀和优化一下。单调不升也一样,简单DP水过。。


CODE:

#include <map>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 2010
#define INF 0x3f3f3f3f
using namespace std;
 
int cnt,src[MAX];
pair<int,int *> xx[MAX];
map<int,int> G;
 
int f[MAX][MAX],_f[MAX][MAX];//单调不降
int g[MAX][MAX],_g[MAX][MAX];//单调不升
 
int main()
{
    cin >> cnt;
    for(int i = 1; i <= cnt; ++i) {
        scanf("%d",&xx[i].first);
        xx[i].second = &src[i];
    }
    sort(xx + 1,xx + cnt + 1);
    int t = 0;
    for(int i = 1; i <= cnt; ++i) {
        if(i == 1 || xx[i].first != xx[i - 1].first)
            ++t;
        *xx[i].second = t;
        G[t] = xx[i].first;
    }
    memset(f,0x3f,sizeof(f));
    memset(g,0x3f,sizeof(g));
    for(int i = 1; i <= t; ++i)
        f[1][i] = g[1][i] = abs(G[src[1]] - G[i]);
    for(int i = 1; i <= cnt; ++i)
        _f[i][0] = _g[i][t + 1] = INF;
    for(int i = 1; i <= t; ++i)
        _f[1][i] = min(_f[1][i - 1],f[1][i]);
    for(int i = t; i; --i)
        _g[1][i] = min(_g[1][i + 1],g[1][i]);
    for(int i = 2; i <= cnt; ++i) {
        for(int j = 1; j <= cnt; ++j) {
            f[i][j] = _f[i - 1][j] + abs(G[j] - G[src[i]]);
            g[i][j] = _g[i - 1][j] + abs(G[j] - G[src[i]]);
        }
        for(int j = 1; j <= t; ++j)
            _f[i][j] = min(_f[i][j - 1],f[i][j]);
        for(int j = t; j; --j)
            _g[i][j] = min(_g[i][j + 1],g[i][j]);
    }
    int ans = INF;
    for(int i = 1; i <= t; ++i)
        ans = min(ans,min(f[cnt][i],g[cnt][i]));
    cout << ans << endl;
    return 0;
}


BZOJ 1592 Usaco 2008 Feb Making the Grade 路面修整 DP