개발일기

#14 백준 코딩은 체육과목이다 & 블랙잭 본문

오류 및 알고리즘정리본

#14 백준 코딩은 체육과목이다 & 블랙잭

츄98 2023. 5. 2. 21:30

오늘은 백준에서 두 문제를 풀었다.

 

1. 코딩은 체육과목이다.

문자열을 이용해서 문제를 간단히 해결할 수 있었다.

import sys
input = sys.stdin.readline
number = int(int(input())/4)
print("long "*number+"int")

 

 

2. 블랙잭

import sys
input = sys.stdin.readline

cnt, sums = map(int, input().split())
numbers = list(map(int,input().split()))

result = 0
target = 0

for i in range(cnt-2):
    for j in range(i+1, cnt-1):
        for k in range(j+1, cnt):
            if numbers[i] + numbers[j] + numbers[k] > sums:
                continue
            else:
                result = numbers[i] + numbers[j] + numbers[k]
                if target <= result:
                    target = result


print(target)

3개의 카드를 뽑아야하고, 모든 경우를 비교해봐야해서 3중 for문을 이용해서 코드를 짰다.

3중 for문을 돌면서 겹치지 않게 범위를 지정해주었다.

 

for문을 이용한 풀이 말고도, combination을 이용해 조합으로 푼 풀이가 있다.

개인적으로 이 풀이 방법이 더 빠르고 코드도 간결하여 좋았다.

 

# combination을 활용한 풀이
from itertools import combinations
import sys
input = sys.stdin.readline

cnt, sums = map(int, input().split())
numbers = list(map(int,input().split()))
target = 0

for i in combinations(numbers,3):
    temp_sum = sum(i)
    if target <= temp_sum <= sums:
        target = temp_sum

print(target)

 

combination을 이용한 풀이가 시간도 줄고 코드길이도 짧은 것을 확인할 수 있다.