๐Ÿ’ญ Problem Solving

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][C++] ์ฒด์œก๋ณต

0=2. 2024. 5. 24. 16:51

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/42862

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

1. ๋ชจ๋“  ํ•™์ƒ๋“ค์˜ ์ฒด์œก๋ณต ์ˆ˜ ๊ณ„์‚ฐ
    (1) ์ฒ˜์Œ์— ๋ชจ๋“  ํ•™์ƒ๋“ค์€ 1๊ฐœ์˜ ์ฒด์œก๋ณต์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค.
    (2) ์—ฌ๋ฒŒ์˜ ์ฒด์œก๋ณต์ด ์žˆ๋Š” ํ•™์ƒ: +1
    (3) ์ฒด์œก๋ณต์„ ๋„๋‚œ๋‹นํ•œ ํ•™์ƒ: -1
2. 1๋ฒˆ ํ•™์ƒ๋ถ€ํ„ฐ ์ฒด์œก๋ณต์„ ๋นŒ๋ฆฌ๋Š” ๊ฒฝ์šฐ ๊ณ„์‚ฐ
    (1) ๋„๋‚œ๋‹นํ•œ ํ•™์ƒ(์ฒด์œก๋ณต ๊ฐœ์ˆ˜: 0)์€ ์–‘์˜†์˜ ํ•™์ƒ์—๊ฒŒ ์ฒด์œก๋ณต์„ ๋นŒ๋ฆด ์ˆ˜ ์žˆ๋Š”์ง€(์ฒด์œก๋ณต ๊ฐœ์ˆ˜: 2) ํ™•์ธํ•œ๋‹ค.
    (2) ์™ผ์ชฝ ํ•™์ƒ์—๊ฒŒ ์šฐ์„ ์ ์œผ๋กœ ๋นŒ๋ฆฐ๋‹ค.

 

๐Ÿšจ ์ „์ฒด ํ•™์ƒ ์ธ๋ฑ์Šค ์œ ์˜

  • ํ•™์ƒ ๋ฒˆํ˜ธ๊ฐ€ 1๋ฒˆ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋ฏ€๋กœ  n + 1
  • n๋ฒˆ์งธ ํ•™์ƒ์ด ์˜ค๋ฅธ์ชฝ ํ•™์ƒ์„ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์กด์žฌํ•˜๋ฏ€๋กœ n + 2

์ฝ”๋“œ

#include <iostream>
#include <vector>

using namespace std;

int solution(int n, vector<int> lost, vector<int> reserve) {
    int answer = n;
    vector<int> clothes(n + 2, 1);  // ์ฒ˜์Œ ํ•™์ƒ์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์ฒด์œก๋ณต ์ˆ˜: 1

    for (int i: reserve) {   // ์—ฌ๋ฒŒ์˜ ์ฒด์œก๋ณต์ด ์žˆ๋Š” ํ•™์ƒ
        clothes[i]++;
    }
    for (int i: lost) {  // ์ฒด์œก๋ณต์„ ๋„๋‚œ๋‹นํ•œ ํ•™์ƒ
        clothes[i]--;
    }

    for (int i = 1; i <= n; i++) {
        if (clothes[i]) { // ์ฒด์œก๋ณต์ด ์žˆ์Œ
            continue;
        }
        if (clothes[i - 1] == 2) {    // ์™ผ์ชฝ ํ•™์ƒ์—๊ฒŒ ๋นŒ๋ฆฌ๊ธฐ
            clothes[i - 1]--;
            clothes[i]++;
        } else if (clothes[i + 1] == 2) { // ์˜ค๋ฅธ์ชฝ ํ•™์ƒ์—๊ฒŒ ๋นŒ๋ฆฌ๊ธฐ
            clothes[i + 1]--;
            clothes[i]++;
        }
    }

    for (int i = 1; i <= n; i++) {
        if (!clothes[i]) {
            answer--;
        }
    }

    return answer;
}