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。
这个题的难点就是找到严格递增的数列。就是下面所说的不严格递增的思想。
假设dp[i][j] 表示序列前 i 个数递增且第 i 个数的不大于原数列第 j 大的数的最少操作数。
状态转移方程为:dp[i][j]=min(dp[i][j−1], dp[i−1][j]+abs(a[i], b[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)ai<ai+1⟺ai≤ai+1−1⟺ai−i≤ai+1−(i+1) 成立,故对于每个读入的 a[i] ,ai=ai−iai=ai−i ,即可使用上述不严格递增的方式求解。
#include
#include
#include
using namespace std;
const int N=3005;
int n,a[N],b[N];
long long dp[N][N];
int main()
{
memset(dp,0x3f,sizeof(dp));
while(cin>>n)
{
for(int i=1;i<=n;i++)
{
cin>>a[i];
a[i]-=i;
b[i]=a[i];
}
sort(b+1,b+n+1);
for(int j=1;j<=n;j++)
dp[0][j]=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
dp[i][j]=min(dp[i][j-1], dp[i-1][j]+abs(a[i]-b[j]));
cout<<dp[n][n]<<endl;
}
}