zoukankan      html  css  js  c++  java
  • HDU 3045 Picnic Cows

    $dp$,斜率优化。

    设$dp[i]$表示$1$至$i$位置的最小费用,则$dp[i]=min(dp[j]+s[i]-s[j]-(i-j)*x[j+1])$,$dp[n]$为答案。

    然后斜率优化就可以了。

    得到了两个教训:

    ①如果可以从$dp[0]$推过来,那么队列中一开始就压入$0$,不要忘记了。

    ②$check2$中,要压入哪个位置就判断哪个位置。

    #pragma comment(linker, "/STACK:1024000000,1024000000")
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    #include<vector>
    #include<map>
    #include<set>
    #include<queue>
    #include<stack>
    #include<ctime>
    #include<iostream>
    using namespace std;
    typedef long long LL;
    const double pi=acos(-1.0),eps=1e-10;
    void File()
    {
        freopen("D:\in.txt","r",stdin);
        freopen("D:\out.txt","w",stdout);
    }
    template <class T>
    inline void read(T &x)
    {
        char c = getchar();
        x = 0;
        while(!isdigit(c)) c = getchar();
        while(isdigit(c))
        {
            x = x * 10 + c - '0';
            c = getchar();
        }
    }
    
    int n,t;
    long long x[500000],dp[500000],s[500000];
    int q[500000],f1,f2;
    
    bool delete1(int a,int b,int c)
    {
        if(dp[b]-s[b]-x[b+1]*(c-b)<=dp[a]-s[a]-x[a+1]*(c-a)) return 1;
        return 0;
    }
    
    bool delete2(int a,int b,int c)
    {
        if(
           ((dp[c]-s[c]+x[c+1]*c)-(dp[b]-s[b]+x[b+1]*b))*(x[b+1]-x[a+1]) <=
           ((dp[b]-s[b]+x[b+1]*b)-(dp[a]-s[a]+x[a+1]*a))*(x[c+1]-x[b+1])
             ) return 1;
        return 0;
    }
    
    int main()
    {
        while(~scanf("%d%d",&n,&t))
        {
            for(int i=1;i<=n;i++) scanf("%lld",&x[i]);
            sort(x+1,x+1+n);
    
            for(int i=1;i<=n;i++) s[i]=s[i-1]+x[i];
    
            for(int i=t;i<2*t;i++) dp[i]=s[i]-x[1]*i;
    
            f1=f2=0; q[0]=0; f2++; q[f2]=t;
    
            for(int i=2*t;i<=n;i++)
            {
                while(1)
                {
                    if(f2-f1+1<2) break;
                    if(delete1(q[f1],q[f1+1],i)) f1++;
                    else break;
                }
    
                dp[i]=dp[q[f1]]+s[i]-s[q[f1]]-x[q[f1]+1]*(i-q[f1]);
    
                while(1)
                {
                    if(f2-f1+1<2) break;
                    if(delete2(q[f2-1],q[f2],i-t+1)) f2--;
                    else break;
                }
    
                f2++; q[f2]=i-t+1;
            }
            printf("%lld
    ",dp[n]);
        }
        return 0;
    }
  • 相关阅读:
    Pandas缺失值处理
    文件读取与存储
    DataFrame运算
    C++11 不抛异常的new operator
    In p = new Fred(), does the Fred memory “leak” if the Fred constructor throws an exception?
    method chaining
    C++中的运算符重载
    Why am I getting an error converting a Foo** → const Foo**?
    The constness of a method should makes sense from outside the object
    Virtual Friend Function
  • 原文地址:https://www.cnblogs.com/zufezzt/p/6357949.html
Copyright © 2011-2022 走看看