[알고리즘]_알고리즘 사전(1)

hanseungjune·2022년 10월 19일
0

알고리즘

목록 보기
1/33
post-thumbnail

📌 LIST(배열)

✏️ 부분집합(비트연산)

import sys; sys.stdin=open('../input.txt', 'r')

T = int(input())
for tc in range(1, T+1):
    N, K = map(int, input().split())
    card = [i for i in range(1, 13)]

    cnt = 0
    lst = []
    for i in range(1<<12):
        temp = []
        for j in range(12):
            if i & (1<<j):
                temp.append(card[j])
        if temp not in lst and K == sum(temp) and N == len(temp):
            cnt += 1

    print(f'#{tc} {cnt}')

비트연산의 핵심은 for문 구조이다. 이해하는게 제일 좋긴하지만, 이해못하니까 그냥 외우기를 반복하자. 그리고 부분집합을 구하기위해서 나오는 숫자는 부분집합을 구해야하는 인덱스임을 다시 확인.

✏️ 이진탐색

import sys;sys.stdin = open('../input.txt', 'r')

def binary_search(target):
    global total
    left = 1
    right = total
    cnt = 0
    while left <= right:
        mid = int((left + right)/2)
        # 찾으면 출력
        if mid == target:
            return cnt
        elif mid < target:
            cnt += 1
            left = mid
        elif mid > target:
            cnt += 1
            right = mid

T = int(input())
for tc in range(1, T+1):
    # 전체쪽수, A에서 찾아야하는 쪽수, B에서 찾아야하는 쪽수
    total, tarA, tarB = map(int, input().split())
    cntA, cntB = 0, 0
    cntA = binary_search(tarA)
    cntB = binary_search(tarB)

    if cntA == cntB:
        print(f'#{tc} 0')
    elif cntA > cntB:
        print(f'#{tc} B')
    elif cntA < cntB:
        print(f'#{tc} A')

해당 문제에서 target과 mid변수의 비교에 따라서 left or right가 mid로 결정된다.
하지만, 보통은 left = mid+1 또는 right = mid-1 로 값을 할당하여 처리한다.
while left <= right: 임을 꼭 인지하자
이진탐색은 특정배열에서 원하는 값을 가장 빨리 찾는 것이라고 생각하고 쓰자.

✏️ 전기버스1

import sys; sys.stdin=open('../input.txt', 'r')

T = int(input())
for tc in range(1, T+1):
    # charge = 최대 이동거리, N = 마지막 정류장 번호, station = 충전소 수
    charge, N, station = map(int, input().split())
    number = list(map(int, input().split()))
    lst = [0]*(N+1)
    for n in number:
        lst[n] = 1
    flag = 0

    # 충전횟수
    cnt = 0
    i = N
    lst[-1] = -1
    while i > 0:
        i -= charge
        # print(lst)
        # print(i)
        # print(cnt)
        if i <= 0:
            break
        for _ in range(charge):
            # 충전소가 있다면,
            if lst[i] == 1:
                lst[i] = -1
                cnt += 1
                break
            # 충전소가 없다면,
            i += 1
        # 다 돌리고 또 이미 방문했다면?
        else:
            if lst[i] == -1:
                cnt = 0
                break

    print(f'#{tc} {cnt}')

그냥 참고하려고 가져옴
로직은 도착점에서 시작점으로 가는 것으로 했고, 갈수있는 만큼 뒤로가는 것을 시작으로해서 충전소가 없으면 +1, 있으면 다시 갈수있는 만큼 뒤로감.

✏️ 숫자 카드

import sys; sys.stdin=open('../input.txt', 'r')

T = int(input())
for tc in range(1, T+1):
    N = int(input())
    lst = list(input())
    lst.sort()

    # card
    card = dict()
    for num in lst:
        if num in card:
            card[num] += 1
        else:
            card[num] = 1

    mx = 0
    mx_key = 0
    for key, value in card.items():
        if mx <= value:
            mx = value
            mx_key = key

    print(f'#{tc} {mx_key} {mx}')

딕셔너리나 셋과 같은 해쉬함수를 쓰는 것이 시간을 줄이기에 좋다고 해서 사용함
최대값 및 최소값을 for문을 사용해서 돌리면서 찾는다.
그리고 해당하는 key값에 따른 value값을 구한다.
딕셔너리는 items() => key, value 를 가져와서 구하는게 제일 나은듯

profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글