[BOJ] 1644๋ฒˆ | ์†Œ์ˆ˜์˜ ์—ฐ์†ํ•ฉ (C++)

2024. 2. 7. 18:58ใ†Coding Test/BOJ

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

1644๋ฒˆ: ์†Œ์ˆ˜์˜ ์—ฐ์†ํ•ฉ

์ฒซ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 4,000,000)

www.acmicpc.net

 

๐Ÿ‘จ‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

  1. 2๋ถ€ํ„ฐ N๊นŒ์ง€ ์†Œ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” "์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด" ์•Œ๊ณ ๋ฆฌ์ฆ˜
  2. 1๋ฒˆ์—์„œ ๊ตฌํ•œ ์†Œ์ˆ˜๋“ค์˜ ๋ˆ„์ ํ•ฉ์„ ์ €์žฅํ•ด ๋‘” ๋ฐฐ์—ด
  3. ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ถ€๋ถ„ ๊ตฌ๊ฐ„์„ ์ด๋™ํ•ด๊ฐ€๋ฉฐ, N์ด ๋‚˜์˜ค๋Š” ๊ตฌ๊ฐ„์˜ ๊ฐœ์ˆ˜๋ฅผ ์นด์šดํŠธ

 

์œ„ ์ˆœ์„œ๋Œ€๋กœ ์ €๋Š” ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค. ํˆฌ ํฌ์ธํ„ฐ์™€ ๊ด€๋ จ๋œ ์†Œ์Šค ์ฝ”๋“œ๋Š” ๋งŽ์ด ์ž‘์„ฑํ•ด๋ณด์ง€ ์•Š์•„์„œ ๊ทธ๋Ÿฐ์ง€, ์งœ๋Š” ๋ฐ์— ์กฐ๊ธˆ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋„ค์š”.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <iostream>
#include <vector>

using namespace std;
#define FAST_IO ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL);

int main()
{
    FAST_IO
    int N;
    cin >> N;

    // 1. N๊นŒ์ง€์˜ ๋ชจ๋“  ์†Œ์ˆ˜ ๊ตฌํ•˜๊ธฐ (์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด)
    vector<bool> isPrimeNumbers(N + 1, true);
    isPrimeNumbers[0] = isPrimeNumbers[1] = false;

    for (int i = 2; i * i <= N; i++)
    {
        if (isPrimeNumbers[i])
        {
            for (int k = i * i; k <= N; k += i)
                isPrimeNumbers[k] = false;
        }
    }

    // 2. ์†Œ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ๋ˆ„์ ํ•ฉ ๋ฐฐ์—ด ๋งŒ๋“ค๊ธฐ
    vector<int> accumulatedPrimeNumbers { 0 };
    for (int i = 2; i <= N; i++)
        if (isPrimeNumbers[i])
            accumulatedPrimeNumbers.push_back(accumulatedPrimeNumbers.back() + i);

    // 3. ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ํ†ตํ•ด, ์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•˜๋Š” ์ˆ˜์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜ ์ฐพ๊ธฐ
    int left = 0, right = 1, end = accumulatedPrimeNumbers.size() - 1, answer = 0;
    while (left < end)
    {
        while (right < end and accumulatedPrimeNumbers[right] - accumulatedPrimeNumbers[left] < N)
            right++;

        while (left < right and accumulatedPrimeNumbers[right] - accumulatedPrimeNumbers[left] >= N)
        {
            if (accumulatedPrimeNumbers[right] - accumulatedPrimeNumbers[left] == N)
                answer++;
            left++;
        }

        // right๋ฅผ ๋๊นŒ์ง€ ๋‹ค ๋ณด๋ƒˆ๋Š”๋ฐ ์—ฐ์†ํ•ฉ์ด N๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ, ๋ฃจํ”„๋ฅผ ๋๋‚ด์ฃผ๊ธฐ ์œ„ํ•ด left++
        if (right == end)
            left++;
    }

    cout << answer;
    return 0;
}

 

 

728x90
๋ฐ˜์‘ํ˜•