✅ 03 회차 모의고사 D-28일

🚨 강의영상링크


🚀 1차 코딩테스트 대비

  1. 백준 2564 (경비원)
  2. 백준 1358 (하키)
  3. 백준 20920 (영단어 암기는 괴로워)
  4. 백준 1343 (폴리오미노)
  5. SQL 모든 레코드 조회하기

👨‍🏫 COLAB

1차 풀이

⭐ 1. 백준 2564 (경비원)

# 1. 알고(구현): 백준 2564 (경비원) - https://www.acmicpc.net/problem/2564
 
import sys
 
from io import StringIO
sys.stdin = StringIO('''10 5
3
1 4
3 2
2 8
2 3''')
 
input = sys.stdin.readline
 
def solve():
    X, Y = map(int, input().split())
    N = int(input())
 
    positions = [tuple(map(int, input().split())) for _ in range(N + 1)]
    dists = []
 
    total_len = (X + Y) * 2
    for d, length in positions:
        if d == 1:    # 북쪽
            dists.append(length)
        elif d == 4:  # 동쪽
            dists.append(X + length)
        elif d == 2:  # 남쪽
            dists.append(X + Y + (X - length))
        elif d == 3:  # 서쪽
            dists.append(X + Y + X + (Y - length))
 
    min_sum = 0
    guard = dists[-1]
    for target in dists[:-1]:
        diff = abs(target - guard)
        min_sum += min(diff, total_len - diff)
    print(min_sum)
 
solve()

⭐ 2. 백준 1358 (하키)

# 2. 알고(수학): 백준 1358 (하키) - https://www.acmicpc.net/problem/1358
import sys
 
from io import StringIO
sys.stdin = StringIO('''24 100 -62 71 8
-63 109
-26 164
-9 91
-113 80
-124 75
-95 140
-89 116
-55 113''')
 
input = sys.stdin.readline
 
def solve():
    W, H, X, Y, P = map(int, input().split())
    peoples = [tuple(map(int, input().split())) for _ in range(P)]
 
    radius = H // 2
    r_sq = radius**2
 
    left_center = (X, Y + radius)
    right_center = (X + W, Y + radius)
 
    def get_dist(a, b):
        return (a[0] - b[0])**2 + (a[1] - b[1])**2
 
    count = 0
    for people in peoples:
        px, py = people
 
        in_rect = (X <= px <= X + W) and (Y <= py <= Y + H)
        in_left_circle = get_dist(people, left_center) <= r_sq
        in_right_circle = get_dist(people, right_center) <= r_sq
 
        if in_rect or in_left_circle or in_right_circle:
            count += 1
 
    print(count)
 
solve()

⭐ 3. 백준 20920 (영단어 암기는 괴로워)

# 3. 알고(Map): 백준 20920 (영단어 암기는 괴로워) - https://www.acmicpc.net/problem/20920
import sys
from collections import defaultdict 
 
from io import StringIO
sys.stdin = StringIO('''12 5
appearance
append
attendance
swim
swift
swift
swift
mouse
wallet
mouse
ice
age''')
 
input = sys.stdin.readline
 
def solve():
 
    N, M = map(int, input().split())
    count_dict = defaultdict(int)
 
    for _ in range(N):
        word = input().rstrip()
        if len(word) >= M:
             count_dict[word] += 1
    
    lst = list(count_dict.items())
    lst.sort(key=lambda x: (-x[1], -len(x[0]), x[0]))
 
    print("\n".join(map(lambda x: x[0], lst)))
 
solve()

⭐ 4. 백준 1343 (폴리오미노)

# 4. 알고(그리디): 백준 1343 (폴리오미노) - https://www.acmicpc.net/problem/1343
import sys
 
from io import StringIO
sys.stdin = StringIO('''XX.XXXXXXXXXX..XXXXXXXX...XXXXXX''')
 
input = sys.stdin.readline
 
