Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions jaykxo/week03/10816_숫자_카드_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 10816 숫자 카드 2
# 메모리: 117520 KB, 시간: 1384 ms


import bisect # 이분 탐색을 내장 함수로 제공
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int, input().split()))
A.sort() # 이분 탐색을 위한 정렬
M = int(input())
K = list(map(int, input().split()))

# bisect_left, bisect_right 내장 함수를 이용하여 구간(개수) 계산
for t in K:
left = bisect.bisect_left(A, t) # t가 처음 등장하는 인덱스
right = bisect.bisect_right(A, t) # t가 마지막으로 끝난 뒤 인덱스
count = (right - left) # 두 위치 차이가 t의 개수

print(count, end=" ") # 개수를 공백으로 구분하여 출력
16 changes: 16 additions & 0 deletions jaykxo/week03/1181_단어_정렬.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 1181 단어 정렬
# 메모리: 37692 KB, 시간: 80 ms

import sys
input = sys.stdin.readline

N = int(input())

# 단어들을 입력받아 리스트에 저장
words = [input().strip() for _ in range(N)]

# 중복 제거 후 길이 → 사전순으로 정렬
words = sorted(set(words), key=lambda x: (len(x), x))

for word in words:
print(word)
60 changes: 60 additions & 0 deletions jaykxo/week03/1920_수_찾기.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# 1920 수 찾기
# 메모리: 50412 KB, 시간: 504 ms

import sys
input = sys.stdin.readline
from typing import Any, Sequence

N = int(input())
A = list(map(int, input().split()))
A.sort() # 이분 탐색을 위해 반드시 정렬 필요
M = int(input())
K = list(map(int, input().split()))

def bin_search(A: Sequence, key: Any):
pl = 0
pr = len(A) - 1 # 탐색 범위 오른쪽 끝 (리스트 마지막 인덱스)

while pl <= pr:
pc = (pl + pr) // 2 # 현재 탐색 구간의 중간 인덱스

if A[pc] == key:
print("1")
return pc # 찾으면 인덱스 반환 (실제 문제에서는 출력만 필요)

elif A[pc] < key:
pl = pc + 1 # 찾는 값이 더 크면 오른쪽 반으로 탐색 범위 좁힘
else:
pr = pc - 1 # 찾는 값이 더 작으면 왼쪽 반으로 탐색 범위 좁힘

print("0") # 끝까지 못 찾으면 0 출력

# 찾을 숫자들을 하나씩 이분 탐색 실행
for key in K:
bin_search(A, key)


############ 번외 ############
# node.js 제출 버전
# 메모리: 39068 KB, 시간: 324 ms

# const fs = require("fs");
# const input = fs.readFileSync(0).toString().trim().split("\n");

# const N = Number(input[0]);
# const A = input[1].split(" ").map(Number).sort((a, b) => a - b);
# const M = Number(input[2]);
# const targets = input[3].split(" ").map(Number);

# function binarySearch(arr, target) {
# let start = 0, end = arr.length - 1;
# while (start <= end) {
# let mid = Math.floor((start + end) / 2);
# if (arr[mid] === target) return 1;
# if (arr[mid] < target) start = mid + 1;
# else end = mid - 1;
# }
# return 0;
# }

# console.log(targets.map(t => binarySearch(A, t)).join("\n"));
13 changes: 13 additions & 0 deletions jaykxo/week03/2750_수_정렬하기.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# 2750 수 정렬하기
# 메모리: 32412 KB, 시간: 40 ms

import sys
input = sys.stdin.readline

N = int(input())
A = [int(input()) for _ in range(N)]

A.sort() # 리스트 오름차순 정렬

for num in A:
print(num)
30 changes: 30 additions & 0 deletions jaykxo/week04/1072_게임.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# 1072 게임
# PyPy3, 메모리: 108384 KB, 시간: 84 ms
# Python3, 메모리: 32412 KB, 시간: 36 ms

import sys
input = sys.stdin.readline

X, Y = map(int, input().split())
Z = (Y * 100) // X

# 현재 승률이 99% 이상이면 더 올라가지 않음 → -1
if Z >= 99:
print(-1)

else:
# 이분탐색: Z가 처음 증가하는 최소 추가 경기 수
lo, hi = 1, 1_000_000_000 # 탐색 범위
ans = -1 # 정답 후보

