简体   繁体   中英

Algorithms - Dynamic Programming

Given an array of n elements a1, a2 ... an. If we define a function C = max |a(i+1)-a(i)| for i = 2 to n-1. So we can calculate a value of C for our array. Now the problem is, if we are given the array and some value of C, How many elements in the array should be changed to obtain this value of C?

This is a part of the solution to this codeforces problem: http://codeforces.com/contest/361/problem/D

It is solved using dynamic programming but I don't understand the answer. Could anyone explain it to me? Here is the code.

/* x is the value of the function 
n the size of the array

*/
int Cal(LL x){ 
    for(int i = 1; i <= n; i++)
        dp[i] = 0;
    for(int i = 1; i <= n; i++){
        for(int j = i + 1; j <= n; j++){
            if(abs(a[i] - a[j]) <= 1ll * (j - i) * x) {
                dp[j] = max(dp[j], dp[i] + 1);
            }
        }
    }
    int ret = 0;
    for(int i = 1; i <= n; i++)
        ret = max(ret, dp[i] + 1);
    return n - ret;
}

In this code, dp[i] denotes the max number of elements don't need to changed, in order to obtain this value of C, in range [1, i] , and we don't change a[i] .

Then check every j > i , if |a[i] - a[j]| <= (j - i) * C |a[i] - a[j]| <= (j - i) * C , we need change all elements between i and j, then dp[j] = max(dp[j], dp[i] + 1 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM