codeforces 360B dp+二分

题目链接:http://codeforces.com/problemset/problem/360/B

 

题目含义:给定n个数,你可以修改k个数,是他们中任意两个相邻的数的差值的绝对值最小,求出那个最小值

 

题目思路:将答案二分, dp[i]表示第i个数字不变并且前i个数字中任意两个相邻数字的差值的绝对值小于等于二分答案所需要改变数的个数,状态转移方程对于j

 

AC代码

#include
using namespace std;

long long num[2003];
int n, k;
long long dp[2003];

bool check(long long mid)
{
    dp[1] = 0;
    for(int i = 2; i <= n; ++i)
    {
        dp[i] = i-1;
        for(int j = 1; j < i; ++j)
        {
            if(abs(num[i]-num[j]) <= mid*(i-j))
                dp[i] = min(dp[i], dp[j]+i-j-1);
        }
    }
    if(dp[n] <= k)
        return true;
    for(int i = 1; i <= n; ++i)
    {
        if(dp[i]+n-i <= k)
            return true;
    }
    return false;
}

int main()
{
    cin >> n >> k;
    for(int i = 1; i <= n; ++i)
        cin >> num[i];
    long long l = 0;
    long long r = 2e9;
    long long ans, mid;
    while(l <= r)
    {
        mid = (l+r)/2;
        if(check(mid))
            ans = mid, r= mid-1;
        else
            l = mid + 1;
    }
    cout << ans << "\n";
    return 0;
}

 

你可能感兴趣的:(Dynamic,programming)