while lo <= hi:
mid = (lo + hi) // 2 # 추가 경기 수 후보
newZ = ((Y + mid) * 100) // (X + mid) # 새 승률(정수 나눗셈)

if newZ > Z: # 승률이 증가함 → 더 작은 해가 있는지 왼쪽으로
ans = mid
hi = mid - 1
else: # 아직 증가 안 함 → 오른쪽으로
lo = mid + 1

print(ans)
18 changes: 18 additions & 0 deletions jaykxo/week04/1302_베스트셀러.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# 1302 베스트셀러
# PyPy3, 메모리: 110064 KB, 시간: 112 ms
# Python3, 메모리: 34908 KB, 시간: 56 ms

import sys
input = sys.stdin.readline
from collections import Counter

N = int(input().strip())
books = [input().strip() for _ in range(N)]

counter = Counter(books) # books 리스트 안의 각 책 제목을 key로, 등장 횟수를 value로 세어 Counter 객체 생성
best = sorted(
counter.items(), # Counter를 (책제목, 등장횟수) 쌍들의 리스트로 변환
key=lambda x: (-x[1], x[0]) # 첫 번째 기준: 등장 횟수 내림차순(-x[1]), 두 번째 기준: 책 제목 오름차순(x[0])
)[0][0] # 정렬된 결과의 첫 번째 요소(가장 많이 팔린 책)에서 제목만 추출

print(best)
21 changes: 21 additions & 0 deletions jaykxo/week04/1431_시리얼_번호.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 1431 시리얼 번호
# PyPy3, 메모리: 109544 KB, 시간: 100 ms
# Python3, 메모리: 32412 KB, 시간: 40 ms

import sys
input = sys.stdin.readline

N = int(input().strip())
serials = [input().strip() for _ in range(N)]

serials.sort(
key=lambda s: (
len(s), # 1순위: 시리얼 길이 (짧을수록 먼저). 길이가 같지 않다면 여기서 순서가 확정된다.
sum(int(ch) for ch in s if ch.isdigit()), # 2순위: 숫자 합 (작을수록 먼저). 각 글자가 숫자인지 확인( ch.isdigit() ) 후 int로 변환해 합산.
s # 3순위: 사전순 (문자열 기본 비교). 앞의 두 기준이 같을 때만 사용된다.
)
)

# 정렬된 시리얼 번호를 한 줄에 하나씩 출력
for s in serials:
print(s)
43 changes: 43 additions & 0 deletions jaykxo/week04/2805_나무_자르기.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# 2805 나무 자르기
# PyPy3, 메모리: 287292 KB, 시간: 632 ms
# Python3, 메모리: 151788 KB, 시간: 3028 ms

import sys
input = sys.stdin.readline
from typing import Any, Sequence

N, M = map(int, input().split())
A = list(map(int, input().split()))

def bin_search():
# pl, pr: 절단기 높이의 하한/상한 (inclusive)
pl = 0
pr = max(A) # 탐색 가능 최대 높이 = 가장 큰 나무 높이

# result: 현재까지 조건을 만족(f(h) ≥ M)한 높이들 중 최댓값을 저장하는 변수
result = 0

# 이분탐색 루프: 경계가 교차할 때 종료 (pl > pr)
while pl <= pr:
# pc: 현재 시험해 볼 절단기 높이 (중간값)
pc = (pl + pr) // 2

# length: 높이 pc에서 잘려 나오는 총 나무 길이
# - 나무가 pc 이하이면 잘릴 길이가 없으므로 0
# - 나무가 pc 초과이면 (tree - pc)만큼 잘림
# ※ 리스트 컴프리헨션을 그대로 사용 (메모리는 조금 더 쓰지만 가독성은 좋음)
length = sum([max(0, tree - pc) for tree in A])

# 조건 검사: 현재 높이 pc에서 요구량 M 이상을 확보할 수 있는가?
if length >= M:
# 가능하다면, 더 높은 높이에서도 가능할지 확인해 최댓값을 노린다
result = pc # 현 시점의 후보 정답 갱신
pl = pc + 1 # 더 큰 높이(오른쪽)로 탐색 범위 이동
else:
# 불가능하다면, 높이가 너무 높다는 뜻 → 낮춰야 함
pr = pc - 1 # 더 작은 높이(왼쪽)로 탐색 범위 이동

# 루프 종료 시 result에는 f(h) ≥ M 를 만족하는 최대 h가 저장되어 있음
return result

print(bin_search())