[hdu][2993][MAX Average Problem]

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2993

一个细节没注意,导致WA了无数遍,不过也让我对斜率优化有了更深的认识,要维护“队列里”的数据的凸性。

View Code
#include <iostream>

#include <stdio.h>

#include <string.h>

#include <algorithm>



using namespace std;



const int N = 100000+10;



int n, m, l, r, k;

int q[N];

double a[N];

char ch = 0;



void input(){

    a[0] = 0;

    ch = 0;

    int s=1;

    while (s<=n){

        int sum = 0;

        while (ch>'9'||ch<'0') ch = getchar();

        while (ch<='9'&&ch>='0') sum=sum*10+ch-'0',ch=getchar();

        a[s]=a[s-1]+sum, s++;

    }

}



bool superior1(int k1, int k2, int r)

{

    return (a[k2]-a[k1])*(r-k2)<(a[r]-a[k2])*(k2-k1);

}



bool superior2(int k1, int k2, int r)

{

    return (a[r]-a[k1])*(r-k2)<=(a[r]-a[k2])*(r-k1);

}



int main()

{

    //freopen("/home/nigel/project/a", "r", stdin);

    while (~scanf("%d%d", &n, &k))

    {

        input();

        double ans = 0;

        q[l=r=0] = 0;

        for (int i=k; i<=n; i++)

        {

            int now = i-k;

            while (l<r&&!superior1(q[r-1],q[r],now)) r--;  //这里把now写成了i,各种WA

            q[++r]=now;

            while (l<r&&superior2(q[l],q[l+1],i)) l++;

            ans = max(ans, (a[i]-a[q[l]])/(i-q[l]));

        }

        printf("%.2lf\n", ans);

    }

    return 0;

}

你可能感兴趣的:(HDU)