✅ 29 회차 모의고사 D-02일

🚨 강의영상링크


🚀 1차 코딩테스트 대비

  1. 백준 2941 (크로아티아 알파벳)
  2. 백준 9020 (골드바흐의 추측)
  3. 백준 11866 (요세푸스 문제 0)
  4. 백준 1026 (보물)
  5. SQL 3월에 태어난 여성 회원 목록 출력하기

👨‍🏫 COLAB

1차 풀이

⭐ 1. 백준 2941 (크로아티아 알파벳)

# 1. 알고(문자열): 백준 2941 (크로아티아 알파벳) - https://www.acmicpc.net/problem/2941
import sys
 
from io import StringIO
sys.stdin = StringIO('''ljes=njak''')
 
input = sys.stdin.readline
 
def solve():
    s = input().rstrip()
    alpabat = ['dz=', 'c=', 'c-', 'd-', 'lj', 'nj', 's=', 'z=']
    
    for token in alpabat:
        s = s.replace(token, '*')
 
    print(len(s))
    
 
solve()

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

# 2. 알고(수학): 백준 9020 (골드바흐의 추측) - https://www.acmicpc.net/problem/9020
import sys
from math import isqrt
 
from io import StringIO
sys.stdin = StringIO('''3
8
10
16''')
 
input = sys.stdin.readline
 
def solve():
    T = int(input())
    querys = [int(input()) for _ in range(T)]
    MAX = max(querys)
 
    is_prime = [True] * (MAX + 1)
    is_prime[0] = is_prime[1] = False
 
    for i in range(2, isqrt(MAX) + 1):
        if not is_prime[i]:
            continue
        is_prime[i*i: MAX+1: i] = [False] * len(range(i*i, MAX+1, i))
 
    for query in querys:
        a = b = query // 2
 
        while True:
            if is_prime[a] and is_prime[b]:
                print(a, b)
                break
            a, b = a - 1, b + 1
 
solve()

⭐ 3. 백준 11866 (요세푸스 문제 0)

# 3. 알고(자료구조): 백준 11866 (요세푸스 문제 0) - https://www.acmicpc.net/problem/11866
import sys
from collections import deque
 
from io import StringIO
sys.stdin = StringIO('''7 3''')
 
input = sys.stdin.readline
 
def solve():
    N, K = map(int, input().split())
    dq = deque(range(1, N + 1))
 
    offset = -(K - 1)
    answers = []
 
    while dq:
        dq.rotate(offset)
        answers.append(dq.popleft())
 
    print(f'<{", ".join(map(str, answers))}>')
 
solve()

⭐ 4. 백준 1026 (보물)

# 4. 알고(그리디): 백준 1026 (보물) - https://www.acmicpc.net/problem/1026
import sys
 
from io import StringIO
sys.stdin = StringIO('''9
5 15 100 31 39 0 0 3 26
11 12 13 2 3 4 5 9 1''')
 
input = sys.stdin.readline
 
def solve():
    N = int(input())
 
    A = sorted(map(int, input().split()))
    B = sorted(map(int, input().split()), reverse=True)
 
    print(sum(a * b for a, b in zip(A, B)))
 
solve()

✏️ 5. SQL 3월에 태어난 여성 회원 목록 출력하기

-- 5. SQL(Lv.2): 3월에 태어난 여성 회원 목록 출력하기 - https://school.programmers.co.kr/learn/courses/30/lessons/131120
SELECT
    MEMBER_ID,
    MEMBER_NAME,
    GENDER,
    DATE_FORMAT(DATE_OF_BIRTH, '%Y-%m-%d' ) AS DATE_OF_BIRTH
FROM
    MEMBER_PROFILE
WHERE
    MONTH(DATE_OF_BIRTH) = 3
    AND TLNO IS NOT NULL
    AND GENDER = 'W'
ORDER BY
    MEMBER_ID ASC;

🚀 2차 코딩테스트 대비

  1. 백준 23291 (어항 정리)
  2. 백준 14725 (개미굴)
  3. 백준 1162 (도로포장)
  4. 백준 17281 (⚾)
  5. SQL 연간 평가점수에 해당하는 평가 등급 및 성과금 조회하기

