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 N N integers A 1 , ⋯   , A N ( 1 ≤ N ≤ 2 , 000 ) A_1,\cdots, A_N (1 ≤ N ≤ 2,000) A1,⋯,AN(1≤N≤2,000) describing the elevation ( 0 ≤ A i ≤ 1 , 000 , 000 , 000 ) (0 ≤ Ai ≤ 1,000,000,000) (0≤Ai≤1,000,000,000) at each of N N 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 B 1 , ⋯   , B N B_1,\cdots, B_N 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
∣
A
1
−
B
1
∣
+
∣
A
2
−
B
2
∣
+
⋯
+
∣
A
N
−
B
N
∣
| A_1 - B_1| + | A_ 2 - B_ 2| + \cdots + | A_N - B_N |
∣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
N
N
Lines
2
⋯
N
+
1
2\cdots N+1
2⋯N+1: Line
i
+
1
i+1
i+1 contains a single integer elevation:
A
i
A_i
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.
Sample Input
7
1
3
2
4
5
3
9
Sample Output
3
记最小值
S
=
∑
i
=
1
N
∣
A
i
−
B
i
∣
S=\sum_{i=1}^N|A_i-B_i|
S=∑i=1N∣Ai−Bi∣
本题最玄幻的地方:
在满足
S
S
S最小化的前提下,一定存在一种构造序列
B
B
B的方案,使得
B
B
B中的数值都在
A
A
A中出现过。
我们设
F
[
i
,
j
]
F[i,j]
F[i,j] 表示完成前
i
i
i 个数的构造,其中
B
i
=
j
B_i=j
Bi=j 时,
S
S
S 的最小值。
状态转移方程:
F
[
i
,
j
]
=
min
0
≤
k
≤
j
{
F
[
i
−
1
,
k
]
+
∣
A
i
−
j
∣
}
F[i,j]=\min\limits_{0\leq k\leq j}\{F[i-1,k]+|A_i-j|\}
F[i,j]=0≤k≤jmin{F[i−1,k]+∣Ai−j∣}
我们可以将
A
A
A 离散化,并且记录决策集合中的最小值,时间复杂度
O
(
N
2
)
O(N^2)
O(N2) 。
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int N=2e3+10;
const int INF=0x3f3f3f3f;
int a[N],b[N],n,f[N][N],ans=INF;
int main()
{
//freopen("in.txt","r",stdin);
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++)
{
int tmp=INF;
for(int j=1;j<=n;j++)
{
tmp=min(tmp,f[i-1][j]);
f[i][j]=tmp+abs(a[i]-b[j]);
}
}
for(int i=1;i<=n;i++)
ans=min(ans,f[n][i]);
printf("%d\n",ans);
return 0;
}
总结
这道DP题中,最关键的就是那个引理,然后就是状态的定义和转移时根据状态集合只增不减的性质减少遍历。