[백준] 2003번 수들의 합2

Peace·2021년 4월 18일

[백준] 2003번 수들의 합2

문제 링크: https://www.acmicpc.net/problem/2003

문제

입출력

문제 접근

투 포인터 문제이다.
한 배열에 두 개의 포인터를 설정해 하나는 start를 가르키고, 하나는 end를 가르켜준다. 그래서 구간의 합이 target num이랑 같으면 cnt를 하나 늘려주고, start와 num 둘 다 하나씩 늘려주고, 작으면, end를 늘려주어 범위를 늘려준다. 만약 크다면, start를 늘려주어 범위를 줄여준다.

코드 구현(c++)

#include <iostream>

using namespace std;
int nums[10001];
int N,M;

int cal(int start, int end){
    int sum = 0;
    for(int i = start ; i <= end ; i++){
        sum += nums[i];
    }
    return sum;
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);cout.tie(NULL);

    
    cin >> N >> M;
   
    int start,end;
    for(int i = 0 ; i < N ; i++){
        cin >> nums[i];
    }
    start = 0 ; end = 0;
    int checkNum;
    int cnt = 0;
    while(end < N){
        checkNum = cal(start, end);
        if(checkNum == M) {
            cnt++;
            end++;
            start++;
        }
        else if(checkNum < M){
            end++;
        }
        else{
            start++;
        }
    }
    cout << cnt << "\n";

}
profile
https://peace-log.tistory.com 로 이사 중

0개의 댓글