✅ 26 회차 모의고사 D-05일

🚨 강의영상링크


🚀 1차 코딩테스트 대비

  1. 백준 25206 (너의 평점은)
  2. 백준 13241 (최소공배수)
  3. 백준 10816 (숫자 카드 2)
  4. 백준 2437 (저울)
  5. SQL 부서별 평균 연봉 조회하기

👨‍🏫 COLAB

1차 풀이

⭐ 1. 백준 25206 (너의 평점은)

# 1. 알고(구현): 백준 25206 (너의 평점은) - https://www.acmicpc.net/problem/25206
import sys
 
from io import StringIO
sys.stdin = StringIO('''ObjectOrientedProgramming1 3.0 A+
IntroductiontoComputerEngineering 3.0 A+
ObjectOrientedProgramming2 3.0 A0
CreativeComputerEngineeringDesign 3.0 A+
AssemblyLanguage 3.0 A+
InternetProgramming 3.0 B0
ApplicationProgramminginJava 3.0 A0
SystemProgramming 3.0 B0
OperatingSystem 3.0 B0
WirelessCommunicationsandNetworking 3.0 C+
LogicCircuits 3.0 B0
DataStructure 4.0 A+
MicroprocessorApplication 3.0 B+
EmbeddedSoftware 3.0 C0
ComputerSecurity 3.0 D+
Database 3.0 C+
Algorithm 3.0 B0
CapstoneDesigninCSE 3.0 B+
CompilerDesign 3.0 D0
ProblemSolving 4.0 P''')
 
input = sys.stdin.readline
 
def solve():
 
    trans = {
        'A+': 4.5, 'A0': 4.0, 'B+': 3.5,
        'B0': 3.0, 'C+': 2.5, 'C0': 2.0,
        'D+': 1.5, 'D0': 1.0, 'F': 0.0
    }
 
    grade_sum = total_score = 0.0
 
    for _ in range(20):
        _, credit, grade = input().split()
        if grade == 'P':
            continue
        credit = float(credit)
        grade_sum += credit
        total_score += credit * trans[grade]
 
    print(f"{total_score/grade_sum:.6f}")
 
solve()

⭐ 2. 백준 13241 (최소공배수)

# 2. 알고(수학): 백준 13241 (최소공배수) - https://www.acmicpc.net/problem/13241
import sys
 
from io import StringIO
sys.stdin = StringIO('''121 199''')
 
input = sys.stdin.readline
 
