跳到正文

题解

题解 P1419 【寻找段落】

Remake_约 2 分钟
原文
文章信息与版本

文章信息

发布
2020年10月3日
收录
2026年8月17日
更新
2026年11月12日
篇幅
约 2 分钟
获赞
68
题目
P1419

版本

  1. v1当前

前缀和优化的暴力大家都会吧,复杂度O⁡(n2)\operatorname{O}(n^2)。

但是这样显然会超时,怎么办?

于是我们可以在for语句中添加 (double)clock() / CLOCKS_PER_SEC <= 0.95来让程序在跑完0.95s0.95s之后直接退出循环然后输出此时的最优解。

为啥这个做法可行呢?因为依照贪心的思路我们选择段落长度越小,平均值越容易做到最大(这个思路在大多时候是对的),所以我们从最小的段落长度开始枚举,时间快跑完的时候停止,有非常大概率是对的。

贼短的Code:

C++
#include <bits/stdc++.h>
using namespace std;
int n, s, t, a[100005], qzh[100005];
double maxx = -0x7fffffff;
int main()
{
    cin >> n >> s >> t;
    for (register int i = 1; i <= n; i++)
        cin >> a[i];
    for (register int i = 1; i <= n; i++)
        qzh[i] = qzh[i - 1] + a[i];
    for (register int i = s; i <= t && (double)clock() / CLOCKS_PER_SEC <= 0.95; ++i)
        for (register int j = i; j <= n; ++j)
            maxx = max(maxx, (qzh[j] - qzh[j - i]) / (1.0 * i));
    printf("%.3f", maxx);
}

或许可以被神仙数据卡掉?