Post

[백준] 21921번 - 블로그 [Java][C++]

[백준] 21921번 - 블로그 [Java][C++]

문제 링크


1. 문제 풀이

주어진 $1$ 일 ~ $N$ 일 중 연속된 $X$ 일에 대해 방문자 수가 최대인 순간의 값을 구하고 그런 구간의 개수를 출력하되, 최대 방문자 수가 $0$ 이면 SAD 를 출력해야 하는 문제다. $N$ 이 최대 $250,000$ 이어서 $O(N^2)$ 으로는 해결할 수 없어 효율적인 탐색이 필요하다. 구간의 합을 빠르게 구할 수 있는 누적합을 활용하거나, 구간의 길이가 고정되어 있다는 점에서 슬라이딩 윈도우를 활용하면 해결할 수 있다.


2. 코드

1. 누적합 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        int X = Integer.parseInt(st.nextToken());

        int[] arr = new int[N];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        int[] pSum = new int[1 + N];
        for (int i = 1; i <= N; i++) {
            pSum[i] = pSum[i - 1] + arr[i - 1];
        }

        int max = 0;
        int cnt = 0;
        for (int i = 0; i <= N - X; i++) {
            int diff = pSum[i + X] - pSum[i];

            if (diff > max) {
                max = diff;
                cnt = 1;
            } else if (diff == max) {
                cnt++;
            }
        }

        if (max == 0) {
            System.out.println("SAD");
        } else {
            System.out.println(max);
            System.out.println(cnt);
        }
    }
}

2. 슬라이딩 윈도우 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        int X = Integer.parseInt(st.nextToken());

        int[] arr = new int[N];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        // 초기 윈도우의 방문자 수 합 계산
        int sum = 0;
        for (int i = 0; i < X; i++) {
            sum += arr[i];
        }

        // 윈도우를 이동하며 최대 방문자수 계산
        int max = sum;
        int cnt = 1;
        for (int i = 0; i < N - X; i++) {
            sum = sum - arr[i] + arr[i + X];

            // 이동한 구간의 최대 방문자 수가 더 많으면 최댓값과 개수를 갱신하고 동일하면 개수만 갱신
            if (sum > max) {
                max = sum;
                cnt = 1;
            } else if (sum == max) {
                cnt++;
            }
        }

        if (max == 0) {
            System.out.println("SAD");
        } else {
            System.out.println(max);
            System.out.println(cnt);
        }
    }
}

3. 누적합 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <bits/stdc++.h>
using namespace std;

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

    int n, x;
    cin >> n >> x;

    vector<int> v(n);
    for (int& x : v) cin >> x;

    vector<int> psum(1 + n);
    for (int i = 1; i <= n; i++) {
        psum[i] = psum[i - 1] + v[i - 1];
    }

    int mx = 0;
    int cnt = 0;
    for (int i = 0; i <= n - x; i++) {
        int diff = psum[i + x] - psum[i];

        if (diff > mx) {
            mx = diff;
            cnt = 1;
        } else if (diff == mx) {
            cnt++;
        }
    }

    if (mx == 0) {
        cout << "SAD";
    } else {
        cout << mx << '\n';
        cout << cnt << '\n';
    }
}

4. 슬라이딩 윈도우 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <bits/stdc++.h>
using namespace std;

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

    int n, x;
    cin >> n >> x;

    vector<int> v(n);
    for (int& x : v) cin >> x;

    // 초기 윈도우의 방문자 수 합 계산
    int sum = 0;
    for (int i = 0; i < x; i++) {
        sum += v[i];
    }

    // 윈도우를 이동하며 최대 방문자수 계산
    int mx = sum;
    int cnt = 1;
    for (int i = 0; i < n - x; i++) {
        sum = sum - v[i] + v[i + x];

        // 이동한 구간의 최대 방문자 수가 더 많으면 최댓값과 개수를 갱신하고 동일하면 개수만 갱신
        if (sum > mx) {
            mx = sum;
            cnt = 1;
        } else if (sum == mx) {
            cnt++;
        }
    }

    if (mx == 0) {
        cout << "SAD";
    } else {
        cout << mx << '\n';
        cout << cnt << '\n';
    }
}

3. 풀이 정보

1. 누적합 [Java]

언어시간메모리코드 길이
Java 11316 ms36148 KB1165 B

2. 슬라이딩 윈도우 [Java]

언어시간메모리코드 길이
Java 11316 ms35088 KB1383 B

3. 누적합 [C++]

언어시간메모리코드 길이
C++ 1720 ms3980 KB690 B

4. 슬라이딩 윈도우 [C++]

언어시간메모리코드 길이
C++ 1720 ms3000 KB896 B

This post is licensed under CC BY 4.0 by the author.