hdu 3045 Picnic Cows

斜率dp

先更新,后添加

#include <STDIO.H>
#include <STRING.H>
#include <algorithm>
using namespace std;
typedef __int64 ll;
/*
    斜率dp
    dp[i] = min(dp[j] + sum[i]-sum[j]-a[j+1]*(i-j)) i-m>=j>=m
    if k<j 
    dp[k]-sum[k]-a[k+1]*(i-k) >= dp[j]-sum[j]-a[j+1]*(i-j)
    dp[j]-dp[k]+sum[k]-sum[j]-k*a[k+1]+j*a[j+1] <= i*(a[j+1]-a[k+1])
*/
const int MAXN = 400005;
inline int min(double a, double b)
{
    return a<b?a:b;
}
int n, m;
ll sum[MAXN], a[MAXN], dp[MAXN];
int q[MAXN];
ll getUP(int k, int j)
{
    return dp[j]-dp[k]+sum[k]-sum[j]-k*a[k+1]+j*a[j+1];
}
ll getDOWN(int k, int j)
{
     return a[j+1]-a[k+1];
}
ll getDP(int i, int j)
{
    return dp[j] + sum[i]-sum[j]-a[j+1]*(i-j);
}
int main()   
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif
    int i, j;
    int head, tail;
    while (scanf("%d%d", &n, &m) == 2)
    {
        for (i = 1, sum[0]=0 ; i<= n; ++i)
            scanf("%I64d", &a[i]);
        sort(a+1, a+1+n);
        for (i = 1; i<=n; ++i)
            sum[i] = sum[i-1]+a[i];
        head = tail = 0;
        q[tail++] = 0;
        for (i = m; i<= n; ++i)
        {
            while ( tail-head>1 && getUP(q[head],q[head+1])<=i*getDOWN(q[head],q[head+1]))
                head++;
            dp[i] = getDP(i, q[head]);
            j = i-m+1;
            if (j < m) continue;
            while ( tail -head > 1 && getUP(q[tail-2],q[tail-1])*getDOWN(q[tail-1],j)
                >= getUP(q[tail-1],j)*getDOWN(q[tail-2],q[tail-1]))
                tail--;
            q[tail++] = j;
        }
        printf("%I64d\n", dp[n]);
    }
    return 0;
}


你可能感兴趣的:(hdu 3045 Picnic Cows)