programming language/Algorithm

[백준] 완전탐색 22864, 18511, 15721, 1969 python

jellylucy 2024. 2. 1. 11:32

22864

완전탐색은 어느 범위로 for문을 돌아야할지 결정하는게 제일 중요하다.

하루에 최대 얼마나 일을 할 수 있는지 - => 하루 24시간으로 정했다.

import sys
input = sys.stdin.readline

a, b, c, m = map(int, input().split())
tired = 0
work = 0
# 각 시간마다 피로도를 체크하고 안 넘었으면 계속 일하는게 최대인 것 같음 
for i in range(24):
    # print(work, tired,"work, tired")
    if (a > m):
        break
    # 일 더 해도 되는지 체크
    if (tired + a > m):
        # 더 할 경우 m 넘어간다
        if (tired - c < 0):
            tired = 0
        else:
            tired -= c
    else:
        tired += a
        work += b

print(work)

18511

중복 순열 !!

from itertools import product

data = ['사과', '배', '귤']

result = list(product(data, repeat=2))

print(result)


//결과
// [('사과', '사과'), ('사과', '배'), ('사과', '귤'), ('배', '사과'), ('배', '배'), ('배', '귤'), ('귤', '사과'), ('귤', '배'), ('귤', '귤')]
from itertools import product
graph = list(map(int, input().split()))

num = list(product(graph, length = maxLen))

product는 클래스이므로 객체 초기화 이후에는 리스트 자료형으로 변환하여 사용한다.

 

str 각 문자가 들어있는 배열을 int값으로 합치고 싶을 때

-> strList를 map해서 list로 다시 묶은 이유는 product의 list 자료형은 순서쌍으로 존재해서.

num = int(''.join(list(map(str, strList))))
# n보다 작거나 같은 자연수 중에서, 집합 k의 원소로만 구성된 가장 큰 수
# K의 모든 원소는 1부터 9까지의 자연수로만 구성된다
# n = 657, 집한 k의 원소 1, 5, 7dlaus
from itertools import product
# 중복순열..

n, countK = map(int, input().split())
graph = list(map(int, input().split()))
result = 0
graph.sort()
# 하나 또는 n의 자릿수만큼 graph의 원소를 구한다.
maxLen = len(str(n))

num = list(product(graph, repeat = maxLen))

# print(num)
# print(''.join(list(map(str, num[0]))))
# # 뭘까..?
while 1:
    # 최대길이로 먼저 중복순열을 돌린다
    num = list(product(graph, repeat = maxLen))
    for a in num:
        print(a, "a")
        print(list(map(str, a)), "list")
        tempA = int(''.join(list(map(str, a))))
        if (tempA <= n):
            result = max(result, tempA)
    if result == 0:
        maxLen -= 1
    else:
        print(result)
        break

 

15721

for문을 어떻게 잡아야할지 몰라서 헤맸다.

이럴 때는 ====> while(True)

 

배열의 index로 원소값을 찾고 싶을 때

tempList.index(1)

tempList.index((x, y))

a = int(input())
t = int(input())
say = int(input())

# T번째 번 또는 데기를 외치는 사람은 위 원에서 몇 번 사람인지를 구하라

bundegi = []
bun = degi = 1
n = 0

while True:
    prev_n = bun # 번이든 , 데기이든 한 번에 카운팅되는 수가 같음
    n += 1
    for _ in range(2):
        bundegi.append((bun, 0)) #왜 이렇게 넣는걸까 - 첫번째의. 0이다?
        bun += 1 # 몇번쨰의 번인지 카운팅
        bundegi.append((degi, 1))
        degi += 1
    for _ in range(n+1):
        bundegi.append((bun, 0)) #왜 이렇게 넣는걸까 - 첫번째의. 0이다?
        bun += 1 # 몇번쨰의 번인지 카운팅
    for _ in range(n+1):
        bundegi.append((degi, 1))
        degi += 1
    if prev_n < t <= bun:
        print(bundegi.index((t, say)) % a)
        break

 

1969

처음에 해맸던게 이중배열로 값을 담으려고 했다.

=> 심플하게 생각할 것!

 

입력이 이중배열이니까 넣는 것도 이중배열이면,, 머리가 안 돌아간다 ><

n, m = map(int, input().split())
graph = []
for i in range(n):
    graph.append(list(map(str, input())))

# 모든 DNA와 비교를 해야한다....
# 만들 수 있는 거는 .. 4 *  4 * 4 000 이거 아니야?
# checkList = [[0] * 4 for _ in  range(m)]
checkList = []
# print(checkList)
for i in range(m):
    countT = 0
    countA = 0
    countG = 0
    countC = 0
    for j in range(n):
        if graph[j][i] == 'T':
            countT += 1
        if graph[j][i] == 'A':
            countA += 1
        if graph[j][i] == 'G':
            countG += 1
        if graph[j][i] == 'C':
            countC += 1
    # print(countT, countA, countG, countC)
    checkList.append([countA,countC,countG, countT])
# print(checkList)

alpha = ['A', 'C', 'G', 'T']
result = []
resultSum = 0
for check in checkList:
    tempNum = 0
    tempChar = ''
    tempCount = 0
    for i in range(4):
        if tempNum < check[i]:
            tempNum = check[i]
            tempChar = alpha[i]
            tempCount = n - check[i]
    resultSum += tempCount
    result.append(tempChar)

result = ''.join(result)
print(result)
print(resultSum)

다른 풀이

n, m = map(int, input().split())

list = []
s=''
dna = ['A', 'C', 'G', 'T']
hamming_distance = 0

for i in range(n):
    data = input()
    list.append(data)
    
for i in range(m):
    a_count, c_count , g_count, t_count = 0,0,0,0
    for j in range(n):
        if list[j][i]==dna[0]:
            a_count += 1
        elif list[j][i]==dna[1]:
            c_count += 1
        elif list[j][i]==dna[2]:
            g_count += 1
        elif list[j][i]==dna[3]:
            t_count += 1
    count_list = [a_count, c_count, g_count, t_count]
    selected_dna = dna[count_list.index(max(count_list))]
    s+=selected_dna
    for k in range(n):
        if list[k][i]!= selected_dna:
            hamming_distance += 1 
        
print(s)
print(hamming_distance)

같은 것이 있을 때  사전순서로 출력하는 부분에서, max를 쓰면 안된다고 생각했다.

근데 이게 되네 => 첫번째로 나타나는 인덱스를 반환한다.

만약 tempList가 [4, 4, 3, 1]인 경우에는 tempList.index(max(tempList))의 결과는 0입니다.

max(tempList)는 리스트 내에서 가장 큰 값을 반환하며, 그 값은 4입니다. 
그 다음으로 tempList.index() 함수는 해당 값(4)이 처음으로 나타나는 인덱스를 반환합니다. 
따라서 4가 리스트에서 첫 번째로 나타나는 위치는 0번 인덱스입니다.