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

[USACO08FEB]修路Making the Grade

时间:2019-10-03 18:21:45      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:using   org   getc   ems   www   分析   reg   http   gis   

题目链接:

走这里

题目分析:

考虑绝对值的几何意义,显然\(b\)里的数一定在\(a\)里出现过
离不离散化问题不大,用下标作第二位状态就行
\(dp[i][j]\)表示第\(i\)个数,高度为\(a[j]\)时的最优解
方程见代码

代码:

#include<bits/stdc++.h>
#define int long long
#define N (2000 + 10)
using namespace std;
inline int read() {
    int cnt = 0, f = 1; char c = getchar();
    while (!isdigit(c)) {if (c == '-') f = -f; c = getchar();}
    while (isdigit(c)) {cnt = (cnt << 3) + (cnt << 1) + c - '0'; c = getchar();}
    return cnt * f;
}
int n, a[N], b[N << 1], dp[N][N], gmin = 1 << 30;
int ans = (1 << 30);
signed main() {
//  freopen("grading.in", "r", stdin);
//  freopen("grading.out", "w", stdout);
    n = read();
    for (register int i = 1; i <= n; ++i) a[i] = b[i] = read();
    memset(dp, 0x3f, sizeof(dp));
    for (register int i = 1; i <= n; ++i) dp[1][i] = abs(a[1] - a[i]);
    sort(a + 1, a + n + 1);
    
    for (register int i = 2; i <= n; ++i) {
        gmin = (1 << 30);
        for (register int j = 1; j <= n; ++j) {
            gmin = min(gmin, dp[i - 1][j]);
            dp[i][j] = gmin + abs(b[i] - a[j]);
        }
    }
    for (register int i = 1; i <= n; ++i) ans = min(ans, dp[n][i]);

    memset(dp, 0x3f, sizeof(dp));
    
    for (register int i = 2; i <= n; ++i) {
        gmin = (1 << 30);
        for (register int j = n; j >= 1; --j) {
            gmin = min(gmin, dp[i - 1][j]);
            dp[i][j] = min(dp[i][j], gmin + abs(b[i] - a[j]));
        }
    }
    
    for (register int i = 1; i <= n; ++i) ans = min(ans, dp[n][i]);
    printf("%lld", ans);
    return 0;
}

[USACO08FEB]修路Making the Grade

标签:using   org   getc   ems   www   分析   reg   http   gis   

原文地址:https://www.cnblogs.com/kma093/p/11620160.html

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