programming language/Algorithm

[백준] 완전탐색 2231, 2798, 18312, 19532 python

jellylucy 2024. 1. 31. 12:36

2798

주어진 카드 중에서 3개를 고르는 경우의 수를 구해야한다. => 조합

from itertools import combinations

for cards in combinations(graph, 3)

# 카드의 합이 21을 넘지 않는 한도내에서 카드의 합을 최대한 크게 만드는 게임이다
# 첫째 줄에 카드의 개수
import sys
from itertools import combinations
# input = sys.stdin.readline()

n, m = map(int, input().split())
graph = list(map(int, input().split()))
graph.sort()
result = 0
# 합이 넘지 않는 카드 3장을 찾을 수 있는 경우만 입력으로 주어진다
# N 개 중에 서로다른 3장을 구하는 경우의 수 = 조합 nC3
# 모든 경우의 합을 다 구한다.
resultList = []
for cards in combinations(graph, 3):
    tempSum = sum(cards)
    differ = m - tempSum
    if (differ >= 0):
        resultList.append([tempSum, differ])
    # if (differ < (m - result)):
    #     result = tempSum
    #     print(cards)
resultList.sort(key=lambda x:x[1])

print(resultList[0][0])
# 그 경우의 합을 구할 때 마다 차이값을 넣는다

2231

3자리 예제를 보고 3자리만 생각했다.

 

n의 값을 낼 수 있는 부분합의 모든 경우의 수 = 1부터 n 사이의 정수

=> for i in range(1, n)

 

각 자리 수를 string으로 변환해서 합을 구해야한다.

=> sum ( map(int, str(i)) )

https://dojang.io/mod/page/view.php?id=2286

map 개념 복습할 것.

 

n = int(input())
result = 0
# 생성자가 생길 수 있는 경우의 수 = n의 작은 자연수들.
# 생성자를 정하고 각 자리 수를 하나씩 더하고 비교한다.

for i in range(1, n+1):
    # 각자리수를 더해야한다...
    # map(int, str(i)) = 문자열을 숫자로 변환한다. 그거를 리스트로..
    nums = sum(map(int, str(i)))
    tempNum = i + nums
    if (tempNum == n):
        # print(tempNum, nums,  "tempNu")
        result = i
        break

print(result)

 

19532

변수를 할당하는 것으로 시간 초과가 날 수 있다ㅠ

from itertools import combinations
import sys
input = sys.stdin.readline
a, b, c, d, e, f = map(int, input().split())
realx, realy = 0, 0
for x in range(-999, 1000):
    for y in range(-999, 1000):
        # tempC = a * x + b * y
        # tempF = d * x + e * y
        # if (tempC == c and tempF == f):
            # print(x, y)
        if (a * x + b * y == c and d * x + e * y == f):
            print(x,y)

# graph = list(i for i in range(-999, 1000))
# for x,y in combinations(graph, 2)

18312

단순 완탐이였는데 수학적으로 접근해서 꼬였다

n, kk = map(int, input().split())
# 모든 시각 중에서 K가 하나라도 포함되는 모든 시각?
# result = 0
# temp_result = 0
# if (k <= n):
#     # k시인 경우일 때 모든 분초
#     result += 60 * 60
#     # k시아닌 경우에서 분에서 3이 나온 경우
#     temp_result = ((6*k + 8) * 60) * (n) 
#     + (6*k + 8) * n - ((6*k + 8) * (6*k +8) * n)
#     result += temp_result
# print(result)
count = 0
strK = str(kk)
# 모든 시각
for i in range(n+1):
    for j in range(60):
        for k in range(60):
            if (i < 10):
                tempI = '0' + str(i)
            else:
                tempI = str(i)
            if (j < 10):
                tempJ = '0' + str(j)
            else:
                tempJ = str(j)
            if (k < 10):
                tempK = '0' + str(k)
            else:
                tempK = str(k)
            if (strK in tempI or strK in tempJ or strK in tempK):
                count+=1

print(count)