👨‍🏫 COLAB

2차 풀이

⭐ 1. 백준 23291 (어항 정리)

# 1. 알고(시뮬): 백준 23291 (어항 정리) - https://www.acmicpc.net/problem/23291
import sys
from itertools import zip_longest
 
from io import StringIO
sys.stdin = StringIO('''16 0
1 1 10000 1 2 3 10000 9999 10 9 8 10000 5 4 3 1''')
 
input = sys.stdin.readline
 
def solve():
 
    # 90도 회전 (시계방향)
    def rotate_90(matrix):
        return list(map(list, zip(*matrix[::-1])))
 
    # 180 도 회전
    def rotate_180(matrix):
        return [row[::-1]for row in matrix[::-1]]
 
    # 물고기 수 조정
    def adjust_fish(board):
        R = len(board)
        diff = [[0] * len(board[r]) for r in range(R)]
 
        for r in range(R):
            for c in range(len(board[r])):
 
                for dr, dc in [(0, 1), (1, 0)]:
                    nr, nc = r + dr, c + dc
                    in_range = nr < R and nc < len(board[nr])
 
                    if not in_range:
                        continue
 
                    cur_fish = board[r][c]
                    nxt_fish = board[nr][nc]
 
                    d = abs(cur_fish - nxt_fish) // 5
                    if d <= 0:
                        continue
 
                    if cur_fish > nxt_fish:
                        diff[r][c] -= d
                        diff[nr][nc] += d
                    else:
                        diff[r][c] += d
                        diff[nr][nc] -= d
 
        # 동시 조정
        for r in range(R):
            for c in range(len(board[r])):
                board[r][c] += diff[r][c]
 
        return board
 
    def flatten(board):
        return [
            item
            for col in zip_longest(*board[::-1])
            for item in col if item is not None
        ]
 
    # 시작
    N, K = map(int, input().split())
    fishs = list(map(int, input().split()))
 
    count = 0
    while True:
        max_f, min_f = max(fishs), min(fishs)
 
        if (max_f - min_f) <= K:
            print(count)
            break
 
        count += 1  # 물고기 1마리씩 추가.
        for i in range(N):
            if fishs[i] == min_f:
                fishs[i] += 1
 
        board = [
            [fishs[0]],     # 처음것 올리고
            fishs[1:]     # 나머지
        ]
 
        # 1. 첫번째 접기
        while True:
            height = len(board)
            top_w = len(board[0])
            bottom_w = len(board[-1])
 
            if height > bottom_w - top_w:
                break       # 위에 못올리면
 
            rotated = rotate_90([row[:top_w] for row in board])
            rotated.append(board[-1][top_w:])  # 바닥 추가
 
            board = rotated
 
        board = adjust_fish(board)
        fishs = flatten(board)    # 복구
 
        # 2. 두번째 접기
        board = [
            fishs[N//2-1:: -1],
            fishs[N//2:]
        ]
 
        width = N//4
        rotated = rotate_180([r[:width] for r in board])
        rotated.extend([r[width:] for r in board])
 
        board = adjust_fish(rotated)
        fishs = flatten(board)
 
solve()

⭐ 2. 백준 14725 (개미굴)

# 2. 알고(트리): 백준 14725 (개미굴) - https://www.acmicpc.net/problem/14725
import sys
 
from io import StringIO
sys.stdin = StringIO('''4
2 KIWI BANANA
2 KIWI APPLE
2 APPLE APPLE
3 APPLE BANANA KIWI''')
 
input = sys.stdin.readline
 
def solve():
    N = int(input())
    trie = {}
 
    for _ in range(N):
        _, *foods = input().split()
 
        current = trie
        for food in foods:
            if food not in current:
                current[food] = {}
            # 자식 노드
            current = current[food]
 
    def dfs(cur_dict, depth):
        for key in sorted(cur_dict):
            print('--'*depth + key)
            dfs(cur_dict[key], depth + 1)
 
    dfs(trie, 0)
 
solve()

⭐ 3. 백준 1162 (도로포장)

# 3. 알고(그래프): 백준 1162 (도로포장) - https://www.acmicpc.net/problem/1162
import sys
from heapq import heappush, heappop
 
from io import StringIO
sys.stdin = StringIO('''4 4 1
1 2 10
2 4 10
1 3 1
3 4 100''')
 
input = sys.stdin.readline
 
def solve():
 
    N, M, K = map(int, input().split())
    graph = [[] for _ in range(N + 1)]
 
    for _ in range(M):
        a, b, c = map(int, input().split())
        graph[a].append((b, c))
        graph[b].append((a, c))
 
    pq = [(0, 1, K)]    # 거리, 노드, 포장 기회
    min_dist = [[float('inf')] * (N + 1) for _ in range(K + 1)]
    min_dist[K][1] = 0
 
    while pq:
        cur_dist, cur, wrap = heappop(pq)
 
        if cur_dist > min_dist[wrap][cur]:
            continue
 
        for nxt, cost in graph[cur]:
 
            # 포장 사용
            if wrap > 0 and cur_dist < min_dist[wrap-1][nxt]:
                min_dist[wrap - 1][nxt] = cur_dist
                heappush(pq, (cur_dist, nxt, wrap - 1))
 
            nxt_dist = cur_dist + cost
            if nxt_dist >= min_dist[wrap][nxt]:
                continue
 
            min_dist[wrap][nxt] = nxt_dist
            heappush(pq, (nxt_dist, nxt, wrap))
 
    print(min(row[N] for row in min_dist))
 
solve()

⭐ 4. 백준 17281 (⚾)

# 4. 알고(시뮬): 백준 17281 (야구) - https://www.acmicpc.net/problem/17281
import sys
from itertools import permutations
 
from io import StringIO
sys.stdin = StringIO('''2
4 3 2 1 0 4 3 2 1
1 2 3 4 1 2 3 4 0''')
 
input = sys.stdin.readline
 
def solve():
    # PyPy3 제출 필수
 
    N = int(input())
    enings = [
        (0,) + tuple(map(int, input().split()))
        for _ in range(N)
    ]  # 1 인덱스
 
    max_score = 0
 
    for permu in permutations(range(2, 10), 8):
        entry = permu[:3] + (1,) + permu[3:]
 
        hitter = 0
        score = 0
        for ening in enings:
 
            out = 0
            b1 = b2 = b3 = 0
 
            while out < 3:
                result = ening[entry[hitter]]
                hitter = (hitter + 1) % 9
 
                if result == 0:
                    out += 1
                elif result == 1:
                    score += b3
                    b1, b2, b3 = 1, b1, b2
                elif result == 2:
                    score += b2 + b3
                    b1, b2, b3 = 0, 1, b1
                elif result == 3:
                    score += b1 + b2 + b3
                    b1, b2, b3 = 0, 0, 1
                elif result == 4:
                    score += b1 + b2 + b3 + 1
                    b1 = b2 = b3 = 0
 
        max_score = max(max_score, score)
 
    # PyPy3 제출 필수
    print(max_score)
 
solve()

✏️ 5. SQL 연간 평가점수에 해당하는 평가 등급 및 성과금 조회하기

-- 5. SQL(Lv.4): 연간 평가점수에 해당하는 평가 등급 및 성과금 조회하기 
-- https://school.programmers.co.kr/learn/courses/30/lessons/284528
WITH
    HG AS (
        SELECT
            EMP_NO,
            CASE    
                WHEN AVG(SCORE) >= 96 THEN 'S'
                WHEN AVG(SCORE) >= 90 THEN 'A'
                WHEN AVG(SCORE) >= 80 THEN 'B'
                ELSE 'C'
            END AS GRADE,
            CASE    
                WHEN AVG(SCORE) >= 96 THEN 20
                WHEN AVG(SCORE) >= 90 THEN 15
                WHEN AVG(SCORE) >= 80 THEN 10
                ELSE 0
            END AS P
        FROM 
            HR_GRADE
        GROUP BY
            EMP_NO
    )
SELECT
    EMP_NO,
    EMP_NAME,
    GRADE,
    ROUND(P*SAL/100) AS BONUS
FROM HG
JOIN HR_EMPLOYEES USING (EMP_NO)
ORDER BY EMP_NO ASC;