[Baekjoon] #11659 - 구간 합 구하기 4

부리또의 댄스·2025년 4월 11일
1

baekjoon

목록 보기
6/8
post-thumbnail

문제

수 N개가 주어졌을 때, i번째 수부터 j번째 수까지 합을 구하는 프로그램을 작성하시오.

입력

첫째 줄에 수의 개수 N과 합을 구해야 하는 횟수 M이 주어진다. 둘째 줄에는 N개의 수가 주어진다. 수는 1,000보다 작거나 같은 자연수이다. 셋째 줄부터 M개의 줄에는 합을 구해야 하는 구간 i와 j가 주어진다.

출력

총 M개의 줄에 입력으로 주어진 i번째 수부터 j번째 수까지 합을 출력한다.


풀이

풀이과정

처음에는 그냥 단순하게 무지성으로 풀었는데

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

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

    int N, M;
    cin >> N >> M;
    vector<int> arr(N+1);
    for(int i=1; i<=N; i++)
        cin >> arr[i];

    //구간 입력받아서 구간합 구하기
    for(int i=0; i<M; i++){
        int a, b;
        cin >> a >> b;
        int sum = 0;
        for(int j=a; j<=b; j++){
            // printf("+%d\n", arr[j]);
            sum += arr[j];
        }
        cout << sum << endl;
    }

    return 0;
}

시간 초과가 떴다. 그래서 dp가 필요하다는 걸 깨닫고 코드를 수정했다.
for문을 불필요하게 두 번 돌리지 않도록 입력받는 즉시 누적합을 계산하도록 했다.

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

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

    int N, M;
    cin >> N >> M;
    vector<int> arr(N+1, 0);
    for(int i=1; i<=N; i++){
        int num;
        cin >> num;
        arr[i] = arr[i-1] + num;
    }

    for(int i=0; i<M; i++){
        int a, b;
        cin >> a >> b;
        cout << arr[b] - arr[a-1] << endl;
    }

    return 0;
}

근데도 계속 시간초과가 떴다...
도당췌 영문을 모르겠어서 GPT한테 물어봤더니 endl 때문이란다...
endl 은 줄 바꿈 + 출력 버퍼 flush 가 동시에 일어나는데, 반복문 안에서 endl 을 쓰면 매번 버퍼가 비워지니 매우 느려진다고 한다.
그래서 endl'\n'으로 바꿔줬다.

최종 코드

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

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

    int N, M;
    cin >> N >> M;
    vector<int> arr(N+1, 0);
    for(int i=1; i<=N; i++){
        int num;
        cin >> num;
        arr[i] = arr[i-1] + num;
    }

    for(int i=0; i<M; i++){
        int a, b;
        cin >> a >> b;
        cout << arr[b] - arr[a-1] << '\n';
    }

    return 0;
}
profile
환영합니다!

0개의 댓글