본문 바로가기

학부 수업 정리/알고리즘연습 (22-1)

[알고연] (2주차-1) 1003C. Intense Heat

1003C. Intense Heat

The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are.

Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows:

Suppose we want to analyze the segment of nn consecutive days. We have measured the temperatures during these nn days; the temperature during ii-th day equals aiai.

We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day $x$ to day $y$, we calculate it as $\sum_{i=x}^y a_i /x+1$  (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than kk consecutive days. For example, if analyzing the measures [3,4,1,2] and k=3, we are interested in segments [3,4,1], [4,1,2]and [3,4,1,2] (we want to find the maximum value of average temperature over these segments).

You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?

이 문제를 브루트포스로 풀 경우 시간이 매우 오래 걸리지만, 누적합 배열을 이용하여 각 구간의 평균들을 구하면 훨씬 빠르게 구할 수 있다. psum 배열은 psum[0] = 0, psum[1] = vec[0], psum[2] = psum[1] + vec[1], ... 과 같이 해당 인덱스 까지의 값들의 누적합을 저장한다. (i, i+j] 구간의 평균을 구하기 위해서는 psum[i+j] 에서 psum[i] 를 빼고, 구간의 개수로 나눠주면 된다. 

#include <bits/stdc++.h>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int n, k; cin >> n >> k;
    double ans = 0;
    vector<int> vec(n), psum(n+1);
    for (int i = 0; i < n; i++) cin >> vec[i];
    psum[0] = 0;
    for (int i = 1; i <= n; i++) psum[i] = psum[i - 1] + vec[i - 1];
    for (int j = k; j <= n; j++) {
        for (int i = 0; i <= n - j; i++) {
            ans = max(ans, ((double)psum[i + j] - psum[i]) / (double)j);
        }
    }
    printf("%lf\n", ans);
    return 0;
}