✅ 30 회차 모의고사 D-01일

🚨 강의영상링크


🚀 1차 코딩테스트 대비

  1. 백준 2108 (통계학)
  2. 백준 6588 (골드바흐의 추측)
  3. 백준 10773 (제로)
  4. 백준 4796 (캠핑)
  5. SQL 대장균의 크기에 따라 분류하기 2

👨‍🏫 COLAB

1차 풀이

⭐ 1. 백준 2108 (통계학)

# 1. 알고(정렬): 백준 2108 (통계학) - https://www.acmicpc.net/problem/2108
import sys
from collections import Counter
 
from io import StringIO
sys.stdin = StringIO('''5
1
3
8
-2
2''')
 
input = sys.stdin.readline
 
def solve():
    N = int(input())
    nums = sorted(int(input()) for _ in range(N))
 
    count = Counter(nums)  # 삽입 순서 유지
    max_count = max(count.values())
    max_keys = [key for key, value in count.items() if value == max_count]
    avg = sum(nums)/N
 
    print(int(avg + 0.5) if avg >= 0 else int(avg - 0.5))   # 반올림 주의 사오사입
    print(nums[N//2])
    print(max_keys[0] if len(max_keys) == 1 else max_keys[1])
    print(nums[-1] - nums[0])
 
solve()

⭐ 2. 백준 6588 (골드바흐의 추측)

# 2. 알고(수학): 백준 6588 (골드바흐의 추측) - https://www.acmicpc.net/problem/6588
import sys
from math import isqrt
 
from io import StringIO
sys.stdin = StringIO('''8
20
42
0''')
 
input = sys.stdin.readline
 
def solve():
    querys = []
 
    while True:
        n = int(input())
        if n == 0:
            break
        querys.append(n)
 
    MAX = max(querys)
 
    is_primes = [True] * (MAX + 1)
    is_primes[0] = is_primes[1] = False
 
    for i in range(2, isqrt(MAX) + 1):
        if not is_primes[i]:
            continue
        is_primes[i*i::i] = [False] * len(range(i*i, MAX + 1, i))
 
    out = []
    for query in querys:
        for a in range(3, query//2 + 1, 2):
            if is_primes[a] and is_primes[query - a]:
                out.append(f"{query} = {a} + {query - a}")
                break
        else:
            out.append("Goldbach's conjecture is wrong.")
 
    print("\n".join(out))
 
solve()

⭐ 3. 백준 10773 (제로)

# 3. 알고(자료구조): 백준 10773 (제로) - https://www.acmicpc.net/problem/10773
import sys
 
from io import StringIO
sys.stdin = StringIO('''10
1
3
5
4
0
0
7
0
0
6''')
 
input = sys.stdin.readline
 
def solve():
    K = int(input())
 
    stack = []
    for _ in range(K):
        num = int(input())
        if num == 0:
            stack.pop()
        else:
            stack.append(num)
 
    print(sum(stack))
 
solve()

⭐ 4. 백준 4796 (캠핑)

# 4. 알고(그리디): 백준 4796 (캠핑) - https://www.acmicpc.net/problem/4796
import sys
 
from io import StringIO
sys.stdin = StringIO('''5 8 20
5 8 17
0 0 0''')
 
input = sys.stdin.readline
 
def solve():
 
    out = []
 
    while True:
        L, P, V = map(int, input().split())
        if (L, P, V) == (0, 0, 0):
            break
 
        q, r = divmod(V, P)
        answer = q * L + min(L, r)
        out.append(answer)
 
    print("\n".join(f"Case {i}: {v}" for i, v in enumerate(out, 1)))
 
solve()

✏️ 5. SQL 대장균의 크기에 따라 분류하기 2

-- 5. SQL(Lv.3): 대장균의 크기에 따라 분류하기 2 - https://school.programmers.co.kr/learn/courses/30/lessons/301649
 
WITH 
    T AS (
        SELECT
            ID,
            NTILE(4) OVER(ORDER BY SIZE_OF_COLONY DESC) AS TIER
        FROM ECOLI_DATA    
    )
SELECT
    ID,
    CASE
        WHEN TIER = 1 THEN 'CRITICAL'
        WHEN TIER = 2 THEN 'HIGH'
        WHEN TIER = 3 THEN 'MEDIUM'
        WHEN TIER = 4 THEN 'LOW'
    END AS COLONY_NAME
FROM T
ORDER BY ID ASC;

🚀 2차 코딩테스트 대비

  1. 백준 17825 (주사위 윷놀이)
  2. 백준 1509 (팰린드롬 분할)
  3. 백준 11438 (LCA 2)
  4. 백준 13460 (구슬 탈출 2)
  5. SQL 언어별 개발자 분류하기

👨‍🏫 COLAB

2차 풀이

⭐ 1. 백준 17825 (주사위 윷놀이)

# 1. 알고(시뮬): 백준 17825 (주사위 윷놀이) - https://www.acmicpc.net/problem/17825
import sys
from collections import defaultdict
 
from io import StringIO
sys.stdin = StringIO('''1 2 3 4 1 2 3 4 1 2''')
 
input = sys.stdin.readline
 
def solve():
 
     # 10(왼), 20(아래), 25(센터), 30(오), 40(위) 그대로
    OUT = [i for i in range(0, 43, 2)] + [42]   # 42 다음은 42
    RIGHT = [10, 113, 116, 119, 25]    
    UP = [20, 222, 224, 25, 230, 235, 40]          
    LEFT = [30, 328, 327, 326, 25]
 
    graph = defaultdict(list)
    
    for path in (OUT, RIGHT, UP, LEFT):
        for i in range(len(path) - 1):
            graph[path[i]].append(path[i + 1])
 
    def get_score(pos):
        if pos == 42: return 0
        return pos % 100
 
    def move(pos, steps):
 
        if len(graph[pos]) > 1: 
            pos = graph[pos][1] 
        else:
            pos = graph[pos][0]
 
        for _ in range(steps - 1):
            pos = graph[pos][0]
 
        return pos
 
    dice = tuple(map(int, input().split()))
    horses = [0] * 4
    max_score = 0
 
    def dfs(turn, total):
        nonlocal max_score
 
        if turn == 10:
            max_score = max(max_score, total)
            return
        
        for i in range(4):
            cur_pos, cur_dice = horses[i], dice[turn]
 
            if cur_pos == 42:
                continue
            
            nxt_pos = move(cur_pos, cur_dice)
            if nxt_pos != 42 and nxt_pos in horses:
                continue
            
            horses[i] = nxt_pos
            dfs(turn + 1, total + get_score(nxt_pos))
            horses[i] = cur_pos
 
    dfs(0, 0)
 
    print(max_score)
 
solve()

⭐ 2. 백준 1509 (팰린드롬 분할)

# 2. 알고(DP): 백준 1509 (팰린드롬 분할) - https://www.acmicpc.net/problem/1509
import sys
 
from io import StringIO
sys.stdin = StringIO('''BBCDDECAECBDABADDCEBACCCBDCAABDBADD''')
 
input = sys.stdin.readline
 
def solve():
 
    S = input().rstrip()
    N = len(S)
 
    is_pal = [[False] * N for _ in range(N)]
 
    for i in range(N):
        is_pal[i][i] = True
    
    for i in range(N-1):
        is_pal[i][i+1] = S[i] == S[i+1]
    
    for length in range(3, N+1):
        for i in range(N - length + 1):
            j = i + length - 1
            is_pal[i][j] = S[i] == S[j] and is_pal[i+1][j-1]
    
    # dp[end] = S[0:end] 를 팰린드롬 분할 시 나오는 최소 분할
    dp = [float('inf')] * (N + 1)
    dp[0] = 0
 
    for end in range(1, N + 1):
        for start in range(end):
            if not is_pal[start][end-1]:
                continue
            dp[end] = min(dp[end], dp[start] + 1)
 
    print(dp[N])
 
solve()

⭐ 3. 백준 11438 (LCA 2)

# 3. 알고(트리): 백준 11438 (LCA 2) - https://www.acmicpc.net/problem/11438
 
import sys
from math import log2
from itertools import product
 
from io import StringIO
sys.stdin = StringIO('''15
1 2
1 3
2 4
3 7
6 2
3 8
4 9
2 5
5 11
7 13
10 4
11 15
12 5
14 7
6
6 11
10 9
2 6
7 6
8 13
8 15''')
 
input = sys.stdin.readline
 
def solve():
    N = int(input())
    graph = [[] for _ in range(N + 1)]
 
    for _ in range(N - 1):
        a, b, = map(int, input().split())
        graph[a].append(b)
        graph[b].append(a)
 
    LOG = int(log2(N)) + 1
 
    # parent[k][n] : n의 2^k 번째 부모
    depth = [-1] * (N + 1)  # visited 기능
    depth[1] = 0
 
    parent = [[0] * (N + 1) for _ in range(LOG)]
 
    stack = [1]
    while stack:
        cur = stack.pop()
 
        for nxt in graph[cur]:
            if depth[nxt] != -1:
                continue
 
            parent[0][nxt] = cur
            stack.append(nxt)
            depth[nxt] = depth[cur] + 1
 
    for k, n in product(range(1, LOG), range(1, N + 1)):
        parent[k][n] = parent[k-1][parent[k-1][n]]
 
    def lca(a, b):
        if depth[a] > depth[b]:  # b 를 깊게 만듬
            a, b, = b, a
 
        diff = depth[b] - depth[a]
        for k in range(LOG):
            if (diff >> k) & 1:
                b = parent[k][b]
 
        if a == b:
            return a
 
        for k in range(LOG - 1, -1, -1):
            if parent[k][a] != parent[k][b]:
                a = parent[k][a]
                b = parent[k][b]
 
        return parent[0][a]
 
    M = int(input())
 
    out = []
    for _ in range(M):
        a, b = map(int, input().split())
        out.append(lca(a, b))
 
    print("\n".join(map(str, out)))
 
solve()

⭐ 4. 백준 13460 (구슬 탈출 2)

# 4. 알고(시뮬): 백준 13460 (구슬 탈출 2) - https://www.acmicpc.net/problem/13460
import sys
from itertools import product
from collections import deque
 
from io import StringIO
sys.stdin = StringIO('''10 10
##########
#R#...##B#
#...#.##.#
#####.##.#
#......#.#
#.######.#
#.#....#.#
#.#.##...#
#O..#....#
##########''')
 
input = sys.stdin.readline
 
def solve():
    N, M = map(int, input().split())
    board = [list(input().strip()) for _ in range(N)]
 
    def move(r, c, dr, dc):
        dist = 0
 
        while board[r + dr][c + dc] != '#':
            dist += 1
            r, c = r + dr, c + dc
            if board[r][c] == 'O':  # 구멍에 도착하면 즉시 중단
                break
 
        return r, c, dist
 
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    rr = rc = br = bc = 0
 
    for r, c in product(range(N), range(M)):
        val = board[r][c]
        if val == 'R':
            rr, rc = r, c
        elif val == 'B':
            br, bc = r, c
 
    cur = (rr, rc, br, bc)
    visited = {cur}
    dq = deque([(*cur, 1)])  # 깊이
 
    while dq:
        rr, rc, br, bc, depth = dq.popleft()
 
        if depth == 11:
            break
 
        for dr, dc in directions:
            nrr, nrc, r_dist = move(rr, rc, dr, dc)
            nbr, nbc, b_dist = move(br, bc, dr, dc)
 
            if board[nbr][nbc] == 'O':  # 파란색 빠지면 안됨.
                continue
 
            if board[nrr][nrc] == 'O':  # 빨강이면 성공.
                return print(depth)
 
            if (nrr, nrc) == (nbr, nbc):  # 겹친상황
 
                # 이동거리가 긴쪽 하나 빼줌
                if r_dist > b_dist:
                    nrr, nrc = nrr - dr, nrc - dc
                else:
                    nbr, nbc = nbr - dr, nbc - dc
 
            nxt = (nrr, nrc, nbr, nbc)
            if nxt not in visited:
                visited.add(nxt)
                dq.append((*nxt, depth + 1))
 
    print(-1)
 
solve()

✏️ 5. SQL 언어별 개발자 분류하기

-- 5. SQL(Lv.5): 언어별 개발자 분류하기 
-- https://school.programmers.co.kr/learn/courses/30/lessons/276036
WITH 
    FE AS (
        SELECT SUM(CODE) AS CODE
        FROM SKILLCODES
        WHERE CATEGORY = 'Front End'
    ),
    PY AS (
        SELECT CODE
        FROM SKILLCODES
        WHERE NAME = 'Python'
    ),
    CS AS (
        SELECT CODE
        FROM SKILLCODES
        WHERE NAME = 'C#'
    ),
    GD AS (
        SELECT 
            CASE 
                WHEN (SKILL_CODE & (SELECT CODE FROM FE)) > 0 
                 AND (SKILL_CODE & (SELECT CODE FROM PY)) > 0 THEN 'A'
                WHEN (SKILL_CODE & (SELECT CODE FROM CS)) > 0 THEN 'B'
                WHEN (SKILL_CODE & (SELECT CODE FROM FE)) > 0 THEN 'C'
            END AS GRADE,
            ID,
            EMAIL
        FROM DEVELOPERS    
    )
SELECT 
    *
FROM GD
WHERE GRADE IS NOT NULL
ORDER BY GRADE, ID;