题意
Sonya was unable to think of a story for this problem, so here comes the formal description.
You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.
给定 n 个正整数的数组,定义一次操作为:任选一个元素 +1
或 -1
。使得在尽可能少的操作数下使得数组序列严格递增。
解题思路
首先考虑数列递增(不严格)的情况:
给定含有 n 个整数的数组,定义一次操作为:任选一个元素 +1
或 -1
。使得在尽可能少的操作数下使得数组序列递增(非严格)。
对于这个问题,数列最终修改完成后的各个数都一定是原数列中某数时,操作数最少(
迷,只可意会...)。
故可以考虑用 DP 解决:dp[i][j]
表示序列前 i 个数递增且第 i 个数的不大于原数列第 j 大的数的最少操作数。
状态转移方程为:
dp[i][j]=min(dp[i][j−1], dp[i−1][j]+abs(a[i], b[j]))
,其中 a[i]
表示原数列中第 i 个数,b[j]
表示原数列中第 j 大的数(对原数列去重后)。
对于严格递增的情况:
不等式
ai<ai+1⟺ai≤ai+1−1⟺ai−i≤ai+1−(i+1)
成立,故对于每个读入的 a[i]
,
ai=ai−i
,即可使用上述不严格递增的方式求解。
此题竟然还有贪心解法,http://www.cnblogs.com/qscqesze/p/5929195.html ,
虽然无法理解
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 3010;
int n, a[N], b[N];
long long dp[N][N];
int main()
{
memset(dp, 0x3f, sizeof(dp));
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]),
a[i]-=i, b[i] = a[i];
sort(b+1, b+n+1);
int len = unique(b+1, b+n+1)-b;
for(int j=1;j<len;j++) dp[0][j] = 0;
for(int i=1;i<=n;i++)
for(int j=1;j<len;j++)
dp[i][j] = min(dp[i][j-1], dp[i-1][j]+abs(a[i]-b[j]));
printf("%I64d", dp[n][len-1]);
}