[백준] CLASS 3 달성하기 8일차

이진규·2022년 7월 18일
1

백준(PYTHON)

목록 보기
54/115

1. 절대값 힙(★최소 힙)

링크 : https://www.acmicpc.net/problem/11286

import heapq
from sys import stdin
input = stdin.readline

n = int(input())
heap = []

for _ in range(n):
    x = int(input())

    if x == 0:
        if heap:
            print(heapq.heappop(heap)[1]) # pop해서 기존값을 출력하는 형태
        else:
            print(0)
    else:
        heapq.heappush(heap, (abs(x), x)) # (절대값, 기존값)을 튜플 형태로 힙에 삽입

2. ATM(그리디)

링크 : https://www.acmicpc.net/problem/11399

from sys import stdin
input = stdin.readline

n = int(input())
time = list(map(int, input().split()))

time.sort()
answer = 0
tmp = 0

for i in time:
    tmp += answer
    answer += i

print(tmp + answer)

3. 경로 찾기(★플로이드-워셜)

링크 : https://www.acmicpc.net/problem/11403

from sys import stdin
input = stdin.readline

n = int(input())
graph = [ list(map(int, input().split())) for _ in range(n) ]

# 플로이드-워셜 알고리즘
for k in range(n):
    for i in range(n):
        for j in range(n):
            if graph[i][k] and graph[k][j]:
                graph[i][j] = 1

for i in graph:
    print(*i)

4. 구간 합 구하기4(★누적합)

링크 : https://www.acmicpc.net/problem/11659

  • 누적 합을 기록한 배열을 따로 생성한 후 일정 범위만큼만 빼주도록 한다.

참고자료

from sys import stdin
input = stdin.readline

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

# 누적 합 배열
for i in range(1, n):
    num[i] += num[i-1]

# 누적 합 계산
for _ in range(m):
    a, b = map(int, input().split())

    if a-2 < 0:
        answer = num[b-1]
    else:
        answer = num[b-1] - num[a-2]

    print(answer)

5. 집합(★집합 자료형)

링크 : https://www.acmicpc.net/problem/11723

from sys import stdin
input = stdin.readline

n = int(input())
s = set()

for _ in range(n):
    ope = list(input().rstrip().split())
    # 'all', 'empty'인 경우는 x 값이 안들어 오기 때문에 리스트에 담아서 입력받음

    if len(ope) == 1:
        if ope[0] == 'all':
            s = set([i for i in range(1, 21)])
        else: # 'empty'인 경우
            s = set()

    else:
        o, x = ope[0], ope[1]
        x = int(x)

        if o == 'add':
            s.add(x)
        elif o == 'remove': # remove()는 존재하지 않는 값을 삭제할 때 오류를 일으키지만 discard()는 그냥 무시함.
            s.discard(x)
        elif o == 'check':
            print(1 if x in s else 0)
        elif o == 'toggle':
            if x in s:
                s.discard(x)
            else:
                s.add(x)
profile
항상 궁금해하고 공부하고 기록하자.

0개의 댓글