[BZOJ 1592] [Usaco2008 Feb] 路面修整

[BZOJ 1592] [Usaco2008 Feb] 路面修整_第1张图片

Solution :

数据范围小,平方算法是资瓷的,前缀和优化DP一发

Code :

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

inline void read(int &x){char c;while((c=getchar())<'0'||c>'9');for(x=c-'0';(c=getchar())>='0'&&c<='9';x=x*10+c-'0');}
const int inf = 0x7fffffff;
const int N = 2005;

int a[N], b[N];
int dp[N][N], g[N][N], n;

int main() 
{
    #ifdef LX_JUDGE
    freopen("in.txt", "r", stdin);
    #endif

    read(n);

    for (int i = 0; i < n; ++i) read(b[i]), a[i] = b[i];
    sort(a, a + n);

    for (int i = 0; i < n; ++i) 
    {
        dp[0][i] = abs(b[0] - a[i]);
        g[0][i] = i ? min(g[0][i - 1], dp[0][i]) : dp[0][i];
    }

    for (int i = 1; i < n; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            dp[i][j] = g[i - 1][j] + abs(b[i] - a[j]);
            g[i][j] = j ? min(g[i][j - 1], dp[i][j]) : dp[i][j];
        }
    }

    int ans = g[n - 1][n - 1];

    for (int i = n - 1; ~i; --i)
    {
        dp[0][i] = abs(b[0] - a[i]);
        g[0][i] = (i != n - 1) ? min(g[0][i + 1], dp[0][i]) : dp[0][i];
    }
    for (int i = 1; i < n; ++i)
    {
        for (int j = n - 1; ~j; --j)
        {
            dp[i][j] = g[i - 1][j] + abs(b[i] - a[j]);
            g[i][j] = (j != n - 1) ? min(g[i][j + 1], dp[i][j]) : dp[i][j];
        }
    }

    ans = min(ans, g[n - 1][0]);

    printf("%d\n", ans);

    return 0;
}

你可能感兴趣的:(bzoj,dp优化)