[C++] 백준 1806 - 부분합

메르센고수·2023년 8월 20일
0

Baekjoon

목록 보기
22/48

문제 - 부분합 (Gold 4)

[백준 1806] https://www.acmicpc.net/problem/1806

풀이 전략

  • 투포인터 알고리즘을 이용해서 부분합을 구한다.
  • count를 세야하기 때문에 vector의 index에 유의한다.
  • 입력한 값을 다 더한 뒤, 제일 앞 인덱스를 이동시키면서 제일 앞 index까지의 값들을 더한 값을 전체에서 빼는 방식 사용

소스 코드

#include <iostream>
#include <vector>
using namespace std;

int main(void){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int N,S;
    cin>>N>>S;
    
    vector<int> A(N);

    for(int i=0;i<N;i++){
        cin>>A[i];
    }
    int min_count=N+1; // min_count 초기화
    int start=0, end=0;
    int sum=0;

    while(end<N){
        sum+=A[end];
        // 일단 end포인터까지의 값을 전부 더함

        while(sum>=S){
            min_count=min(min_count,end-start+1);
            sum-=A[start]; // start 포인터까지의 값을 빼줌
            start++;
        }
        end++;
    } // index가 N-1까지이므로 end 포인터가 N이 되기 전까지 반복
    if(min_count>N){
        cout<<0<<'\n'; // 값을 구할 수 없으면 0 출력
    }else{
        cout<<min_count<<'\n';
    }
    return 0;
}

결과

profile
블로그 이전했습니다 (https://phj6724.tistory.com/)

0개의 댓글