[USACO08FEB] road solution to a problem

Welcome to behold look

Topic Link

This question is the code is simple, but the state transition equation is quite difficult to think of

First, we can find a greedy nature, to make the repairs finished way to spend a minimum, each route will be bound to the already existing height, otherwise it will cause losses

Next, how to handle it? Consider the use of the above properties to design a state

First input data at discrete, \ (B [I] \) represents \ (I \) highly elevated road, you can use \ (f [i] [j ] \) indicates when the first \ (I \ ) the height of the road \ (b [j] \) , the front End repair \ (I \) minimum cost route used, transfer is not difficult to think

\(f[i][j]=min(f[i-1][k])+|a[i]-b[j]|(k\in[1,j))\)

Wherein \ (min (f [i- 1] [k]) \) can be an array of record, you can put \ (O (n ^ 3) \) complexity of optimization to \ (O (n ^ 2) \)

Next is the code

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,a[2003],b[2003],mi[2003][2003],f[2003][2003];//mi数组用来记录min(f[i-1][k])
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        b[i]=a[i];
    }
    sort(b+1,b+n+1);//离散化
    for(int i=1;i<=n;i++)
        mi[i][0]=1e9;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
            f[i][j]=mi[i-1][j]+abs(a[i]-b[j]),mi[i][j]=min(mi[i][j-1],f[i][j]);     
    }
    cout<<mi[n][n];
    return 0;
}

Guess you like

Origin www.cnblogs.com/dzice/p/11938678.html