[Luogu P2893] [USACO08FEB] Osamuro Making the Grade

Portal: https://www.luogu.org/problemnew/show/P2893

The title of "original elevation of each section of the road is A_i, after repairs are B_i, cost |. A_i - B_i | we require road repair is not monotonous monotone does not rise or drop in demand minimal cost.." At first glance rise up like sequences (obviously not), this is a relatively simple linear dp title track of. First, a valid solution must satisfy the constructed sequence B such that there ∀x∈B x∈A,

So B sequence must be composed of a plurality of consecutive segments x (x∈A), then the first A discrete reduce consumption, provided F [i] [j] is done before the number i, j is the number of the last the minimum cost, there are:

f [i] [j] = min (f [i-1] [k] + |A [i] -j|).

The time complexity is O (n ^ 2), does not time out.

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<cstring>
#include<vector>
using namespace std;
const int maxn = 2005;
int a[maxn], num[maxn], c[maxn];
int f[maxn][maxn];
int n;
int main() {
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
        num[i] = a[i];
    }
    sort(num + 1,num + n + 1);
    int m = unique(num + 1,num + n + 1) - num - 1;
    for(int i = 1; i <= n; i++)
        c[i] = lower_bound
               (num + 1,num + n + 1,a[i]) - num;
    memset(f,0x3f,sizeof(f));
    f[0][0] = 0;
    for(int i = 1; i <= n; i++) {
        int temp = f[i - 1][0];
        for(int j = 1; j <= m; j++) {
            temp = min(temp,f[i - 1][j]);
            f[i][j] = temp + abs(a[i] - num[j]);
        }
    }
    int ans = 1 << 30;
    for(int i = 1; i <= m; i++)
        ans = min(ans,f[n][i]);
    printf("%d\n", ans);
    return 0;
}
View Code

 

Guess you like

Origin www.cnblogs.com/jiqimin/p/10992885.html