zoukankan      html  css  js  c++  java
  • bzoj-4518 4518: [Sdoi2016]征途(斜率优化dp)

    题目链接:

    4518: [Sdoi2016]征途

    Description

    Pine开始了从S地到T地的征途。
    从S地到T地的路可以划分成n段,相邻两段路的分界点设有休息站。
    Pine计划用m天到达T地。除第m天外,每一天晚上Pine都必须在休息站过夜。所以,一段路必须在同一天中走完。
    Pine希望每一天走的路长度尽可能相近,所以他希望每一天走的路的长度的方差尽可能小。
    帮助Pine求出最小方差是多少。
    设方差是v,可以证明,v×m^2是一个整数。为了避免精度误差,输出结果时输出v×m^2。
     

    Input

    第一行两个数 n、m。
    第二行 n 个数,表示 n 段路的长度
     

    Output

     一个数,最小方差乘以 m^2 后的值

     

    Sample Input

    5 2
    1 2 5 8 6

    Sample Output

    36

    HINT

    1≤n≤3000,保证从 S 到 T 的总路程不超过 30000

     
    思路:
     
    又是一个斜率优化dp,跟把n个数分成m块,平方和最小等效,然后就是斜率优化dp啦;
     
    AC代码:
     
    #include <bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    const int maxn=3e3+4;
    int n,m,q[maxn],head=1,tail=1;
    LL a[maxn],sum[maxn],dp[maxn][maxn];
    inline double slope(int l,int r,int dep)
    {
        double ratio;
        ratio=(double)(dp[r][dep]+sum[r]*sum[r]-dp[l][dep]-sum[l]*sum[l])/(double)(sum[r]-sum[l]);
        return ratio;
    }
    int main()
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)scanf("%lld",&a[i]),sum[i]=sum[i-1]+a[i];
        for(int i=1;i<=n;i++)dp[i][1]=sum[i]*sum[i];
        for(int j=2;j<=m;j++)
        {
            head=tail=1;
            for(int i=1;i<=n;i++)
            {
                while(head<tail&&slope(q[head],q[head+1],j-1)<(double)2*sum[i])head++;//因为sum[i]是单调递增的;
                dp[i][j]=dp[q[head]][j-1]+(sum[i]-sum[q[head]])*(sum[i]-sum[q[head]]);
                while(head<tail&&slope(q[tail-1],q[tail],j-1)>slope(q[tail],i,j-1))tail--;
                q[++tail]=i;
            }
        }
        printf("%lld
    ",m*dp[n][m]-sum[n]*sum[n]);
        return 0;
    }
    

      

  • 相关阅读:
    cogs 1682. [HAOI2014]贴海报 WW
    cogs 2039. 树的统计
    cogs luogu [NOIP2011] 选择客栈
    cogs luogu 1804. [NOIP2014]联合权值 WD
    cogs luogu [NOIP2014]生活大爆炸版石头剪刀布
    leetcode[119]Pascal's Triangle II
    leetcode[120]Triangle
    leetcode[121]Best Time to Buy and Sell Stock
    leetcode[122]Best Time to Buy and Sell Stock II
    leetcode[123]Best Time to Buy and Sell Stock III
  • 原文地址:https://www.cnblogs.com/zhangchengc919/p/6129615.html
Copyright © 2011-2022 走看看