zoukankan      html  css  js  c++  java
  • [POJ3666] Making the Grade

    Description

    A straight dirt road connects two fields on FJ's farm, but it changes elevation more than FJ would like. His cows do not mind climbing up or down a single slope, but they are not fond of an alternating succession of hills and valleys. FJ would like to add and remove dirt from the road so that it becomes one monotonic slope (either sloping up or down).

    You are given N integers A1, ... , AN (1 ≤ N ≤ 2,000) describing the elevation (0 ≤ Ai ≤ 1,000,000,000) at each of N equally-spaced positions along the road, starting at the first field and ending at the other. FJ would like to adjust these elevations to a new sequence B1, . ... , BN that is either nonincreasing or nondecreasing. Since it costs the same amount of money to add or remove dirt at any position along the road, the total cost of modifying the road is

    |A1 - B1| + |A2 - B2| + ... + |AN - BN |

    Please compute the minimum cost of grading his road so it becomes a continuous slope. FJ happily informs you that signed 32-bit integers can certainly be used to compute the answer.

    Input

    * Line 1: A single integer: N
    * Lines 2..N+1: Line i+1 contains a single integer elevation: Ai

    Output

    * Line 1: A single integer that is the minimum cost for FJ to grade his dirt road so it becomes nonincreasing or nondecreasing in elevation.

    题解:

    dp(向前取min)+离散化

    这题有两个方面需要考虑,首先是要代价最小,然后为了代价最小我们需要花费代价使高度尽量低,这就需要用dp来解决

    状态:dp[i][j]表示到第i位,且第i位为j的最小代价

    转移:dp[i][j]=min{dp[i-1][k]}+|a[i]-j| (k<=j)

    首先j<=10^9,所以要离散化,其次复杂度是三方的,肯定不行

    发现k始终比j小,且对于每一个j来说,一定是要找j前面代价最小的那一个状态,所以采用向前取min操作,就不用枚举k了

    #include<iostream>
    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    #define ll long long
    using namespace std;
    
    const int N = 2010;
    
    int a[N],v[N],dp[N][N];
    
    int gi() {
      int x=0,o=1; char ch=getchar();
      while(ch!='-' && (ch<'0' || ch>'9')) ch=getchar();
      if(ch=='-') o=-1,ch=getchar();
      while(ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
      return o*x;
    }
    
    int main() {
      int n=gi(),ans,mi;
      for(int i=1; i<=n; i++) {
        a[i]=v[i]=gi();
      }
      sort(v+1,v+n+1);//离散化
      memset(dp,63,sizeof(dp));
      ans=dp[0][0];
      for(int i=1; i<=n; i++) dp[0][i]=0;
      for(int i=1; i<=n; i++) {
        mi=dp[i-1][1];
        for(int j=1; j<=n; j++) {
          mi=min(mi,dp[i-1][j]);
          dp[i][j]=min(dp[i][j],mi+abs(a[i]-v[j]));
        }
      }
      for(int i=1; i<=n; i++) ans=min(ans,dp[n][i]);
      printf("%d", ans);
      return 0;
    }
    
  • 相关阅读:
    strlen和sizeof
    函数值传递和地址传递
    指向函数的指针变量
    for循环scanf赋值刷新缓冲区
    指针
    排序简化
    随机数找到最大值
    上楼梯问题
    分布式系统并发情况下会生成多个token
    Swagger 文档生成工具
  • 原文地址:https://www.cnblogs.com/HLXZZ/p/7508367.html
Copyright © 2011-2022 走看看