# BZOJ-1721|线性dp-缆车支柱

## Ski Lift 缆车支柱

#### Description

Farmer Ron in Colorado is building a ski resort for his cows (though budget constraints dictate construction of just one ski lift). The lift will be constructed as a monorail and will connect a concrete support at the starting location to the support at the ending location via some number of intermediate supports, each of height 0 above its land. A straight-line segment of steel connects every pair of adjacent supports. For obvious reasons, each section of straight steel must lie above the ground at all points. Always frugal, FR wants to minimize the number of supports that he must build. He has surveyed the N (2 <= N <= 5,000) equal-sized plots of land the lift will traverse and recorded the integral height H (0 <= H <= 1,000,000,000) of each plot. Safety regulations require FR to build adjacent supports no more than K (1 <= K <= N - 1) units apart. The steel between each pair of supports is rigid and forms a straight line from one support to the next. Help FR compute the smallest number of supports required such that: each segment of steel lies entirely above (or just tangent to) each piece of ground, no two consecutive supports are more than K units apart horizontally, and a support resides both on the first plot of land and on the last plot of land.

#### Input

• Line 1: Two space-separate integers, N and K

• Lines 2..N+1: Line i+1 contains a single integer that is the height of plot i.

#### Output

• Line 1: A single integer equal to the fewest number of lift towers FR needs to build subject to the above constraints

13 4
0
1
0
2
4
6
8
6
8
8
9
11
12

5

#### 思路：

dp状态转移方程:
dp[i] 表示在i点最少建立的柱子
dp[i] 就等于 dp[i-k] ~ dp[i-1] 上建立的最少的柱子数 + 1

#### AC代码

#include<bits/stdc++.h>
#define eps 1e-6
using namespace std;

typedef long long ll;
const int maxn = 5010;
int n,k;
ll h[maxn];
ll dp[maxn];

/*

dp[i] 表示在i点最少建立的柱子
dp[i] 就等于 dp[i-k] ~ dp[i-1] 上建立的最少的柱子数 + 1
*/

//判断起点e 和 终点s 是否能建立一个连线 (当且仅当 e 和 s连起来的线段上没有经过其他柱子)
bool check(int s,int e){
double h1=h[s],k=(h[e]-h[s])*1.0/(e-s); //k表示斜率 h表示当前高度
for(int i=s+1;i<e;i++){
h1+=k;
if(h1<h[i]&&fabs(h1-h[i])>eps)return 0;
}
return true;
}

int main(){
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++) scanf("%lld",&h[i]);
memset(dp,0x3f3f3f,sizeof(dp));//要求dp的最小值 先要初始化为无穷大
dp[1] = 1;
dp[2] = 2;
for(int i=3;i<=n;i++){
for(int j=max(1,i-k);j<i;j++){
if(dp[i] > dp[j] + 1 && check(j,i)) dp[i] = dp[j] + 1;
}
}
printf("%lld\n",dp[n]);
return 0;
}

posted @ 2019-04-20 17:46  fishers  阅读(236)  评论(0编辑  收藏  举报