[C++] 2003 BOJ 수들의 합 2

2021. 4. 10. 13:16ssh$/알고리즘

https://www.acmicpc.net/problem/2003

 

2003번: 수들의 합 2

첫째 줄에 N(1 ≤ N ≤ 10,000), M(1 ≤ M ≤ 300,000,000)이 주어진다. 다음 줄에는 A[1], A[2], …, A[N]이 공백으로 분리되어 주어진다. 각각의 A[x]는 30,000을 넘지 않는 자연수이다.

www.acmicpc.net

 

Memo


  • 투포인터
  • 어렵당..

Code


제출 날짜

@2021/04/08

메모리

2176 KB

시간

0 ms

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

int N, M, result;
std::vector<int> arr;

void output()
{
    std::cout << result;
}

void solution()
{
    int start = 0, end = 0, sum = 0;

    for(;;)
    {
        if (sum >= M)
        {
            sum -= arr[start];
            ++start;
        }
        else if (end == N)
            break;
        else
        {
            sum += arr[end];
            ++end;
        }

        if (sum == M)
            ++result;
    }
}

void input()
{
    std::cin >> N >> M;
    arr.resize(N);
    for(auto& i : arr)
        std::cin >> i;
}

void preset()
{
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::cout.tie(NULL);
}

int main()
{
    preset();
    input();
    solution();
    output();
}

'ssh$ > 알고리즘' 카테고리의 다른 글

양념 반 후라이드 반  (0) 2021.04.10
BOJ) 2193 이친수 <C++>  (0) 2021.01.27
BOJ) 1932 정수 삼각형 <C++>  (0) 2021.01.27
BOJ) 1149 RGB거리 <C++>  (0) 2021.01.24
BOJ) 11726 2xn 타일링 <C++>  (0) 2021.01.22