Algoogle

Algorithm for Programming Contest

PKU 3666 Making the Grade

Category: PKU Tag: compress, dp

Making the Grade

問題概要


解法


dp[i][j] := i番目を高さj以上にするときの最小のコスト
高さの種類は高々N個なので座圧する.

コード


(3666.cpp) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>
#include <vector>

using namespace std;

#define int long long

const int inf = (int)1e18;
int N, M, A[2048];
int dp[2048][2048];
int dp2[2048][2048];
int ans;
int unzip[2048];

signed main(){
    scanf("%lld", &N);
    vector<int> tmp;
    for(int i = 0; i < N; i++){
        scanf("%lld", A+i);
        tmp.push_back(A[i]);
    }
    sort(tmp.begin(), tmp.end());
    tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end());
    M = tmp.size();
    for(int i = 0; i < M; i++) unzip[i] = tmp[i];

    for(int i = 0; i < M; i++){
        dp[0][i] = abs(A[0] - unzip[i]);
        dp2[0][i] = dp[0][i];
        if(i) dp2[0][i] = min(dp2[0][i], dp2[0][i-1]);
    }
    for(int i = 1; i < N; i++)
        for(int j = 0; j < M; j++){
            dp[i][j] = dp2[i-1][j] + abs(A[i] - unzip[j]);
            dp2[i][j] = dp[i][j];
            if(j) dp2[i][j] = min(dp2[i][j], dp2[i][j-1]);
        }
    ans = dp2[N-1][M-1];

    reverse(A, A+N);
    for(int i = 0; i < M; i++){
        dp[0][i] = abs(A[0] - unzip[i]);
        dp2[0][i] = dp[0][i];
        if(i) dp2[0][i] = min(dp2[0][i], dp2[0][i-1]);
    }
    for(int i = 1; i < N; i++)
        for(int j = 0; j < M; j++){
            dp[i][j] = dp2[i-1][j] + abs(A[i] - unzip[j]);
            dp2[i][j] = dp[i][j];
            if(j) dp2[i][j] = min(dp2[i][j], dp2[i][j-1]);
        }
    ans = min(ans, dp2[N-1][M-1]);
    printf("%lld\n", ans);
    return 0;
}

Comments