def solve():
 
    S = input().rstrip()
 
    info = []
    counter = 0
    for i, c in enumerate(S):
        if c == '.':
            info.append('.')
        else:
            counter += 1
            if i + 1 == len(S) or S[i + 1] == '.':
                info.append(counter)
                counter = 0
 
    result = []
    for i in info:
        if i == '.':
            result.append('.')
        else:
            a = i // 4
            b = i % 4
            
            if b == 1 or b == 3:
                print(-1)
                return
            
            result.extend('AAAA' * a + 'BB' * (b//2))
 
    print("".join(result))
 
solve()

✏️ 5. SQL 모든 레코드 조회하기

-- 5. SQL(Lv.1): 모든 레코드 조회하기 
-- https://school.programmers.co.kr/learn/courses/30/lessons/59034
SELECT
    ANIMAL_ID,
    ANIMAL_TYPE,
    DATETIME,
    INTAKE_CONDITION,
    NAME,
    SEX_UPON_INTAKE
FROM
    ANIMAL_INS
ORDER BY
    ANIMAL_ID;

🚀 2차 코딩테스트 대비

  1. 백준 15683 (감시)
  2. 백준 1535 (안녕)
  3. 백준 4485 (녹색 옷 입은 애가 젤다지?)
  4. 백준 1987 (알파벳)
  5. SQL 조회수가 가장 많은 중고거래 게시판의 첨부파일 조회하기

👨‍🏫 COLAB

2차 풀이

⭐ 1. 백준 15683 (감시)

# 1. 알고(시뮬): 백준 15683 (감시) - https://www.acmicpc.net/problem/15683
import sys
 
from io import StringIO
sys.stdin = StringIO('''6 6
0 0 0 0 0 0
0 2 0 0 0 0
0 0 0 0 6 0
0 6 0 0 2 0
0 0 0 0 0 0
0 0 0 0 0 5''')
 
input = sys.stdin.readline
 
# [i] : [0]상, [1]우, [2]하, [3]좌
dr = (-1, 0, 1, 0)
dc = (0, 1, 0, -1)
 
base_dirs = [
    (1, ),
    (1, 3),
    (0, 1),
    (0, 1, 3),
    (0, 1, 2, 3)
]
 
def solve():
    N, M = map(int, input().split())
    board = [list(map(int, input().split())) for _ in range(N)]
    min_val = sys.maxsize
 
    # 회전 방향 저장.
    dirs_modes = [[]]
    for dirs in base_dirs:
        temp_set = set()
        for i in range(4):  # 90도 회전 i 번,
            rotate_cctv = [(d + i) % 4 for d in dirs]
            rotate_cctv.sort()  # 중복제거를 위해 정렬 후 set(사용)
            temp_set.add(tuple(rotate_cctv))
        dirs_modes.append(list(temp_set))
 
    # CCTV 좌표와 카메라 type
    cctvs = [
        (r, c, board[r][c])
        for c in range(M)
        for r in range(N)
        if 1 <= board[r][c] <= 5
    ]
 
    # 감시대상은 val = -1, 복구는 +1
    def update(r, c, dirs, val):
        for d in dirs:  # 정해진 방향
            nr, nc = r, c
 
            while True:
                nr += dr[d]
                nc += dc[d]
                vaild_idx = (0 <= nr < N) and (0 <= nc < M)
 
                if not vaild_idx or board[nr][nc] == 6:
                    break                # 멈춤조건,
                if board[nr][nc] <= 0:
                    board[nr][nc] += val  # 카메라 통과.
 
    def dfs(depth):
        nonlocal min_val
 
        if depth == len(cctvs):
            sum_value = sum(row.count(0) for row in board)
            if sum_value < min_val:
                min_val = sum_value
            return
 
        r, c, cctv_type = cctvs[depth]
        for mode in dirs_modes[cctv_type]:
            update(r, c, mode, -1)
            dfs(depth + 1)
            update(r, c, mode, +1)
 
    dfs(0)
    print(min_val)
 
solve()

⭐ 2. 백준 1535 (안녕)

# 2. 알고(DP): 백준 1535 (안녕) - https://www.acmicpc.net/problem/1535
import sys
 
from io import StringIO
sys.stdin = StringIO('''8
100 26 13 17 24 33 100 99
34 56 21 1 24 34 100 99''')
 
input = sys.stdin.readline
 
def solve():
 
    N = int(input())
    L = list(map(int, input().split()))
    J = list(map(int, input().split()))
 
    LIMIT = 99
    dp = [0] * (LIMIT + 1)  # dp[health] = 체력을 사용해 최대로 얻을 수 있는 즐거움
 
    for i in range(N):
        cost_h = L[i]
        get_joy = J[i]
 
        for h in range(LIMIT, cost_h - 1, -1):
            dp[h] = max(dp[h], get_joy + dp[h - cost_h])
 
    print(dp[LIMIT])
 
solve()

⭐ 3. 백준 4485 (녹색 옷 입은 애가 젤다지?)

# 3. 알고(그래프): 백준 4485 (녹색 옷 입은 애가 젤다지?) - https://www.acmicpc.net/problem/4485
import sys
from heapq import heappush, heappop
 
from io import StringIO
sys.stdin = StringIO('''3
5 5 4
3 9 1
3 2 7
5
3 7 2 0 1
2 8 0 9 1
1 2 1 8 1
9 8 9 2 0
3 6 5 1 5
7
9 0 5 1 1 5 3
4 1 2 1 6 5 3
0 7 6 1 6 8 5
1 1 7 8 3 2 3
9 4 0 7 6 4 1
5 8 3 2 4 8 3
7 4 8 4 8 3 4
0''')
 
input = sys.stdin.readline
 
def solve(n, count):
    grid = [tuple(map(int, input().split())) for _ in range(n)]
    directions = [(-1, 0), (0, +1), (+1, 0), (0, -1)]
 
    # 시작 (0, 0) 에서 (n, n) 까지 최소 루피
    INF = sys.maxsize
    min_rupee = [[INF] * n for _ in range(n)]
 
    pq = [(grid[0][0], (0, 0))]  # (차감 루피, (r, c) )
    min_rupee[0][0] = grid[0][0]
 
    while pq:
        cur_cost, (r, c) = heappop(pq)
        if cur_cost > min_rupee[r][c]:
            continue
        
        for dr, dc in directions:
            nr, nc = r + dr, c + dc
            if (0 <= nr < n) and (0 <= nc < n):
                nxt_cost = cur_cost + grid[nr][nc]
                if nxt_cost < min_rupee[nr][nc]:
                    min_rupee[nr][nc] = nxt_cost
                    heappush(pq, (nxt_cost, (nr, nc)))
 
    print(f"Problem {count}: {min_rupee[n-1][n-1]}")
 
count = 0
while True:
    N = int(input())
    if N == 0:
        break
    count += 1
    solve(N, count)

⭐ 4. 백준 1987 (알파벳)

# 4. 알고(백트래킹): 백준 1987 (알파벳) - https://www.acmicpc.net/problem/1987
import sys
 
from io import StringIO
sys.stdin = StringIO('''5 5
IEFCJ
FHFKC
FFALF
HFGCF
HMCHH''')
 
# 백트래킹 이용시, 파이썬에서 시간초과, SET BFS 이용.
input = sys.stdin.readline
 
def solve():
    R, C = map(int, input().split())
 
    board = [input().rstrip() for _ in range(R)]
    directions = [(+1, 0), (-1, 0), (0, +1), (0, -1)]
 
    max_len = 1
    set_q = set([(0, 0, board[0][0])])  # 튜플 셋큐
 
    while set_q:
        r, c, visit_str = set_q.pop()  # 랜덤 set.pop
        max_len = max(max_len, len(visit_str))
 
        if max_len == 26:
            break  # 알파벳 최대값
 
        for dr, dc in directions:
            nr, nc = r + dr, c + dc
            if 0 <= nr < R and 0 <= nc < C:
                nxt = board[nr][nc]
                if nxt not in visit_str:
                    set_q.add((nr, nc, visit_str + nxt))
                    
    print(max_len)
 
solve()

✏️ 5. SQL 조회수가 가장 많은 중고거래 게시판의 첨부파일 조회하기

-- 5. SQL(Lv.3): 조회수가 가장 많은 중고거래 게시판의 첨부파일 조회하기 
-- https://school.programmers.co.kr/learn/courses/30/lessons/164671
SELECT
    CONCAT('/home/grep/src/', BOARD_ID, '/', FILE_ID, FILE_NAME, FILE_EXT) AS FILE_PATH
FROM
    USED_GOODS_FILE
WHERE
    BOARD_ID = (
        SELECT
            BOARD_ID
        FROM
            USED_GOODS_BOARD
        ORDER BY
            VIEWS DESC
        LIMIT 1
   )
ORDER BY
    FILE_ID DESC;