def solve():
    a, b = map(int, input().split())
 
    product = a * b
    while b != 0:       # 유클리드 호제법
        a, b = b, a % b
    print(product // a)
 
solve()

⭐ 3. 백준 10816 (숫자 카드 2)

# 3. 알고(Map): 백준 10816 (숫자 카드 2) - https://www.acmicpc.net/problem/10816
import sys
from bisect import bisect_left, bisect_right
 
from io import StringIO
sys.stdin = StringIO('''10
6 3 2 10 10 10 -10 -10 7 3
8
10 9 -5 2 3 4 5 -10''')
 
input = sys.stdin.readline
 
def solve():
 
    N = input()
    cards = sorted(map(int, input().split()))
    M = input()
 
    def count(num):
        right_idx = bisect_right(cards, num)
        left_idx = bisect_left(cards, num)
        return right_idx - left_idx
 
    print(*[count(num) for num in map(int, input().split())])
 
solve()

⭐ 4. 백준 2437 (저울)

# 4. 알고(그리디): 백준 2437 (저울) - https://www.acmicpc.net/problem/2437
import sys
 
from io import StringIO
sys.stdin = StringIO('''7
3 1 6 2 7 30 1''')
 
input = sys.stdin.readline
 
def solve():
    N = int(input())
    grams = sorted(map(int, input().split()))
 
    reach = 0
    for gram in grams:
        if gram > reach + 1:
            return print(reach + 1)
        reach += gram
 
    print(reach + 1)
 
solve()

✏️ 5. SQL 부서별 평균 연봉 조회하기

-- 5. SQL(Lv.2): 부서별 평균 연봉 조회하기 
-- https://school.programmers.co.kr/learn/courses/30/lessons/284529
SELECT 
    DEPT_ID,
    DEPT_NAME_EN,
    ROUND(AVG(SAL)) AS AVG_SAL
FROM 
    HR_EMPLOYEES
JOIN
    HR_DEPARTMENT USING (DEPT_ID)
GROUP BY
    DEPT_ID
ORDER BY
    AVG_SAL DESC;

🚀 2차 코딩테스트 대비

  1. 백준 20057 (마법사 상어와 토네이도)
  2. 백준 1309 (동물원)
  3. 백준 1766 (문제집)
  4. 백준 4574 (스도쿠미노)
  5. SQL 오랜 기간 보호한 동물(2)

👨‍🏫 COLAB

2차 풀이

⭐ 1. 백준 20057 (마법사 상어와 토네이도)

# 1. 알고(시뮬): 백준 20057 (마법사 상어와 토네이도) - https://www.acmicpc.net/problem/20057
 
import sys
from collections import defaultdict
from itertools import product
 
from io import StringIO
sys.stdin = StringIO('''5
100 200 300 400 200
300 243 432 334 555
999 111 0 999 333
888 777 222 333 900
100 200 300 400 500''')
 
input = sys.stdin.readline
 
def solve():
    directions = [(0, -1), (+1, 0), (0, +1), (-1, 0)]   # 반시계
 
    N = int(input())
    board = [list(map(int, input().split())) for _ in range(N)]
 
    # 모래 딕셔너리에 저장
    sands_dict = defaultdict(int)
    for r, c in product(range(N), repeat=2):
        val = board[r][c]
        if val == 0:
            continue
        sands_dict[(r, c)] = val
 
    # 퍼지는 모래 준비.
    base_offset = [
        (+0, -2, 5),    # 대칭 아닌 5 것
        (-1, +1, 1), (-2, +0, 2), (-1, +0, 7), (-1, -1, 10)
    ]
 
    for r, c, ratio in base_offset[1:]:
        base_offset.append((-r, c, ratio))  # 위 아래 대칭
 
    offsets = [base_offset]  # 나머지 방향 추가
    for _ in range(3):
        base_offset = [(-c, r, ratio) for r, c, ratio in base_offset]
        offsets.append(base_offset)
 
    def run_tornado(r, c):
        step, d = 1, 0
 
        while True:
            dr, dc = directions[d]
            for _ in range(step):   # 진행 횟수
                r, c = nxt = r + dr, c + dc   # 전진
 
                if nxt == (0, -1):   # 마지막 오면 종료
                    return
 
                cur_sand = sands_dict[nxt]
                if cur_sand == 0:
                    continue
 
                spread_sum = 0
                sands_dict[nxt] = 0
 
                for sdr, sdc, ratio in offsets[d]:
                    amount = (cur_sand * ratio) // 100
                    sands_dict[(r + sdr, c + sdc)] += amount
                    spread_sum += amount
 
                alpha = (r + dr, c + dc)    # (기존 dr, dc 활용)
                sands_dict[alpha] += (cur_sand - spread_sum)
 
            if d in (1, 3):     # 아래 , 위 방향 이었다면 다음에 한칸 더 전진
                step += 1
            d = (d + 1) % 4     # 전진 다 했으니 방향 전환
 
   # 시작
    run_tornado(N // 2, N // 2)
 
    # 밖을 나간 것들
    outside = sum(
        amount for (r, c), amount in sands_dict.items()
        if not (0 <= r < N and 0 <= c < N)
    )
    print(outside)
 
solve()

⭐ 2. 백준 1309 (동물원)

# 2. 알고(DP): 백준 1309 (동물원) - https://www.acmicpc.net/problem/1309
import sys
 
from io import StringIO
sys.stdin = StringIO('''4''')
 
input = sys.stdin.readline
 
def solve():
    N = int(input())
    MOD = 9901
 
    dp = [1] * 3    # 0:empty, 1:left, 2:right
 
    for _ in range(N-1):
        val = sum(dp)
 
        empty = val % MOD
        left = (val - dp[1]) % MOD
        right = (val - dp[2]) % MOD
 
        dp[:] = empty, left, right
 
    print(sum(dp) % MOD)
 
solve()

⭐ 3. 백준 1766 (문제집)

# 3. 알고(그래프): 백준 1766 (문제집) - https://www.acmicpc.net/problem/1766
import sys
from heapq import heappop, heapify, heappush
 
from io import StringIO
sys.stdin = StringIO('''4 2
4 2
3 1''')
 
input = sys.stdin.readline
 
def solve():
    N, M = map(int, input().split())
 
    graph = [[] for _ in range(N)]
    in_degree = [0] * N
 
    for _ in range(M):
        A, B = map(lambda x: int(x) - 1, input().split())   # 0 인덱스
        graph[A].append(B)
        in_degree[B] += 1
 
    pq = [i for i, degree in enumerate(in_degree) if degree == 0]
    heapify(pq)
 
    answer = []
    while pq:
        num = heappop(pq)
        answer.append(num + 1)  # 1 인덱스
 
        for nxt in graph[num]:
            val = in_degree[nxt]
 
            if val == 0:
                continue
 
            if val == 1:
                heappush(pq, nxt)
 
            in_degree[nxt] -= 1
 
    print(*answer)
 
solve()

⭐ 4. 백준 4574 (스도쿠미노)

# 4. 알고(백트래킹): 백준 4574 (스도쿠미노) - https://www.acmicpc.net/problem/4574
import sys
from itertools import combinations
 
from io import StringIO
sys.stdin = StringIO('''10
6 B2 1 B3
2 C4 9 C3
6 D3 8 E3
7 E1 4 F1
8 B7 4 B8
3 F5 2 F6
7 F7 6 F8
5 G4 9 G5
7 I8 8 I9
7 C9 2 B9
C5 A3 D9 I4 A9 E5 A2 C6 I1
11
5 I9 2 H9
6 A5 7 A6
4 B8 6 C8
3 B5 8 B4
3 C3 2 D3
9 D2 8 E2
3 G2 5 H2
1 A2 8 A1
1 H8 3 I8
8 I3 7 I4
4 I6 9 I7
I5 E6 D1 F2 B3 G9 H7 C9 E5
0''')
 
input = sys.stdin.readline
 
def solve(N, count):
 
    board = [[0] * 9 for _ in range(9)]
 
    row_i = [[False] * 10 for _ in range(9)]
    col_i = [[False] * 10 for _ in range(9)]
    sqr_i = [[False] * 10 for _ in range(9)]
 
    # 블럭 놓기
    def place(r, c, n, state):
        s = (r // 3) * 3 + c // 3
        board[r][c] = n if state else 0
        row_i[r][n] = col_i[c][n] = sqr_i[s][n] = state
 
    # 문자 좌표 변환
    def get_pos(string):
        alpha, num = string
        row = ord(alpha) - ord('A')
        col = int(num) - 1
        return row, col
 
    # 도미노 정보
    used_d = set()
    for _ in range(N):
        n1, str1, n2, str2 = input().split()
        n1, n2 = int(n1), int(n2)
 
        place(*get_pos(str1), n1, True)
        place(*get_pos(str2), n2, True)
 
        used_d.add((min(n1, n2), max(n1, n2)))  # 정렬
 
    # 한개짜리
    for num, pos in enumerate(input().split(), 1):
        place(*get_pos(pos), num, True)
 
    # 놀수 있는지
    def can_place(r, c, n):
        s = (r // 3) * 3 + c // 3
        return not row_i[r][n] and not col_i[c][n] and not sqr_i[s][n]
 
    DOMINOES = tuple(combinations(range(1, 10), 2))  # 36개 블럭 생성
    need_search = True
 
    # 시작
    def dfs(idx):
        nonlocal need_search
 
        if not need_search:
            return
 
        if idx == 81:
            print(f"Puzzle {count}")
            print("\n".join("".join(map(str, row)) for row in board))
            need_search = False
            return
 
        r, c = divmod(idx, 9)
 
        if board[r][c] != 0:    # 이미 숫자가 있으면
            dfs(idx + 1)
            return
 
        # 오른쪽 방향, 아래 방향
        for dr, dc in [(0, 1), (1, 0)]:
            nr, nc = r + dr, c + dc
 
            if nr >= 9 or nc >= 9 or board[nr][nc] != 0:
                continue
 
            for a, b in DOMINOES:   # a < b 조합 생성 규칙
                if (a, b) in used_d:  # 사용한 건 건너뜀
                    continue
 
                for n1, n2 in ((a, b), (b, a)):
                    if can_place(r, c, n1) and can_place(nr, nc, n2):
 
                        place(r, c, n1, True)
                        place(nr, nc, n2, True)
                        used_d.add((a, b))
 
                        dfs(idx + 1)
 
                        place(r, c, n1, False)
                        place(nr, nc, n2, False)
                        used_d.remove((a, b))
 
        return None
 
    dfs(0)
 
count = 1
while True:
    N = int(input())
    if N == 0:
        break
    solve(N, count)
    count += 1

✏️ 5. SQL 오랜 기간 보호한 동물(2)

-- 5. SQL(Lv.3): 오랜 기간 보호한 동물(2) 
-- https://school.programmers.co.kr/learn/courses/30/lessons/59411
SELECT 
    ANIMAL_ID,
    O.NAME
FROM 
    ANIMAL_OUTS O
JOIN 
    ANIMAL_INS I USING (ANIMAL_ID)
ORDER BY
    DATEDIFF(O.DATETIME, I.DATETIME) DESC
LIMIT 2;