728x90
반응형

다익스트라 알고리즘 같은 경우에는 하나의 정점에서 출발해서 모든 정점으로의 최단거리를 구할 수 있는 반면에,

플로이드-와샬 알고리즘은 모든 정점에서 모든 정점으로의 최단거리를 구할 수 있다.

이 알고리즘의 핵심은 거쳐가는 정점을 기준으로 최단거리를 구한다는 점이다.

다익스트라에 비해서 구현 난이도가 훨씬 쉽다! 와!! 삼중 반복문!!!

 

아래 코드는 파이썬으로 구현한 플로이드-와샬 알고리즘 예시이다.

백준 11404번 플로이드)

import sys
INF = sys.maxsize
input = sys.stdin.readline

n, m = int(input()), int(input())
dis = [[INF]*n for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    if c < dis[a-1][b-1]:
        dis[a-1][b-1] = c
for k in range(n):
    for a in range(n):
        for b in range(n):
            if a != b:
                dis[a][b] = min(dis[a][b], dis[a][k]+dis[k][b])
for i in range(n):
    for j in range(n):
        if dis[i][j] == INF:
            dis[i][j] = 0
for t in dis:
    print(*t)

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/1017?category=911939

 

백준 알고리즘 11404번 플로이드(python)

기본적인 플로이드-와샬 문제이다. import sys INF = sys.maxsize input = sys.stdin.readline n, m = int(input()), int(input()) dis = [[INF]*n for _ in range(n)] for _ in range(m): a, b, c = map(int, inp..

jinho-study.tistory.com

jinho-study.tistory.com/1019

 

백준 알고리즘 2458번 키 순서(python)

기본적인 플로이드-와샬 문제이다. PyPy3로 제출해야 통과된다. (특정 노드가 다른 노드를 가리키는 횟수 + 다른 노드가 특정 노드를 가리키는 횟수) == N-1이라면 그 특정 노드의 순서를 알 수 있다

jinho-study.tistory.com

jinho-study.tistory.com/1020

 

백준 알고리즘 11403번 경로 찾기(python)

기본적인 플로이드-와샬 문제이다. graph[a][k] == 1 and graph[k][b] == 1 이면 a에서 b로 갈 수 있다라는 점이 핵심이다. N = int(input()) graph = [list(map(int, input().split())) for _ in range(N)] for..

jinho-study.tistory.com

https://jinho-study.tistory.com/1085

 

프로그래머스 Level 3 순위

순위를 정확하게 매길 수 있는 사람이 몇 명인지 찾는 문제이다. 플로이드 와샬 알고리즘을 모른다면 풀기 조금 힘들 것 같은 문제이다. 플로이드 와샬을 사용해서 최단경로가 아닌 승패를 확인

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

다익스트라 알고리즘음의 가중치가 없는 그래프의 한 정점에서 모든 정점까지의 최단거리를 구하는 알고리즘이다.

간선에 가중치가 없다면 너비 우선 탐색(BFS)으로도 충분히 풀 수 있지만, 간선에 가중치가 있다면 풀기가 매우

힘들어진다. 간선에 가중치가 있다면 다익스트라 알고리즘을 사용해서 풀도록 하자!!

다익스트라 알고리즘은 동작 과정은 아래와 같다.

1. 출발 노드 지정

2. 최단 거리 테이블 초기화

3. 방문한 적 없는 노드 중에서 최단 거리가 제일 짧은 노드를 선택

4. 해당 노드를 거쳐 다른 노드로 가는 거리를 구하여 최단 거리 테이블을 업데이트

5. 위 3, 4번 과정을 모든 노드를 방문할 때까지 반복

 

아래 코드는 파이썬으로 구현한 다익스트라 알고리즘 예시이다.

백준 1753번 최단경로)

import heapq
import sys
input = sys.stdin.readline

def dijkstra(start):
    q = []
    heapq.heappush(q, (0, start))
    dis[start] = 0
    while q:
        d, now = heapq.heappop(q)
        if dis[now] < d:
            continue
        for v, w in graph[now]:
            cost = d + w
            if cost < dis[v]:
                dis[v] = cost
                heapq.heappush(q, (cost, v))

V, E = map(int, input().split())
start = int(input())
INF = 10**9
dis = [INF]*(V+1)
graph = [[] for _ in range(V+1)]
for _ in range(E):
    u, v, w = map(int, input().split())
    graph[u].append((v, w))
dijkstra(start)
for n in dis[1:]:
    print(n if n != INF else "INF")

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/1011

 

백준 알고리즘 1753번 최단경로(python)

기본적인 다익스트라 알고리즘 문제이다. import heapq import sys input = sys.stdin.readline def dijkstra(start): q = [] heapq.heappush(q, (0, start)) dis[start] = 0 while q: d, now = heapq.heappop(q)..

jinho-study.tistory.com

jinho-study.tistory.com/1013

 

백준 알고리즘 1504번 특정한 최단 경로(python)

기본적인 다익스트라 문제이다. 다익스트라를 1(맨 처음 노드), v1, v2 기준으로 3번 돌려서 3개의 최단 거리 테이블을 생성하고 1 -> v1 -> v2 -> n 순서로 갈 때와 1 -> v2 -> v1 -> n 순서로 갈 때의 거리

jinho-study.tistory.com

jinho-study.tistory.com/1014

 

백준 알고리즘 1446번 지름길(python)

다익스트라 문제이긴 한데 조금 더 쉽게 풀 수 있는 문제이다. BFS랑 매우 비슷한 풀이다. 1. 최단거리 테이블 생성 -> [i for i in range(D+1)] = [0, 1, 2, 3, ... , D] 2. 한 칸 전 위치의 테이블 값+1이 현..

jinho-study.tistory.com

jinho-study.tistory.com/1015

 

백준 알고리즘 1916번 최소비용 구하기(python)

기본적인 다익스트라 문제이다. import heapq import sys INF = sys.maxsize input = sys.stdin.readline def dijkstra(start): q = [] heapq.heappush(q, (0, start)) dis[start] = 0 while q: d, now = heapq.he..

jinho-study.tistory.com

jinho-study.tistory.com/1021

 

백준 알고리즘 5972번 택배 배송(python)

기본적인 다익스트라 문제이다. import heapq import sys INF = sys.maxsize def dijkstra(start): q = [] heapq.heappush(q, (0, start)) dis[start] = 0 while q: d, now = heapq.heappop(q) if dis[now] < d: c..

jinho-study.tistory.com

jinho-study.tistory.com/1022

 

백준 알고리즘 14284번 간선 이어가기 2(python)

기본적인 다익스트라 문제이다. import heapq import sys INF = sys.maxsize # input = sys.stdin.readline def dijkstra(start): q = [] heapq.heappush(q, (0, start)) dis[start] = 0 while q: d, now = heapq...

jinho-study.tistory.com

jinho-study.tistory.com/1023

 

백준 알고리즘 17396번 백도어(python)

기본적인 다익스트라 문제이긴 하다만, N-1번째 분기점을 제외하고 상대의 시야에 보이지 않는 분기점에만 방문해야 한다는 차이점이 있다. import heapq import sys INF = sys.maxsize input = sys.stdin.readli..

jinho-study.tistory.com

jinho-study.tistory.com/1069

 

백준 알고리즘 1238번 파티(python)

골드 3 난이도 치고는 쉬운 다익스트라 알고리즘 문제이다. N-1개(1->X->1, 2->X->2, ..., N->X->X (X->X->X 제외))의 최단경로 중 최댓값을 출력해주면 된다. import heapq import sys INF = sys.maxsize # input..

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

우선순위 큐(Priority Queue)는 큐(Queue)나 스택(Stack)과 비슷한 축약 자료형이다.

일반적인 큐는 FIFO(First in-First Out) 구조이지만 우선순위 큐(Priority Queue)는 들어간 순서에 상관없이 

우선순위가 높은 데이터가 먼저 나오는 구조이다.

파이썬에서는 heapq 또는 PriorityQueue 라이브러리를 사용해서 우선순위 큐를 구현할 수 있다.

import heapq

nums = [4, 1, 7, 3, 8, 5]
heap = []
for n in nums:
    heapq.heappush(heap, n)
while heap:
    print(heapq.heappop(heap))

우선순위 큐(최소 힙)

heapq.heappush를 사용해서 우선순위 큐에 요소를 삽입하고, heapq.heappop을 사용해서 pop 할 수 있다.

heapq는 기본적으로 최소 힙이라서 값이 작은 (1, 3)부터 (3, 1), (10, 2)가 순서대로 pop 되는 것을 확인할 수 있다.

큰 것부터 pop 하고 싶다면 아래 코드와 같이 구현해주면 된다.

import heapq

nums = [4, 1, 7, 3, 8, 5]
heap = []
for n in nums:
    heapq.heappush(heap, (-n, n))
while heap:
    print(heapq.heappop(heap)[1], end=' ')
print()

우선순위 큐(최대 힙)

아래 코드는 PriorityQueue를 사용해서 구현한 우선순위 큐이다.

from queue import PriorityQueue

q = PriorityQueue(maxsize=4)
q.put(3)
q.put(7)
q.put(2)
q.put(9)
print(q.get(), end= ' ')
print(q.get(), end= ' ')
print(q.get(), end= ' ')
print(q.get(), end= ' ')

우선순위 큐는 다익스트라 알고리즘이나, K번 째 최댓값을 찾을 때 등등에 사용할 수 있다.

아래는 대표적인 우선순위 큐 문제 풀이이다.

백준 11279번 최대 힙)

import heapq
import sys
input = sys.stdin.readline

N = int(input()) 
q = []
for _ in range(N):
    n = int(input())
    if n != 0:
        heapq.heappush(q, -n)
    else:
        print(-heapq.heappop(q) if q else 0)

백준 1927번 최소 힙)

import heapq
import sys
input = sys.stdin.readline

N = int(input()) 
q = []
for _ in range(N):
    n = int(input())
    if n != 0:
        heapq.heappush(q, n)
    else:
        print(heapq.heappop(q) if q else 0)

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/1006

 

백준 알고리즘 11279번 최대 힙(python)

기본적인 우선순위 큐 문제이다. import heapq import sys input = sys.stdin.readline N = int(input()) q = [] for _ in range(N): n = int(input()) if n != 0: heapq.heappush(q, -n) else: print(-heapq.heap..

jinho-study.tistory.com

jinho-study.tistory.com/1007

 

백준 알고리즘 1927번 최소 힙(python)

기본적인 우선순위 큐 문제이다. import heapq import sys input = sys.stdin.readline N = int(input()) q = [] for _ in range(N): n = int(input()) if n != 0: heapq.heappush(q, n) else: print(heapq.heappo..

jinho-study.tistory.com

jinho-study.tistory.com/1009

 

백준 알고리즘 11286번 절댓값 힙(python)

기본적인 우선순위 큐 문제이다. import heapq import sys input = sys.stdin.readline N = int(input()) q = [] for _ in range(N): n = int(input()) if n != 0: heapq.heappush(q, (abs(n), n)) else: print(he..

jinho-study.tistory.com

jinho-study.tistory.com/1010

 

백준 알고리즘 1655번 가운데를 말해요(python)

우선순위 큐를 사용해서 빠르게 중앙값을 찾아야 되는 문제이다. 우선순위 큐를 2개(최대 힙, 최소 힙) 사용한다는 점이 핵심이다. 왼쪽 우선순위 큐는 최대 힙으로 최댓값이 맨 처음에 오도록

jinho-study.tistory.com

jinho-study.tistory.com/1024

 

백준 알고리즘 1417번 국회의원 선거(python)

기본적인 우선순위 큐 문제이다. 최대 힙으로 구현해주면 된다. import heapq N = int(input()) D = int(input()) q = [] for _ in range(N-1): n = int(input()) heapq.heappush(q, -n) res = 0 while q: n = -he..

jinho-study.tistory.com

jinho-study.tistory.com/1026

 

백준 알고리즘 14235번 크리스마스 선물(python)

기본적인 우선순위 큐 문제이다. 파이썬에서 우선순위 큐는 heapq 라이브러리 또는 queue 라이브러리의 PriorityQueue를 사용하면 쉽게 구현할 수 있다. 나는 그냥 heapq 라이브러리를 사용해서 풀었다.

jinho-study.tistory.com

jinho-study.tistory.com/1027

 

백준 알고리즘 15903번 카드 합체 놀이(python)

기본적인 우선순위 큐 문제이다. import heapq n, m = map(int, input().split()) q = list(map(int, input().split())) heapq.heapify(q) for _ in range(m): a = heapq.heappop(q) b = heapq.heappop(q) heapq.h..

jinho-study.tistory.com

jinho-study.tistory.com/1067

 

백준 알고리즘 2075번 N번째 큰 수(python)

골드 5 난이도 치고는 매우 쉬운 우선순위 큐 문제이다. 최대 힙 우선순위 큐로 구현해서 N번째 pop결과를 출력해주는 식으로 풀어도 답은 맞지만 메모리 초과가 뜬다. heapq의 nlargest를 사용해서

jinho-study.tistory.com

jinho-study.tistory.com/1068

 

백준 알고리즘 1715번 카드 정렬하기(python)

기본적인 우선순위 큐 문제이다. 이 문제도 골드 4 난이도 치고는 쉽다. 우선순위 큐에 남은 수가 2개 이하가 되기 전까지 제일 작은 두 값을 pop 해서 더하고, 그 합을 우선순위 큐에 추가하고 res

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

백트래킹(Backtracking)이란 해를 찾는 도중 해가 아니면 되돌아가서 다시 해를 찾아가는 방법을 말한다. 

방식에 따라서 깊이우선탐색(Depth-first search, DFS)과 너비우선탐색(Breadth-first search, BFS)으로 나눌 수 있다.

깊이우선탐색(Depth-first search, DFS) jinho-study.tistory.com/865?category=999578

 

깊이 우선 탐색(depth-first search, DFS) (백준 문제 포함)

깊이 우선 탐색(DFS)은 현재 정점과 인접한 간선들을 하나씩 검사하다가, 아직 방문하지 않은 정점으로 통하는 간선이 있다면 그 간선을 방문하고, 이 과정에서 더 이상 방문할 곳이 없다면, 마

jinho-study.tistory.com

너비우선탐색(Breadth-first search, BFS) jinho-study.tistory.com/866?category=999578

 

너비 우선 탐색(breadth-first search, BFS) (백준 문제 포함)

너비 우선 탐색(BFS)은 시작 정점을 방문한 후 시작 정점에 인접한 모든 정점들을 먼저 탐색하는 방법이다. 가까운 정점을 전부 저장해놓고 순서대로 방문해야 하기 때문에 스택으로는 구현이

jinho-study.tistory.com

 

백트래킹 문제로는 대표적인 예시로 여덟 퀸 문제가 있다.

백준 9663번 N-Queen)

def check(n):
    for i in range(n):
        if row[n] == row[i] or abs(row[n]-row[i]) == n-i:
            return 0
    return 1
        
def dfs(n):
    global res
    if n == N:
        res += 1
    else:
        for i in range(N):
            row[n] = i
            if check(n):
                dfs(n+1)

N = int(input())
row = [0]*N
res = 0
dfs(0)
print(res)

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/979

 

백준 알고리즘 9663번 N-Queen(python)

대표적인 브루트포스 알고리즘 & 백트래킹 문제이다. row[n] == row[i] -> 같은 열 확인, abs(row[n]-row[i]) == n-i -> 대각선 확인 def check(n): for i in range(n): if row[n] == row[i] or abs(row[n]-row[..

jinho-study.tistory.com

jinho-study.tistory.com/985

 

백준 알고리즘 15649번 N과 M (1)(python)

기본적인 백트래킹 문제이다. def dfs(i): if i == M: print(*li) return ; for n in range(1, N+1): if check[n]: continue check[n] = 1 li[i] = n dfs(i+1) check[n] = 0 N, M = map(int, input().split()) che..

jinho-study.tistory.com

jinho-study.tistory.com/987

 

백준 알고리즘 15650번 N과 M (2)(python)

기본적인 백트래킹 문제이다. def dfs(n): if n == M: print(*li) return for i in range(N): if check[i]: continue check[i] = 1 li.append(i+1) dfs(n+1) li.pop() for j in range(i+1, N): check[j] = False N..

jinho-study.tistory.com

jinho-study.tistory.com/988

 

백준 알고리즘 15651번 N과 M (3)(python)

기본적인 백트래킹 문제이다. def dfs(n): if n == M: print(*li) return for i in range(N): if check[i]: continue li.append(i+1) dfs(n+1) li.pop() N, M = map(int, input().split()) check = [0]*N li = []..

jinho-study.tistory.com

jinho-study.tistory.com/989

 

백준 알고리즘 15652번 N과 M (4)(python)

기본적인 백트래킹 문제이다. def dfs(n): if n == M: print(*li) return for i in range(N): if check[i]: continue li.append(i+1) dfs(n+1) li.pop() check[i] = 1 for j in range(i+1, N): check[j] = 0 N, M..

jinho-study.tistory.com

jinho-study.tistory.com/993

 

백준 알고리즘 15654번 N과 M (5)(python)

기본적인 다이나믹 프로그래밍 문제이다. def dfs(n): if n == M: print(*t) return ; for i in range(N): if check[i]: continue t.append(li[i]) check[i] = 1 dfs(n+1) t.pop() check[i] = 0 N, M = map(int, i..

jinho-study.tistory.com

jinho-study.tistory.com/1032

 

백준 알고리즘 19699번 소-난다!(python)

백트래킹 & 소수 판정(에라토스테네스의 체) 문제이다. 꽤 좋은 퀄리티의 문제인 것 같다. def dfs(depth): if depth == M: s.add(sum(li)) for i in range(N): if check[i]: continue li.append(nums[i]) check[i..

jinho-study.tistory.com

jinho-study.tistory.com/1034

 

백준 알고리즘 1182번 부분수열의 합(python)

브루트포스 알고리즘 & 백트래킹 문제이다. PyPy3로 제출해야 통과된다. def dfs(depth, k): if depth == k and sum(li) == S: s.append(li) return ; for i in range(N): if check[i]: continue li.append(nums[i..

jinho-study.tistory.com

jinho-study.tistory.com/1035

 

백준 알고리즘 10819번 차이를 최대로(python)

브루트포스 알고리즘 & 백트래킹 문제이다. def dfs(depth): if depth == N: res.append(sum(abs(li[i+1]-li[i]) for i in range(N-1))) return ; for i in range(N): if check[i]: continue li.append(nums[i]) c..

jinho-study.tistory.com

jinho-study.tistory.com/1036

 

백준 알고리즘 15655번 N과 M (6)(python)

기본적인 백트래킹 문제이다. def dfs(depth): if depth == M: print(*li) for i in range(N): if check[i]: continue li.append(nums[i]) check[i] = 1 dfs(depth+1) li.pop() for j in range(i+1, N): check[j]..

jinho-study.tistory.com

jinho-study.tistory.com/1037

 

백준 알고리즘 15656번 N과 M (7)(python)

기본적인 백트래킹 문제이다. def dfs(depth): if depth == M: print(*li) return ; for i in range(N): li.append(nums[i]) dfs(depth+1) li.pop() N, M = map(int, input().split()) nums = sorted(map(int, inp..

jinho-study.tistory.com

jinho-study.tistory.com/1038

 

백준 알고리즘 15657번 N과 M (8)(python)

기본적인 백트래킹 문제이다. def dfs(depth): if depth == M: print(*li) return ; for i in range(N): if depth == 0 or li[-1] <= nums[i]: li.append(nums[i]) dfs(depth+1) li.pop() N, M = map(int, input()..

jinho-study.tistory.com

jinho-study.tistory.com/1040

 

백준 알고리즘 18429번 근손실(python)

브루트포스 알고리즘 & 백트래킹 문제이다. 현재 근육량 + 현재 운동 키트 중량 - K가 0 이상일 때만 재귀 함수로 진입하고 depth(운동 일수)가 성공적으로 N이 되었다면 cnt를 올려주면 된다. def dfs(d

jinho-study.tistory.com

jinho-study.tistory.com/1041

 

백준 알고리즘 19949번 영재의 시험(python)

브루트포스 알고리즘 & 백트래킹 문제이다. depth > 1 and li[depth-2] == li[depth-1] == i(현재 선택한 답과 그 전의 2개의 답이 같음) 조건을 성립하지 않는 답을 추가하고, 정답을 10개 다 선택했다면 점수

jinho-study.tistory.com

jinho-study.tistory.com/1042

 

백준 알고리즘 15663번 N과 M (9)(python)

기본적인 백트래킹 문제이다. 그냥 리스트를 사용해서 중복인지 아닌지 확인하면 무조건 시간초과가 나와서, 딕셔너리(해시)를 사용해서 풀었다. 해시는 진짜 진짜 진짜 엄청 빠르다!! def dfs(dept

jinho-study.tistory.com

jinho-study.tistory.com/1043

 

백준 알고리즘 15664번 N과 M (10)(python)

기본적인 백트래킹 문제이다. 15663번 N과 M (9)과 비슷한 문제이다. def dfs(depth): if depth == M: s = ' '.join(map(str, li)) if s not in d: d[s] = 1 print(s) return ; for i in range(N): if check[i]: c..

jinho-study.tistory.com

jinho-study.tistory.com/1044

 

백준 알고리즘 15665번 N과 M (11)(python)

기본적인 백트래킹 문제이다. 15663번 N과 M (9)와 비슷한 문제이다. def dfs(depth): if depth == M: s = ' '.join(map(str, li)) if s not in d: d[s] = 1 print(s) return ; for i in range(N): li.append(nums..

jinho-study.tistory.com

jinho-study.tistory.com/1045

 

백준 알고리즘 15666번 N과 M (12)(python)

기본적인 백트래킹 문제이다. 15663번 N과 M (9)와 비슷한 문제이다. def dfs(depth): if depth == M: s = ' '.join(map(str, li)) if s not in d: d[s] = 1 print(s) return ; for i in range(N): if depth == 0..

jinho-study.tistory.com

jinho-study.tistory.com/1047

 

백준 알고리즘 5568번 카드 놓기(python)

그냥 백트래킹 형식으로 쉽게 풀었다. def dfs(depth): if depth == k: s.add(''.join(map(str, li))) return ; for i in range(n): if check[i]: continue li.append(nums[i]) check[i] = 1 dfs(depth+1) li.pop(..

jinho-study.tistory.com

jinho-study.tistory.com/1070

 

백준 알고리즘 6603번 로또(python)

단순한 백트래킹 문제이다. def dfs(depth): if depth == 6: print(*li) return ; for i in range(n): if check[i]: continue li.append(nums[i]) check[i] = 1 dfs(depth+1) li.pop() for j in range(i+1, n): ch..

jinho-study.tistory.com

https://jinho-study.tistory.com/1095

 

백준 알고리즘 14888번 연산자 끼워넣기(python)

브루트포스 알고리즘 & 백트래킹 문제이다. 나누기 처리를 할 때 int(n1 / n2) 또는 -(-n1 / n2) 같은 방식으로 나눠야 하는데, 처음에 이걸 몰라서 계속 틀렸다. def dfs(res, i, add, sub, mul, div): global N..

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

동적 계획법(Dynamic programming)이란 복잡한 문제를 간단한 여러 개의 문제로 나누어 푸는 방법을 말한다. 

처음 주어진 문제를 더 작은 문제들로 나눈 뒤 각 조각의 답을 계산하고, 이 답들로부터 원래 문제에 대한 답을 계산해

낸다는 점에서 분할 정복(Divide & Conquer)과 비슷하지만, 동적 계획법에서는 쪼개진 작은 제가 중복되지만, 분할

정복은 절대로 중복될 수가 없다는 차이점이 있다.

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/937

 

백준 알고리즘 16395번 파스칼의 삼각형(python)

기본적인 다이나믹 프로그래밍 문제이다. n, k = map(int, input().split()) li = [[1], [1, 1]] for i in range(2, n): t = [1] for j in range(1, i): t.append(li[i-1][j-1]+li[i-1][j]) t.append(1) li.append..

jinho-study.tistory.com

jinho-study.tistory.com/939

 

백준 알고리즘 15489번 파스칼 삼각형(python)

기본적인 다이나믹 프로그래밍 문제이다. R, C, W = map(int, input().split()) li = [[1], [1, 1]] for i in range(2, R+W-1): t = [1] for j in range(1, i): t.append(li[i-1][j-1]+li[i-1][j]) t.append(1) li..

jinho-study.tistory.com

jinho-study.tistory.com/940

 

백준 알고리즘 2670번 연속부분최대곱(python)

기본적인 다이나믹 프로그래밍 문제이다. N = int(input()) li = [float(input()) for _ in range(N)] t = [0]*(N) t[0] = li[0] for i in range(1, N): if t[i] == 0: t[i] = max(li[i], li[i]*t[i-1]) print("%...

jinho-study.tistory.com

jinho-study.tistory.com/942

 

백준 알고리즘 1149번 RGB거리(python)

기본적인 다이나믹 프로그래밍 문제이다. N = int(input()) li = [list(map(int, input().split())) for _ in range(N)] for i in range(1, N): for j in range(3): li[i][j] += min(li[i-1][:j]+li[i-1][j+1:]) p..

jinho-study.tistory.com

jinho-study.tistory.com/943

 

백준 알고리즘 11053번 가장 긴 증가하는 부분 수열(python)

아주 기본적인 다이나믹 프로그래밍 문제이다. N = int(input()) A = list(map(int, input().split())) dp = [1]*N for i in range(1, N): for j in range(i): if A[j] < A[i]: dp[i] = max(dp[i], dp[j]+1) print..

jinho-study.tistory.com

jinho-study.tistory.com/6

 

백준 알고리즘 1003번 피보나치 함수(python)

기본적인 다이나믹 프로그래밍 문제이다. EX) 입력이 3일 때, 1의 결과 (0, 1)과 2의 결과 (1, 1)을 더한 (1, 2)가 답이다. 피보나치수열의 2차원 버전이 아닐까 라는 생각이 든다. 리스트를 그대로 출력

jinho-study.tistory.com

jinho-study.tistory.com/50

 

백준 알고리즘 1904번 01타일(python)

기본적인 다이나믹 프로그래밍 문제이다. N = 1 -> 1개, N = 2 -> 2개, N = 3 -> 3개, N = 4 -> 5개, N = 5 -> 8개... 규칙을 보면 1, 2, 3, 5, 8, 13 ...인데 피보나치 수열이다. a, b = 1, 1 for i in range(int..

jinho-study.tistory.com

jinho-study.tistory.com/63

 

백준 알고리즘 1932번 정수삼각형(python)

기본적인 다이나믹 프로그래밍 문제이다. n = int(input()) li = [list(map(int, input().split())) for i in range(n)] if n > 1: li[1][0] += li[0][0] li[1][1] += li[0][0] for i in range(2, n): for j in ra..

jinho-study.tistory.com

jinho-study.tistory.com/51

 

백준 알고리즘 1912번 연속합(python)

기본적인 다이나믹 프로그래밍 문제이다. n = int(input()) li = list(map(int, input().split())) for i in range(1, n): li[i] = max(li[i], li[i]+li[i-1]) print(max(li))

jinho-study.tistory.com

 

jinho-study.tistory.com/944

 

백준 알고리즘 1463번 1로 만들기(python)

기본적인 다이나믹 프로그래밍 문제이다. N = int(input()) li = [1000001]*(N+1) li[1] = 0 for i in range(1, N+1): if i%3 == 0: li[i] = min(li[i], li[i//3]+1) if i%2 == 0: li[i] = min(li[i], li[i//2]+1)..

jinho-study.tistory.com

jinho-study.tistory.com/945

 

백준 알고리즘 9461번 파도반 수열(python)

기본적인 다이나믹 프로그래밍 문제이다. 2가지 패턴으로 풀어봤는데 아래쪽이 좀 더 합리적인 것 같다. li = [0, 1, 1, 1, 2, 2, 3] i = 7 while i <= 100: li.append(li[-1] + li[i-5]) i += 1 for _ in range(i..

jinho-study.tistory.com

jinho-study.tistory.com/946

 

백준 알고리즘 9184번 신나는 함수 실행(python)

기본적인 다이나믹 프로그래밍 & 재귀 문제이다. dp = [[[0]*21 for a in range(21)] for b in range(21)] def w(a, b, c): if a <= 0 or b <= 0 or c <= 0: return 1 if a > 20 or b > 20 or c > 20: return w(20..

jinho-study.tistory.com

jinho-study.tistory.com/949

 

백준 알고리즘 2579번 계단 오르기(python)

기본적인 다이나믹 프로그래밍 문제이다. li와 dp를 미리 선언하고 풀어야 런타임 에러가 안 나온다. 마지막 계단의 전 계단을 밟은 경우와, 밟지 않은 경우 2가지를 고려해서 풀면 된다. N = int(inp

jinho-study.tistory.com

jinho-study.tistory.com/952

 

백준 알고리즘 9095번 1, 2, 3 더하기(python)

기본적인 다이나믹 프로그래밍 문제이다. for _ in range(int(input())): n = int(input()) dp = [0]*12 dp[0] = dp[1] = 1 dp[2] = 2 for i in range(3, n+1): dp[i] = dp[i-1] + dp[i-2] + dp[i-3] print(dp[n])

jinho-study.tistory.com

jinho-study.tistory.com/953

 

백준 알고리즘 11726번 2×n 타일링(python)

기본적인 다이나믹 프로그래밍 문제이다. 두 가지 경우만 고려하면 쉽게 풀 수 있다. 1. 2*(n-1) -> 2*n: 타일이 한 개 들어가는 경우밖에 없기 때문에 2*(n-1) 크기의 직사각형에 타일을 배치하는 방

jinho-study.tistory.com

jinho-study.tistory.com/954

 

백준 알고리즘 11727번 2×n 타일링 2(python)

기본적인 다이나믹 프로그래밍 문제이다. 11726번 2×n 타일링과 비슷한 문제이다. n = int(input()) dp = [0, 1, 3] for i in range(3, n+1): dp.append(dp[i-2]*2+dp[i-1]) print(dp[n]%10007)

jinho-study.tistory.com

jinho-study.tistory.com/962

 

백준 알고리즘 9625번 BABBA(python)

기본적인 다이나믹 프로그래밍 문제이다. 처음에 풀 때 dp에 문자열(EX: "BA")을 저장했는데 메모리 초과가 나와서 그냥 숫자로 해결했다. k = int(input()) dp = [0]*(k+1) dp[1] = 1 for i in range(2, k+1): dp..

jinho-study.tistory.com

jinho-study.tistory.com/963

 

백준 알고리즘 13301번 타일 장식물(python)

기본적인 다이나믹 프로그래밍 문제이다. N = int(input()) dp = [0]*(N+1) dp[1] = 4 dp[2] = 6 for i in range(3, N+1): dp[i] = dp[i-1]+dp[i-2] print(dp[N])

jinho-study.tistory.com

jinho-study.tistory.com/965

 

백준 알고리즘 14916번 거스름돈(python)

기본적인 다이나믹 프로그래밍 문제이다. n = int(input()) dp = [-1]*(n+1) dp[0] = 0 for i in range(1, n+1): if i >= 2 and dp[i-2] > -1: dp[i] = (dp[i-2]+1) if dp[i] == -1 else min(dp[i-2]+1, dp[i]) if..

jinho-study.tistory.com

jinho-study.tistory.com/966

 

백준 알고리즘 19947번 투자의 귀재 배주형(python)

브루트포스 알고리즘 & 다이나믹 프로그래밍 문제이다. H, Y = map(int, input().split()) dp = [0]*(Y+1) dp[0] = H for i in range(1, Y+1): if i-1 >= 0 and dp[i-1]: dp[i] = max(int(dp[i-1]*1.05), dp[i]) i..

jinho-study.tistory.com

jinho-study.tistory.com/967

 

백준 알고리즘 8394번 악수(python)

기본적인 다이나믹 프로그래밍 문제이다. n = int(input()) a, b = 1, 0 for i in range(n): a, b = (a+b)%10, a%10 print(a)

jinho-study.tistory.com

jinho-study.tistory.com/969

 

백준 알고리즘 9844번 Gecko(python)

기본적인 다이나믹 프로그래밍 문제이다. h, w = map(int, input().split()) li = [list(map(int, input().split())) for _ in range(h)] dp = [[0]*w for _ in range(h)] dp[0] = li[0] for i in range(1, h): fo..

jinho-study.tistory.com

jinho-study.tistory.com/970

 

백준 알고리즘 13699번 점화식(python)

기본적인 다이나믹 프로그래밍 문제이다. n = int(input()) dp = [0]*(36) dp[0] = 1 dp[1] = 1 dp[2] = 2 for i in range(3, n+1): t = 0 if i%2: for j in range(i//2): t += 2*dp[j]*dp[i-j-1] dp[i] = t + dp[..

jinho-study.tistory.com

jinho-study.tistory.com/971

 

백준 알고리즘 14606번 피자 (Small)(python)

간단한 수학 & 다이나믹 프로그래밍 문제이다. 평범하게 다이나믹 프로그래밍으로 풀면 아래 코드와 같다. N = int(input()) dp = [0]*(11) dp[1] = 0 dp[2] = 1 for i in range(3, N+1): m = i//2 dp[i] = m*(i-m..

jinho-study.tistory.com

jinho-study.tistory.com/972

 

백준 알고리즘 2193번 이친수(python)

기본적인 다이나믹 프로그래밍 문제이다. 평범하게 다이나믹 프로그래밍으로 풀면 아래 코드와 같다. 마지막 자리가 0인 숫자 뒤에는 0과 1 2개를, 마지막 자리가 1인 숫자는 0 1개를 추가할 수 있

jinho-study.tistory.com

jinho-study.tistory.com/973

 

백준 알고리즘 9507번 Generations of Tribbles(python)

기본적인 다이나믹 프로그래밍 문제이다. def koong(n): if n < 2: return 1 if n == 2: return 2 if n == 3: return 4 if dp[n]: return dp[n] dp[n] = koong(n-1) + koong(n-2) + koong(n-3) + koong(n-4) retur..

jinho-study.tistory.com

jinho-study.tistory.com/974

 

백준 알고리즘 14495번 피보나치 비스무리한 수열(python)

기본적인 다이나믹 프로그래밍 문제이다. n = int(input()) dp = [1]*117 for i in range(4, n+1): dp[i] = dp[i-3] + dp[i-1] print(dp[n])

jinho-study.tistory.com

jinho-study.tistory.com/975

 

백준 알고리즘 15624번 피보나치 수 7(python)

기본적인 다이나믹 프로그래밍 문제이다. dp 리스트를 만들어서 풀면 메모리 초과가 나오고 그냥 a, b 변수 2개를 사용해서 풀면 시간 초과가 나오길래 뭔가 했는데, 너무 큰 숫자들로 계산하는

jinho-study.tistory.com

jinho-study.tistory.com/976

 

백준 알고리즘 17175번 피보나치는 지겨웡~(python)

기본적인 다이나믹 프로그래밍 문제이다. n = int(input()) if n < 2: print(1) else: a, b = 1, 1 for i in range(n-1): a, b = a+b+1, a print(a%1000000007)

jinho-study.tistory.com

jinho-study.tistory.com/977

 

백준 알고리즘 11660번 구간 합 구하기 5(python)

누적 합 & 다이나믹 프로그래밍 문제이다. 처음에는 아래 코드와 같이 풀었다. PyPy3로 제출해야 통과가 된다. import sys N, M = map(int, sys.stdin.readline().split()) li = [list(map(int, sys.stdin.readlin..

jinho-study.tistory.com

jinho-study.tistory.com/990

 

백준 알고리즘 12852번 1로 만들기 2(python)

다이나믹 프로그래밍 or 그래프 탐색 문제이다. 다이나믹 프로그래밍 풀이 N = int(input()) dp = [[0, []] for _ in range(N+1)] dp[1][0] = 0 dp[1][1] = [1] for i in range(2, N+1): dp[i][0] = dp[i-1][0] +..

jinho-study.tistory.com

jinho-study.tistory.com/991

 

백준 알고리즘 2156번 포도주 시식(python)

기본적인 다이나믹 프로그래밍 문제이다. 현재 포도주를 마시지 않는 경우, 앞에 포도주를 마시고 현재 포도주를 마시는 경우, 앞에 포도주를 마시지 않고 현재 포도주를 마시는 경우로 총 세

jinho-study.tistory.com

jinho-study.tistory.com/992

 

백준 알고리즘 14697번 방 배정하기(python)

간단한 브루트포스 알고리즘 or 다이나믹 프로그래밍 문제이다. 브루트포스 알고리즘 풀이 a, b, c, n = map(int, input().split()) res = 0 for i in range(0, n+1, a): for j in range(0, n-i+1, b): for k in r..

jinho-study.tistory.com

jinho-study.tistory.com/995

 

백준 알고리즘 11057번 오르막 수(python)

기본적인 다이나믹 프로그래밍 문제이다. N = int(input()) dp = [[0]*10 for _ in range(N+1)] for i in range(10): dp[1][i] = 1 for i in range(2, N+1): for j in range(10): for k in range(j+1): dp[i][j] +..

jinho-study.tistory.com

jinho-study.tistory.com/996

 

백준 알고리즘 9465번 스티커(python)

기본적인 다이나믹 프로그래밍 문제이다. 뒤쪽 대각선 방향으로 첫 번째, 두 번째 위치의 값 중 큰 걸 선택하면 된다. dp[0][j] += max(dp[1][j-1], dp[1][j-2]) dp[1][j] += max(dp[0][j-1], dp[0][j-2]) for..

jinho-study.tistory.com

jinho-study.tistory.com/999

 

백준 알고리즘 11055번 가장 큰 증가 부분 수열(python)

기본적인 다이나믹 프로그래밍 문제이다. 자기 앞에 자기보다 작은 수가 없는 경우도 있는데, 이 부분만 주의하면 쉽게 풀 수 있다. from copy import deepcopy N = int(input()) li = list(map(int, input().spli..

jinho-study.tistory.com

jinho-study.tistory.com/1001

 

백준 알고리즘 2491번 수열(python)

기본적인 다이나믹 프로그래밍 문제이다. N = int(input()) li = list(map(int, input().split())) dp1, dp2 = [1]*N, [1]*N for i in range(1, N): if li[i] <= li[i-1]: dp1[i] = max(dp1[i], dp1[i-1]+1) if li..

jinho-study.tistory.com

jinho-study.tistory.com/1002

 

백준 알고리즘 1965번 상자넣기(python)

기본적인 다이나믹 프로그래밍 문제이다. n = int(input()) li = list(map(int, input().split())) dp = [1]*n for i in range(1, n): for j in range(i): if li[i] > li[j]: dp[i] = max(dp[i], dp[j]+1) print(m..

jinho-study.tistory.com

jinho-study.tistory.com/1003

 

백준 알고리즘 4097번 수익(python)

기본적인 다이나믹 프로그래밍 문제이다. import sys input = sys.stdin.readline while 1: N = int(input()) if N == 0: break li = [int(input()) for _ in range(N)] for i in range(1, N): li[i] = max(li[i],..

jinho-study.tistory.com

jinho-study.tistory.com/1004

 

백준 알고리즘 11060번 점프 점프(python)

기본적인 다이나믹 프로그래밍 문제이다. N = int(input()) li = list(map(int, input().split())) dp = [N+1]*N dp[0] = 0 for i in range(N): for j in range(1, li[i]+1): if i+j >= N: break dp[i+j] = min(dp..

jinho-study.tistory.com

jinho-study.tistory.com/1005

 

백준 알고리즘 14430번 자원 캐기(python)

기본적인 다이나믹 프로그래밍 문제이다. 1차원 DP처럼 똑같이 해주면 된다. N, M = map(int, input().split()) li = [list(map(int, input().split())) for _ in range(N)] dp = [[0]*M for _ in range(N)] dp[0]..

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

너비 우선 탐색(BFS)은 시작 정점을 방문한 후 시작 정점에 인접한 모든 정점들을 먼저 탐색하는 방법이다.

가까운 정점을 전부 저장해놓고 순서대로 방문해야 하기 때문에 스택으로는 구현이 어렵기에 큐(Queue)를 사용한다.

최단거리를 구하는 문제에 많이 사용되는 알고리즘이다. 아래 코드는 BFS코드 예시이다.

 

BFS 경로 탐색(인접 리스트, 1260번 DFS와 BFS)

from collections import deque

def bfs(start):
    queue = deque([start])
    while queue:
        node = queue.popleft()
        print(node, end=' ')
        check[node] = 1
        for n in sorted(li[node]):
            if check[n] == 0:
                queue.append(n)
                check[n] = 1 

N, M, V = map(int, input().split())
li = [[] for _ in range(N+1)]
for _ in range(M):
    a, b = map(int, input().split())
    li[a].append(b)
    li[b].append(a)
check = [0]*(N+1)
bfs(V)

 

BFS 문제 풀이(인접 행렬, 1012번 유기농 배추)

from collections import deque

def bfs(y, x):
    queue = deque()
    queue.append((y, x))
    d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    while queue:
        y, x = queue.popleft()
        for dy, dx in d:
            Y, X = y+dy, x+dx
            if (0 <= Y < N) and (0 <= X < M) and graph[Y][X] == 1:
                queue.append((Y, X))
                graph[Y][X] = 0
                           
for case in range(int(input())):
    M, N, K = map(int, input().split())
    graph = [[0]*M for _ in range(N)]
    for _ in range(K):
        x, y = map(int, input().split())
        graph[y][x] = 1
    res = 0
    for i in range(N):
        for j in range(M):
            if graph[i][j] == 1:
                graph[i][j] = 0
                bfs(i, j)
                res += 1
    print(res)

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/867

 

백준 알고리즘 1012번 유기농 배추(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(10000) def dfs(y, x): graph[y][x] = 0 d = [(-1, 0), (1, 0), (0, -1), (0, 1)] for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < N)..

jinho-study.tistory.com

jinho-study.tistory.com/868

 

백준 알고리즘 1260번 DFS와 BFS(python)

기본적인 DFS & BFS 문제이다. from collections import deque def dfs(node): if check[node] == 0: print(node, end=' ') check[node] = 1 for n in sorted(li[node]): dfs(n) def bfs(start): queue = deque([s..

jinho-study.tistory.com

jinho-study.tistory.com/869

 

백준 알고리즘 7562번 나이트의 이동(python)

최단경로를 찾아야 되는 기본적인 BFS 문제이다. bfs 함수에서 반복문 4번(위, 아래, 오른쪽, 왼쪽) 돌아가던걸 나이트의 이동경로에 맞게 8번 돌도록 바꿔주면 끝이다. from collections import deque def b

jinho-study.tistory.com

jinho-study.tistory.com/870

 

백준 알고리즘 2178번 미로 탐색(python)

최단경로를 찾아야 되는 기본적인 BFS 문제이다. from collections import deque def bfs(): queue = deque() queue.append((0, 0)) d = [(0, 1), (0, -1), (1, 0), (-1, 0)] while queue: y, x = queue.popleft..

jinho-study.tistory.com

jinho-study.tistory.com/871

 

백준 알고리즘 2606번 바이러스(python)

기본적인 DFS & BFS 문제이다. 양방향임 구조임에 주의하자. 처음에 단방향으로 만들어 놓고 풀려해서 왜 틀렸는지 한참을 찾았다. DFS 풀이 def dfs(node): if check[node] == 0: check[node] = 1 for t in graph..

jinho-study.tistory.com

jinho-study.tistory.com/872

 

백준 알고리즘 2667번 단지번호붙이기(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 def dfs(y, x, cnt): graph[y][x] = 0 d = [(-1, 0), (0, 1), (1, 0), (0, -1)] for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < N) and (0 <= X < N) and graph[Y][X] =..

jinho-study.tistory.com

jinho-study.tistory.com/873

 

백준 알고리즘 1697번 숨바꼭질(python)

BFS 문제이다. 인접 행렬, 인접 리스트가 구조가 아닌, 1차원 리스트 구조로 BFS를 구현해주면 된다. from collections import deque def bfs(N, K): queue = deque([N]) while queue: node = queue.popleft() if..

jinho-study.tistory.com

jinho-study.tistory.com/875

 

백준 알고리즘 1926번 그림(python)

DFS & BFS 문제이다. BFS로는 쉽게 통과했는데 DFS에서 계속 메모리 초과가 나온다. 한 시간 동안 해봤는데 해결하지 못했고, 내린 결론은 BFS로 풀 수 있는 문제는 BFS로 풀어야겠다는 점이다ㅜ DFS는 B

jinho-study.tistory.com

jinho-study.tistory.com/876

 

백준 알고리즘 1743번 음식물 피하기(python)

DFS & BFS 문제이다. BFS 풀이 from collections import deque def bfs(i, j): queue = deque() queue.append((i, j)) d = [(-1, 0), (1, 0), (0, -1), (0, 1)] cnt = 1 while queue: y, x = queue.popleft() for..

jinho-study.tistory.com

jinho-study.tistory.com/877

 

백준 알고리즘 2468번 안전 영역(python)

DFS & BFS 문제이다. BFS는 큐에 넣을 때 방문 표시를 해줘야 된다는 점을 항상 주의해야겠다. 큐에서 뺀 뒤에 하면 같은 좌표가 중복으로 큐에 들어가는 것이 반복된다. DFS 풀이 import sys from copy impor

jinho-study.tistory.com

jinho-study.tistory.com/878

 

백준 알고리즘 2583번 영역 구하기(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(10000) def dfs(y, x, cnt): graph[y][x] = 1 for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < M) and (0 <= X < N) and graph[Y][X]..

jinho-study.tistory.com

jinho-study.tistory.com/879

 

백준 알고리즘 4963번 섬의 개수(python)

DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(10000) def dfs(y, x): graph[y][x] = 0 for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < h) and (0 <= X < w) and graph[Y][X] == 1: dfs(Y, X..

jinho-study.tistory.com

jinho-study.tistory.com/882

 

백준 알고리즘 11724번 연결 요소의 개수(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(10000) def dfs(node): check[node] = 1 for n in graph[node]: if check[n] == 0: dfs(n) N, M = map(int, sys.stdin.readline().split..

jinho-study.tistory.com

jinho-study.tistory.com/883

 

백준 알고리즘 10026번 적록색약(python)

DFS & BFS 문제이다. 나름 짧게 잘 구현한 것 같다. 이제 좀 DFS, BFS에 익숙해진 것 같다!! DFS 풀이 import sys from copy import deepcopy sys.setrecursionlimit(10000) def dfs(y, x, color): t[y][x] = '0'..

jinho-study.tistory.com

jinho-study.tistory.com/884

 

백준 알고리즘 11725번 트리의 부모 찾기(python)

트리 & DFS & BFS 문제이다. 시간 초과를 매우 조심해야 되는 문제다. 처음에 방문 체크 리스트를 N-2번 생성하고 순서대로 체크하도록 구현했어서 그런지 시간 초과가 엄청 나왔다. DFS 풀이 import sys

jinho-study.tistory.com

jinho-study.tistory.com/885

 

백준 알고리즘 2644번 촌수계산(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(300000) def dfs(node): for n in graph[node]: if check[n] == 0: check[n] = check[node]+1 dfs(n) n = int(input()) graph = [[] for..

jinho-study.tistory.com

jinho-study.tistory.com/887

 

백준 알고리즘 11559번 Puyo Puyo(python)

구현 & DFS & BFS 문제이다. 기업 코딩 테스트에서 나올 것 같은 문제인데 참 재밌게 푼 것 같다. 1. 터트릴 뿌요가 있는지 확인하는 함수(같은 색깔의 뿌요가 4개 이상 뭉쳐 있는지 확인) 2. 뿌요를

jinho-study.tistory.com

jinho-study.tistory.com/890

 

백준 알고리즘 1389번 케빈 베이컨의 6단계 법칙(python)

BFS 문제이다. res.append(sum(check)-N)이 포인트인 것 같다. from collections import deque def bfs(node): queue = deque() queue.append(node) while queue: node = queue.popleft() for n in grpah[node]: i..

jinho-study.tistory.com

jinho-study.tistory.com/891

 

백준 알고리즘 2589번 보물섬(python)

브루트포스 알고리즘 & BFS 문제이다. 처음에 지도의 크기가 1이나 2같이 작을 경우를 고려하지 못해서 많이 틀렸다. 입력을 받을 때 먼저 처리를 해서 -1, 0으로 이루어진 지도를 생성해서 나중에

jinho-study.tistory.com

jinho-study.tistory.com/892

 

다시 풀자_백준 알고리즘 9205번 맥주 마시면서 걸어가기(python)

BFS & DFS 문제이다. 인접리스트를 행렬 형식으로 구현해서 그래프를 생성하면 쉽게 풀 수 있다. 이걸 생각못해서 1시간 넘게 뻘짓을 했다. BFS 풀이 from collections import deque def make_graph(): for i in r..

jinho-study.tistory.com

jinho-study.tistory.com/893

 

백준 알고리즘 5567번 결혼식(python)

구현 & BFS 문제이다. 거리가 2 이상 3 이하인 노드의 개수를 출력해주면 된다. from collections import deque def bfs(node): queue = deque() queue.append(node) while queue: node = queue.popleft() for n i..

jinho-study.tistory.com

jinho-study.tistory.com/894

 

백준 알고리즘 3184번 양(python)

BFS 문제이다. bfs탐색으로 각 울타리 영역의 양과, 늑대('o'와 'v')의 수를 센 후에, 각 울타리당 양의 수가 늑대보다 많으면 늑대를 0으로, 아니면 양을 0으로 바꿔주고 그 총합을 출력해주면 된다.

jinho-study.tistory.com

 

 

백준 알고리즘 16956번 늑대와 양(python)

기본적인 BFS 문제이다. 양과 늑대가 인접해있으면 막을 수가 없으므로 0을 출력해주고, 인접한 경우가 없다면 늑대를 가둬버리고 결과를 출력해주면 된다. from collections import deque def bfs(y, x): for

jinho-study.tistory.com

jinho-study.tistory.com/895

 

백준 알고리즘 16953번 A → B(python)

그리디 알고리즘 & BFS 문제이다. from collections import deque def bfs(A, B): cnt = 1 queue = deque() queue.append((A, cnt)) while queue: node, cnt = queue.popleft() if node == B: return cnt if node*..

jinho-study.tistory.com

jinho-study.tistory.com/896

 

백준 알고리즘 6118번 숨바꼭질(python)

기본적인 BFS 문제이다. from collections import deque def bfs(node): q = deque() q.append(node) check[node] = 1 while q: node = q.popleft() for n in graph[node]: if check[n] == 0: check[n] = check[no..

jinho-study.tistory.com

jinho-study.tistory.com/897

 

백준 알고리즘 18352번 특정 거리의 도시 찾기(python)

기본적인 BFS 문제이다. from collections import deque def bfs(node): q = deque() q.append(node) check[node] = 0 while q: node = q.popleft() for n in graph[node]: if check[n] == -1: check[n] = check[n..

jinho-study.tistory.com

jinho-study.tistory.com/898

 

백준 알고리즘 16948번 데스 나이트(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = 0 while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < N) and (0..

jinho-study.tistory.com

jinho-study.tistory.com/899

 

백준 알고리즘 16928번 뱀과 사다리 게임(python)

기본적인 BFS 문제이다. if check[t] == -1 or check[t] > graph[n]+1 부분이 핵심인 것 같다. from collections import deque def bfs(node): q = deque() q.append(node) check[node] = 0 while q: node = q.pop..

jinho-study.tistory.com

jinho-study.tistory.com/900

 

백준 알고리즘 13565번 침투(python)

기본적인 DFS & BFS 문제이다. 첫번째 줄만 탐색을 시킨 후에 마지막 줄이 탐색이 된 적 있으면 "YES" 아니면 "NO"를 출력해주면 된다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph..

jinho-study.tistory.com

jinho-study.tistory.com/901

 

백준 알고리즘 12761번 돌다리(python)

기본적인 BFS 문제이다. from collections import deque def bfs(node): q = deque() q.append(node) graph[node] = 0 while q: node = q.popleft() for n in [node-1, node+1, node+A, node-A, node+B, node-B, n..

jinho-study.tistory.com

jinho-study.tistory.com/902

 

백준 알고리즘 3187번 양치기 꿍(python)

기본적인 DFS & BFS 문제이다. 3184번 양과 거의 동일한 문제이다. 그냥 BFS으로만 풀었다. BFS 풀이 from collections import deque def bfs(y, x): queue = deque() queue.append((y, x)) s = w = 0 while queue..

jinho-study.tistory.com

jinho-study.tistory.com/903

 

백준 알고리즘 18405번 경쟁적 전염(python)

생각보다 어려운 BFS 문제이다. 바이러스가 퍼지는 순서(작은 숫자부터)에 맞게 def bfs(x, y): check[x][y] = 1 for dx, dy in d: X, Y = x+dx, y+dy if (0 <= X < N) and (0 <= Y < N) and graph[X][Y] == 0: ch..

jinho-study.tistory.com

jinho-study.tistory.com/904

 

백준 알고리즘 14716번 현수막(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = 0 for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < M) and (0 <= X < N) and graph[Y][X] ==..

jinho-study.tistory.com

jinho-study.tistory.com/905

 

백준 알고리즘 16956번 늑대와 양(python)

기본적인 BFS 문제이다. 양과 늑대가 인접해있으면 막을 수가 없으므로 0을 출력해주고, 인접한 경우가 없다면 늑대를 가둬버리고 결과를 출력해주면 된다. from collections import deque def bfs(y, x): for

jinho-study.tistory.com

jinho-study.tistory.com/907

 

백준 알고리즘 1303번 전쟁 - 전투(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x, cnt): c = graph[y][x] graph[y][x] = 1 for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < M) and (0 <= X < N..

jinho-study.tistory.com

jinho-study.tistory.com/908

 

백준 알고리즘 17806번 아기 상어 2(python)

브루트포스 알고리즘 & BFS 문제이다. from collections import deque from copy import deepcopy def bfs(y, x): q = deque() q.append((y, x)) a[y][x] = 0 while q: y, x = q.popleft() for dy, dx in d: Y, X..

jinho-study.tistory.com

jinho-study.tistory.com/909

 

백준 알고리즘 6186번 Best Grass(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = '1' while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < R) and..

jinho-study.tistory.com

jinho-study.tistory.com/910

 

백준 알고리즘 11123번 양 한마리... 양 두마리...(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = '.' for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < H) and (0 <= X < W) and graph[Y][X] =..

jinho-study.tistory.com

jinho-study.tistory.com/911

 

백준 알고리즘 17198번 Bucket Brigade(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = 0 while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < 10) and (..

jinho-study.tistory.com

jinho-study.tistory.com/912

 

백준 알고리즘 4677번 Oil Deposits(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = '*' for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < m) and (0 <= X < n) and graph[Y][X] =..

jinho-study.tistory.com

jinho-study.tistory.com/913

 

백준 알고리즘 18232번 텔레포트 정거장(python)

기본적인 BFS 문제이다. from collections import deque import sys def bfs(node): q = deque() q.append(node) check[node] = 0 while q: node = q.popleft() d = [node-1, node+1] if graph[node]: d += graph[..

jinho-study.tistory.com

jinho-study.tistory.com/914

 

백준 알고리즘 18243번 Small World Network(python)

기본적인 BFS 문제이다. from collections import deque def bfs(node): q = deque() q.append(node) check[node] = 0 while q: node = q.popleft() for n in graph[node]: if check[n] == -1: q.append(n) check[..

jinho-study.tistory.com

jinho-study.tistory.com/915

 

백준 알고리즘 18404번 현명한 나이트(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = 0 while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < N) and (0..

jinho-study.tistory.com

jinho-study.tistory.com/916

 

백준 알고리즘 8061번 Bitmap(python)

기본적인 BFS 문제이다. 처음에 '1'의 위치들을 queue에 모두 추가해놓고 bfs를 돌리면 쉽게 풀 수 있다. 간단하지만 여태까지 풀어왔던 문제랑 조금 느낌이 달라서 푸는데 시간이 조금 걸렸다. from c

jinho-study.tistory.com

jinho-study.tistory.com/917

 

백준 알고리즘 15240번 Paint bucket(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x, K, n): graph[y][x] = K for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < R) and (0 <= X < C) and graph[Y][..

jinho-study.tistory.com

jinho-study.tistory.com/918

 

백준 알고리즘 14248번 점프 점프(python)

기본적인 BFS 문제이다. from collections import deque def bfs(node): q = deque() q.append(node) check[node] = 1 while q: node = q.popleft() for d in [-graph[node], graph[node]]: t = node+d if (0 <= t..

jinho-study.tistory.com

jinho-study.tistory.com/919

 

백준 알고리즘 15092번 Sheba’s Amoebas(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = '.' for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < m) and (0 <= X < n) and graph[Y][X] =..

jinho-study.tistory.com

jinho-study.tistory.com/920

 

백준 알고리즘 5938번 Daisy Chains in the Field(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(node): check[node] = 1 for n in graph[node]: if check[n] == 0: dfs(n) N, M = map(int, input().split()) graph =..

jinho-study.tistory.com

jinho-study.tistory.com/921

 

백준 알고리즘 5931번 Cow Beauty Pageant(python)

생각보다 쉽지 않은 BFS 문제이다. 우선 'X'를 '1'과 '2'로 각각 채워주고, 1에서 2로 가는 최소 거리를 찾아주면 된다. 1이 1안에 갇혀서 2로 갈 수도 없는 경우가 있으므로 이 경우는 따로 잘 처리해

jinho-study.tistory.com

jinho-study.tistory.com/922

 

백준 알고리즘 10917번 Your life(python)

기본적인 BFS 문제이다. import sys from collections import deque def bfs(node): q = deque() q.append(node) check[node] = 0 while q: node = q.popleft() for n in graph[node]: if check[n] == -1: q.appen..

jinho-study.tistory.com

jinho-study.tistory.com/923

 

백준 알고리즘 6031번 Feeding Time(python)

기본적인 BFS 문제이다. '.'을 1, 2, 3...으로 채울 때마다 각각 몇 개를 채웠는지 확인하고, 그중 최댓값을 출력해주면 된다. from collections import deque def bfs(y, x, t): q = deque() q.append((y, x)) gr..

jinho-study.tistory.com

jinho-study.tistory.com/924

 

백준 알고리즘 11370번 Spawn of Ungoliant(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < H) and (0 <= X < W) and g..

jinho-study.tistory.com

jinho-study.tistory.com/927

 

백준 알고리즘 16390번 Sheba’s Amoebas(python)

기본적인 DFS & BFS 문제이다. 15092번 Sheba’s Amoebas와 같은 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = '.' for dy, dx in d: Y, X = y+dy, x+dx if (0 <=..

jinho-study.tistory.com

jinho-study.tistory.com/928

 

백준 알고리즘 1325번 효율적인 해킹(python)

DFS & BFS 문제이다. 그런데 DFS로 풀면 시간초과가 계속 나와서 그냥 BFS로만 풀었다. 입력을 받을 때는 sys.stdin.readline을 사용하고, Python3가 아닌 PyPy3로 제출해야 통과된다. BFS 풀이 from collections..

jinho-study.tistory.com

jinho-study.tistory.com/929

 

백준 알고리즘 14496번 그대, 그머가 되어(python)

단순한 BFS 문제이다. 근데 a == b일 때를 생각 못하고 처리를 안 해서 엄청나게 많이 틀렸다. 주의하도록 하자 from collections import deque def bfs(a, b): q = deque() q.append(a) check[a] = 0 while q: no..

jinho-study.tistory.com

jinho-study.tistory.com/930

 

백준 알고리즘 14145번 Žetva(python)

기본적인 DFS & BFS 문제이다. 처음에 그래프를 생성할 때 graph = [map(int, list(input())) for _ in range(R)] 와 같은 방식으로 생성해서 계속 메모리 초과가 나왔다. graph = [list(input()) for _ in range(..

jinho-study.tistory.com

jinho-study.tistory.com/931

 

백준 알고리즘 10204번 Neighborhoods in Graphs(python)

기본적인 BFS 문제이다. 특정 노드에서부터 거리가 2 이하인 노드가 몇 개 인지 출력하면 되는 문제이다. from collections import deque def bfs(node): q = deque() q.append(node) check[node] = 0 while q: no..

jinho-study.tistory.com

jinho-study.tistory.com/932

 

백준 알고리즘 13746번 Islands(python)

기본적인 BFS 문제이다. L(땅)이 탐지될 때마다 BFS를 돌리고 카운트를 세는데 이때 C(구름)는 L이라고 생각하고 처리하면 된다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) gra..

jinho-study.tistory.com

jinho-study.tistory.com/933

 

백준 알고리즘 18422번 Emacs(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = '.' while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < r) and..

jinho-study.tistory.com

jinho-study.tistory.com/934

 

백준 알고리즘 6189번 Munching(python)

기본적인 BFS 문제이다. B에서 C로 가는 최단거리의 길이를 출력해주면 된다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = 0 while q: y, x = q.popleft() for dy,..

jinho-study.tistory.com

jinho-study.tistory.com/936

 

백준 알고리즘 6080번 Bad Grass(python)

기본적인 DFS & BFS 문제인데 DFS로는 메모리 초과 때문에 통과가 안 되는 것 같다. BFS로 제출하면 통과된다. BFS 풀이 from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x]..

jinho-study.tistory.com

jinho-study.tistory.com/957

 

백준 알고리즘 6004번 The Chivalrous Cow(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = 0 while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < N) and (0..

jinho-study.tistory.com

jinho-study.tistory.com/958

 

백준 알고리즘 6229번 Bronze Lilypad Pond(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = 0 while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < M) and (0..

jinho-study.tistory.com

jinho-study.tistory.com/951

 

백준 알고리즘 9019번 DSLR(python)

생각보다 쉬운 BFS 문제이다. 변환된 숫자와 여태까지 사용한 명령어를 큐에 같이 append, pop 해주면 된다. 변환된 숫자와 B가 같다면 여태까지 사용한 명령어(res)를 리턴하면 끝이다. from collections i

jinho-study.tistory.com

jinho-study.tistory.com/959

 

백준 알고리즘 6798번 Knight Hop(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = 0 while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < 8) and (0..

jinho-study.tistory.com

jinho-study.tistory.com/960

 

백준 알고리즘 11448번 Ga(python)

기본적인 BFS 문제이다. from collections import deque def bfs(y, x): q = deque() q.append((y, x)) graph[y][x] = 'w' cnt = 0 while q: y, x = q.popleft() for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y <..

jinho-study.tistory.com

jinho-study.tistory.com/981

 

백준 알고리즘 5558번 チーズ(python)

S에서 시작해서 1부터 N까지 순서대로 들렀을 때의 최단거리를 구해야 되는 BFS 문제이다. 1에 들러야 된다고 해서 2를 지나가면 안 된다는 것은 아니다. 목적지(1, 2, ... N)에 도착할 때마다 시작점

jinho-study.tistory.com

jinho-study.tistory.com/990

 

백준 알고리즘 12852번 1로 만들기 2(python)

다이나믹 프로그래밍 or 그래프 탐색 문제이다. 다이나믹 프로그래밍 풀이 N = int(input()) dp = [[0, []] for _ in range(N+1)] dp[1][0] = 0 dp[1][1] = [1] for i in range(2, N+1): dp[i][0] = dp[i-1][0] +..

jinho-study.tistory.com

jinho-study.tistory.com/1016

 

백준 알고리즘 13549번 숨바꼭질 3(python)

너비 우선 탐색 or 다익스트라 문제인데 그냥 너비 우선 탐색으로 풀었다. 이전 숨바꼭질 문제와는 다르게 순간이동할 때 걸리는 시간이 0이다. 이 점 때문에 node-1, node+1보다 node*2를 먼저 탐색을

jinho-study.tistory.com

https://jinho-study.tistory.com/1075

 

백준 알고리즘 1326번 폴짝폴짝(python)

앞, 뒤 방향과 노드별 이동거리 모두 고려해줘야 되는 bfs 문제이다. 아래와 같이 앞, 뒤 방향의 경우로 둘로 나눠서 반복문을 짜면 96ms로 통과된다. from collections import deque def bfs(a, b, bridge, N): q..

jinho-study.tistory.com

https://jinho-study.tistory.com/1076

 

백준 알고리즘 1326번 폴짝폴짝(python)

기본적인 BFS 문제이다. B가 200점 이상이 되는 최단경로는 없을 것 같아서 check 리스트 크기를 200으로 정했다. from collections import deque def bfs(S, T): q = deque() q.append((S, T, 0)) check = [-1]*..

jinho-study.tistory.com

https://jinho-study.tistory.com/1084

 

프로그래머스 Level 3 가장 먼 노드

1번 노드에서 제일 먼 노드가 몇 개 인지 찾는 문제이다. BFS로 아주 쉽게 풀 수 있다. from collections import deque def solution(N, edge): graph = [[] for _ in range(N+1)] for a, b in edge: graph[a].app..

jinho-study.tistory.com

https://jinho-study.tistory.com/1087

 

프로그래머스 Level 3 네트워크

간단한 그래프 탐색 문제이다. 반복문을 돌면서 체크가 안된 노드가 있다면 ans += 1을 하고 그 노드부터 시작하여 dfs 또는 bfs를 돌려서 갈 수 있는 길을 다 체크해주면 된다. check[i] = 0 -> i 노드 들

jinho-study.tistory.com

https://jinho-study.tistory.com/1099

 

백준 알고리즘 16173번 점프왕 쩰리 (Small)(python)

기본적인 BFS, DFS 문제이다. (N, N) 좌표에 도착할 수 있는지를 확인해주면 된다. BFS 풀이 from collections import deque def bfs(y, x): q = deque() q.append((y, x, li[y][x])) while q: y, x, d = q.poplef..

jinho-study.tistory.com

https://jinho-study.tistory.com/1100

 

백준 알고리즘 17204번 죽음의 게임(python)

기본적인 그래프 탐색 문제이다. 최단거리를 찾는 문제이므로 BFS로 풀었다. from collections import deque def bfs(): q = deque() q.append((0)) while q: node = q.popleft() n = li[node] if check[n] == 0 a..

jinho-study.tistory.com

https://jinho-study.tistory.com/1107

 

백준 알고리즘 9311번 Robot in a Maze(python)

간단한 BFS 문제이다. S에서 G로 가는 최단경로의 길이를 출력해주면 된다. 경로가 없다면 No Exit 출력 from collections import deque def bfs(i, j): d = [(-1, 0), (1, 0), (0, -1), (0, 1)] q = deque() q.ap..

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

깊이 우선 탐색(DFS)은 현재 정점과 인접한 간선들을 하나씩 검사하다가, 아직 방문하지 않은 정점으로 통하는 간선이

있다면 그 간선을 방문하고, 이 과정에서 더 이상 방문할 곳이 없다면, 마지막에 방문했던 간선을 따라 뒤로 돌아가는 방

식이다. 동굴을 탐험한다고 생각하면 쉽다.

마지막에 방문했던 곳으로 되돌아간다는 점에서 스택과 비슷해서 그런지, DFS는 스택 또는 재귀 함수로 구현할 수 있다.

아래 코드는 DFS코드 예시이다.

 

DFS 경로 탐색(인접 리스트, 1260번 DFS와 BFS)

def dfs(node):
    if check[node] == 0:
        print(node, end=' ')
        check[node] = 1
        for n in sorted(li[node]):
            dfs(n)
    
N, M, V = map(int, input().split())
li = [[] for _ in range(N+1)]
for _ in range(M):
    a, b = map(int, input().split())
    li[a].append(b)
    li[b].append(a)
check = [0]*(N+1)
dfs(V)
print()

 

DFS 문제 풀이(인접 행렬, 1012번 유기농 배추)

import sys
sys.setrecursionlimit(10000)

def dfs(y, x):
    graph[y][x] = 0
    d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    for dy, dx in d:
        Y, X = y+dy, x+dx
        if (0 <= Y < N) and (0 <= X < M) and graph[Y][X] == 1:
            dfs(Y, X)

for case in range(int(input())):
    M, N, K = map(int, input().split())
    graph = [[0]*M for _ in range(N)]
    for _ in range(K):
        x, y = map(int, input().split())
        graph[y][x] = 1
    res = 0
    for i in range(N):
        for j in range(M):
            if graph[i][j] == 1:
                dfs(i, j)
                res += 1
    print(res)

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/867

 

백준 알고리즘 1012번 유기농 배추(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(10000) def dfs(y, x): graph[y][x] = 0 d = [(-1, 0), (1, 0), (0, -1), (0, 1)] for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < N)..

jinho-study.tistory.com

jinho-study.tistory.com/868

 

백준 알고리즘 1260번 DFS와 BFS(python)

기본적인 DFS & BFS 문제이다. from collections import deque def dfs(node): if check[node] == 0: print(node, end=' ') check[node] = 1 for n in sorted(li[node]): dfs(n) def bfs(start): queue = deque([s..

jinho-study.tistory.com

jinho-study.tistory.com/871

 

백준 알고리즘 2606번 바이러스(python)

기본적인 DFS & BFS 문제이다. 양방향임 구조임에 주의하자. 처음에 단방향으로 만들어 놓고 풀려해서 왜 틀렸는지 한참을 찾았다. DFS 풀이 def dfs(node): if check[node] == 0: check[node] = 1 for t in graph..

jinho-study.tistory.com

jinho-study.tistory.com/872

 

백준 알고리즘 2667번 단지번호붙이기(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 def dfs(y, x, cnt): graph[y][x] = 0 d = [(-1, 0), (0, 1), (1, 0), (0, -1)] for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < N) and (0 <= X < N) and graph[Y][X] =..

jinho-study.tistory.com

jinho-study.tistory.com/876

 

백준 알고리즘 1743번 음식물 피하기(python)

DFS & BFS 문제이다. BFS 풀이 from collections import deque def bfs(i, j): queue = deque() queue.append((i, j)) d = [(-1, 0), (1, 0), (0, -1), (0, 1)] cnt = 1 while queue: y, x = queue.popleft() for..

jinho-study.tistory.com

jinho-study.tistory.com/877

 

백준 알고리즘 2468번 안전 영역(python)

DFS & BFS 문제이다. BFS는 큐에 넣을 때 방문 표시를 해줘야 된다는 점을 항상 주의해야겠다. 큐에서 뺀 뒤에 하면 같은 좌표가 중복으로 큐에 들어가는 것이 반복된다. DFS 풀이 import sys from copy impor

jinho-study.tistory.com

jinho-study.tistory.com/878

 

백준 알고리즘 2583번 영역 구하기(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(10000) def dfs(y, x, cnt): graph[y][x] = 1 for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < M) and (0 <= X < N) and graph[Y][X]..

jinho-study.tistory.com

jinho-study.tistory.com/879

 

백준 알고리즘 4963번 섬의 개수(python)

DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(10000) def dfs(y, x): graph[y][x] = 0 for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < h) and (0 <= X < w) and graph[Y][X] == 1: dfs(Y, X..

jinho-study.tistory.com

jinho-study.tistory.com/882

 

백준 알고리즘 11724번 연결 요소의 개수(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(10000) def dfs(node): check[node] = 1 for n in graph[node]: if check[n] == 0: dfs(n) N, M = map(int, sys.stdin.readline().split..

jinho-study.tistory.com

jinho-study.tistory.com/883

 

백준 알고리즘 10026번 적록색약(python)

DFS & BFS 문제이다. 나름 짧게 잘 구현한 것 같다. 이제 좀 DFS, BFS에 익숙해진 것 같다!! DFS 풀이 import sys from copy import deepcopy sys.setrecursionlimit(10000) def dfs(y, x, color): t[y][x] = '0'..

jinho-study.tistory.com

jinho-study.tistory.com/884

 

백준 알고리즘 11725번 트리의 부모 찾기(python)

트리 & DFS & BFS 문제이다. 시간 초과를 매우 조심해야 되는 문제다. 처음에 방문 체크 리스트를 N-2번 생성하고 순서대로 체크하도록 구현했어서 그런지 시간 초과가 엄청 나왔다. DFS 풀이 import sys

jinho-study.tistory.com

jinho-study.tistory.com/885

 

백준 알고리즘 2644번 촌수계산(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(300000) def dfs(node): for n in graph[node]: if check[n] == 0: check[n] = check[node]+1 dfs(n) n = int(input()) graph = [[] for..

jinho-study.tistory.com

jinho-study.tistory.com/886

 

백준 알고리즘 11558번 The Game of Death(python)

간단한 그래프 탐색 문제이다. 그냥 DFS 방식으로 풀었다. def dfs(node): for n in graph[node]: if check[n] == 0: check[n] = check[node]+1 dfs(n) for _ in range(int(input())): N = int(input()) graph = [..

jinho-study.tistory.com

jinho-study.tistory.com/887

 

백준 알고리즘 11559번 Puyo Puyo(python)

구현 & DFS & BFS 문제이다. 기업 코딩 테스트에서 나올 것 같은 문제인데 참 재밌게 푼 것 같다. 1. 터트릴 뿌요가 있는지 확인하는 함수(같은 색깔의 뿌요가 4개 이상 뭉쳐 있는지 확인) 2. 뿌요를

jinho-study.tistory.com

jinho-study.tistory.com/889

 

백준 알고리즘 9372번 상근이의 여행(python)

트리 & 그래프 이론 문제이다. 문제가 웃긴게 애초에 모든 국가가 연결되있기 때문에 N-1을 출력해면 끝이다. 처음에는 이걸 생각 못해서 두 번째 코드 같ㅇ탐색해서 풀었다. for _ in range(int(input())

jinho-study.tistory.com

jinho-study.tistory.com/892

 

다시 풀자_백준 알고리즘 9205번 맥주 마시면서 걸어가기(python)

BFS & DFS 문제이다. 인접리스트를 행렬 형식으로 구현해서 그래프를 생성하면 쉽게 풀 수 있다. 이걸 생각못해서 1시간 넘게 뻘짓을 했다. BFS 풀이 from collections import deque def make_graph(): for i in r..

jinho-study.tistory.com

jinho-study.tistory.com/900

 

백준 알고리즘 13565번 침투(python)

기본적인 DFS & BFS 문제이다. 첫번째 줄만 탐색을 시킨 후에 마지막 줄이 탐색이 된 적 있으면 "YES" 아니면 "NO"를 출력해주면 된다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph..

jinho-study.tistory.com

jinho-study.tistory.com/902

 

백준 알고리즘 3187번 양치기 꿍(python)

기본적인 DFS & BFS 문제이다. 3184번 양과 거의 동일한 문제이다. 그냥 BFS으로만 풀었다. BFS 풀이 from collections import deque def bfs(y, x): queue = deque() queue.append((y, x)) s = w = 0 while queue..

jinho-study.tistory.com

jinho-study.tistory.com/904

 

백준 알고리즘 14716번 현수막(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = 0 for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < M) and (0 <= X < N) and graph[Y][X] ==..

jinho-study.tistory.com

jinho-study.tistory.com/907

 

백준 알고리즘 1303번 전쟁 - 전투(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x, cnt): c = graph[y][x] graph[y][x] = 1 for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < M) and (0 <= X < N..

jinho-study.tistory.com

jinho-study.tistory.com/910

 

백준 알고리즘 11123번 양 한마리... 양 두마리...(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = '.' for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < H) and (0 <= X < W) and graph[Y][X] =..

jinho-study.tistory.com

jinho-study.tistory.com/912

 

백준 알고리즘 4677번 Oil Deposits(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = '*' for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < m) and (0 <= X < n) and graph[Y][X] =..

jinho-study.tistory.com

jinho-study.tistory.com/917

 

백준 알고리즘 15240번 Paint bucket(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x, K, n): graph[y][x] = K for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < R) and (0 <= X < C) and graph[Y][..

jinho-study.tistory.com

jinho-study.tistory.com/919

 

백준 알고리즘 15092번 Sheba’s Amoebas(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = '.' for dy, dx in d: Y, X = y+dy, x+dx if (0 <= Y < m) and (0 <= X < n) and graph[Y][X] =..

jinho-study.tistory.com

jinho-study.tistory.com/920

 

백준 알고리즘 5938번 Daisy Chains in the Field(python)

기본적인 DFS & BFS 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(node): check[node] = 1 for n in graph[node]: if check[n] == 0: dfs(n) N, M = map(int, input().split()) graph =..

jinho-study.tistory.com

jinho-study.tistory.com/925

 

백준 알고리즘 2210번 숫자판 점프(python)

브루트포스 알고리즘 & DFS 문제이다. 문자열 s를 계속 업데이트하다가 길이가 6이면 set(res)에 추가해주고, 마지막에 set의 길이를 출력해주면 된다. import sys sys.setrecursionlimit(3000000) def dfs(y, x,..

jinho-study.tistory.com

jinho-study.tistory.com/926

 

백준 알고리즘 19621번 회의실 배정 2(python)

기본적인 DFS 문제이다. 현재 회의가 끝나는 시간이 제일 늦은 회의 시작 시간보다 크면 더 이상 회의를 할 수 없는 상황이므로 여태까지 회의에 참여한 인원수를 리스트에 추가해준다. 마지막에

jinho-study.tistory.com

jinho-study.tistory.com/927

 

백준 알고리즘 16390번 Sheba’s Amoebas(python)

기본적인 DFS & BFS 문제이다. 15092번 Sheba’s Amoebas와 같은 문제이다. DFS 풀이 import sys sys.setrecursionlimit(3000000) def dfs(y, x): graph[y][x] = '.' for dy, dx in d: Y, X = y+dy, x+dx if (0 <=..

jinho-study.tistory.com

jinho-study.tistory.com/930

 

백준 알고리즘 14145번 Žetva(python)

기본적인 DFS & BFS 문제이다. 처음에 그래프를 생성할 때 graph = [map(int, list(input())) for _ in range(R)] 와 같은 방식으로 생성해서 계속 메모리 초과가 나왔다. graph = [list(input()) for _ in range(..

jinho-study.tistory.com

https://jinho-study.tistory.com/1086

 

프로그래머스 Level 3 여행경로

리스트가 아닌 딕셔너리로 그래프를 구현해서 풀어야되는 문제이다. 올바른 경로를 찾을 때까지 뺑뺑이를 돌려줘야 되는 문제라 dfs로 풀었다. 핵심은 dfs 함수를 재귀로 넘기기 전에 딕셔너리의

jinho-study.tistory.com

https://jinho-study.tistory.com/1087

 

프로그래머스 Level 3 네트워크

간단한 그래프 탐색 문제이다. 반복문을 돌면서 체크가 안된 노드가 있다면 ans += 1을 하고 그 노드부터 시작하여 dfs 또는 bfs를 돌려서 갈 수 있는 길을 다 체크해주면 된다. check[i] = 0 -> i 노드 들

jinho-study.tistory.com

https://jinho-study.tistory.com/1088

 

프로그래머스 Level 3 단어 변환

begin에서 target으로 가는 최단경로의 길이를 찾는 문제이다. 두 단어의 차이가 한 글자면 이동 가능하다. 이동 가능한지 판별하는 부분은 아래의 조건문같이 구현했다. if len([1 for i in range(N) if node

jinho-study.tistory.com

https://jinho-study.tistory.com/1096

 

백준 알고리즘 3182번 한동이는 공부가 하기 싫어!(python)

기본적인 그래프 탐색 문제이다. 각 노드별로 몇 명의 사람을 만날 수 있는지 확인하고, 최댓값의 인덱스를 출력해주면 된다 -> res.index(max(res)) def dfs(node, cnt): check[node] = 1 n = graph[node][0] if..

jinho-study.tistory.com

https://jinho-study.tistory.com/1099

 

백준 알고리즘 16173번 점프왕 쩰리 (Small)(python)

기본적인 BFS, DFS 문제이다. (N, N) 좌표에 도착할 수 있는지를 확인해주면 된다. BFS 풀이 from collections import deque def bfs(y, x): q = deque() q.append((y, x, li[y][x])) while q: y, x, d = q.poplef..

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

큐(Queue)는 FIFO구조로 먼저 집어넣은 데이터를 가장 먼저 뺄 수 있는 데이터 구조이다.

나중에 집어넣은 데이터가 먼저 나오는 스택(Stack)과는 반대되는 개념이다. 덱(Deque)은 양쪽 끝에서 삽입과 삭제가

모두 가능한 자료구조인데, 큐와 스택을 합친 형태라고 생각하면 쉽다. 아래 코드는 큐 코드 예시이다.

 

큐 구현 문제(10845번 큐)

import sys

class Queue():
    def __init__(self):
        self.li = []
    
    def push(self, n):
        self.li.append(n)

    def pop(self):
        print(self.li.pop(0) if self.li else -1)
    
    def size(self):
        print(len(self.li))

    def empty(self):
        print(0 if self.li else 1)
        
    def front(self):
        print(self.li[0] if self.li else -1)
        
    def back(self):
        print(self.li[-1] if self.li else -1)

queue = Queue()
for _ in range(int(sys.stdin.readline())):
    s = sys.stdin.readline().split()
    if s[0] == "push":
        queue.push(int(s[1]))
    elif s[0] == "pop":
        queue.pop()
    elif s[0] == "size":
        queue.size()
    elif s[0] == "empty":
        queue.empty()
    elif s[0] == "front":
        queue.front()
    elif s[0] == "back":
        queue.back()

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/798

 

백준 알고리즘 10845번 큐(python)

기본적인 큐 문제이다. sys.stdin.readline을 사용하지 않으면 시간 초과가 나온다. import sys class Queue(): def __init__(self): self.li = [] def push(self, n): self.li.append(n) def pop(self): print(se..

jinho-study.tistory.com

jinho-study.tistory.com/800

 

백준 알고리즘 10866번 덱(python)

기본적인 덱(Deque) 문제이다. sys.stdin.readline을 사용하지 않으면 시간 초과가 나온다. import sys class Deque(): def __init__(self): self.li = [] def push_front(self, n): self.li.insert(0, n) def pus..

jinho-study.tistory.com

jinho-study.tistory.com/802

 

백준 알고리즘 11866번 요세푸스 문제 0(python)

기본적인 큐 문제이다. 순환큐! N, K = map(int, input().split()) queue = [i for i in range(1, N+1)] res = [] for _ in range(N): for i in range(K-1): queue.append(queue.pop(0)) res.append(queue.pop(0))..

jinho-study.tistory.com

jinho-study.tistory.com/803

 

백준 알고리즘 2164번 카드2(python)

기본적인 큐 문제이다. 그냥 리스트로 큐를 구현해서 풀려고 하면 시간 초과가 나와서 collections.deque를 사용해서 풀었다. collections모듈 안의 deque가 CPython으로 구성되어 있어서 그런지 속도면에

jinho-study.tistory.com

jinho-study.tistory.com/804

 

백준 알고리즘 1966번 프린터 큐(python)

숫자들이 담긴 큐와, 인덱스들이 담긴 리스트를 같이 사용해서 풀어야 하는 문제이다. from collections import deque for _ in range(int(input())): N, M = map(int, input().split()) queue = deque(map(int, i..

jinho-study.tistory.com

jinho-study.tistory.com/807

 

백준 알고리즘 1158번 요세푸스 문제(python)

순환큐 문제이다. 11866번 요세푸스 문제 0과 같은 문제이다. 11866번은 그냥 리스트로 큐를 구현해서 풀어도 맞았었는데 이 문제는 시간초과가 나와서 속도가 매우 빠른 collections.deque를 사용했다.

jinho-study.tistory.com

jinho-study.tistory.com/808

 

백준 알고리즘 18258번 큐 2(python)

큐 문제이다. 10845번 큐와 같은 문제이다. 이 문제는 collections.deque와 sys.stdin.readline을 사용해서 풀지 않으면 시간 초과가 나온다. 주의하자. import sys from collections import deque class Queue():..

jinho-study.tistory.com

jinho-study.tistory.com/809

 

백준 알고리즘 12789번 도키도키 간식드리미(python)

스택과 큐를 둘 다 사용해야 되는 문제이다. from collections import deque N = int(input()) queue = deque(map(int, input().split())) stack = deque() i = 1 while queue: if queue and queue[0] == i: queue..

jinho-study.tistory.com

jinho-study.tistory.com/810

 

백준 알고리즘 15828번 Router(python)

기본적인 큐 문제이다. import sys from collections import deque N = int(sys.stdin.readline()) queue = deque() while 1: n = int(sys.stdin.readline()) if n == -1: break if n != 0 and len(queue) < N: qu..

jinho-study.tistory.com

jinho-study.tistory.com/811

 

백준 알고리즘 1021번 회전하는 큐(python)

기본적인 덱 문제이다. from collections import deque N, M = map(int, input().split()) li = list(map(int, input().split())) queue = deque(range(1, N+1)) cnt = 0 for n in li: while queue[0] != n: t = q..

jinho-study.tistory.com

jinho-study.tistory.com/812

 

백준 알고리즘 2161번 카드1(python)

기본적인 덱 문제이다. 2164 카드2와 거의 동일한 문제이다. from collections import deque N = int(input()) queue = deque([i for i in range(1, N+1)]) while len(queue) > 1: print(queue.popleft(), end=' '..

jinho-study.tistory.com

jinho-study.tistory.com/813

 

백준 알고리즘 2346번 풍선 터뜨리기(python)

기본적인 덱 문제이다. 조금 더 쉽게 풀 수도 있을 것 같은 문제인데 연습 삼아 그냥 이런 식으로 풀어봤다. from collections import deque N = int(input()) li = [[n, i+1] for i, n in enumerate(map(int, inp..

jinho-study.tistory.com

jinho-study.tistory.com/814

 

백준 알고리즘 13417번 카드 문자열(python)

그리디 알고리즘 & 덱 문제이다. 덱의 맨 처음 값보다 t가 크다면 덱의 맨 뒤에 t를 추가, 그렇지 않다면 덱의 맨 앞에 t를 추가해주면 된다. from collections import deque for _ in range(int(input())): N = i..

jinho-study.tistory.com

jinho-study.tistory.com/815

 

백준 알고리즘 18115번 카드 놓기(python)

기본적인 덱 문제이다. 카드 방향 때문에 되게 헷갈리는 문제이다. 난이도에 비해 푸는데 시간이 오래 걸린 것 같다. from collections import deque N = int(input()) li = deque(map(int, input().split())) aft..

jinho-study.tistory.com

jinho-study.tistory.com/816

 

백준 알고리즘 20301번 반전 요세푸스(python)

구현 & 덱 문제이다. 요세푸스 문제에서 조금 진화한 버전인 것 같은데, 오른쪽으로 돌 때는 K-1번, 왼쪽으로 돌 때는 K번 돈다는 점만 이해하면 쉽게 풀 수 있다. PyPy3로 제출해야 시간 초과가 안

jinho-study.tistory.com

jinho-study.tistory.com/821

 

백준 알고리즘 5430번 AC(python)

덱 문제이다. 생각보다 쉽지 않은 문제였다. 런타임 에러에 주의해줘야 하고 시간도 빡빡하기 때문이다. 핵심은 R이 들어올 때마다 reverse 하면 안 된다는 점이다. 이것 때문에 계속 시간 초과가

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

스택은 LIFO구조로 가장 나중에 집어넣은 데이터를 가장 먼저 뺄 수 있는 데이터 구조이다.

먼저 집어 넣은 데이터가 먼저 나오는 큐(Queue)와는 반대되는 개념이다.

 

아래 코드들은 스택을 활용하여 만들어 본 계산기이다.

1. infix 수식 -> postfix 수식 코드

tokens = input().split()
stack, output = [], []
op = {')': 3, '*': 2, '/': 2, '+': 1, '-': 1, '(': 0}
for t in tokens:
    if t not in op:
        output.append(int(t))
    elif t == '(':
        stack.append(t)
    elif t == ')':
        while stack != [] and stack[-1] != '(':
            output.append(stack.pop())
        stack.pop()
    else:
        while stack != [] and op[stack[-1]] >= op[t] :
            output.append(stack.pop())
        stack.append(t)
while stack:
    output.append(stack.pop())
print(output)

예를 들어 입력이 "( 1 + 3 ) * 2 * 4 - 1"이라면 결과는 [1, 3, '+', 2, '*', 4, '*', 1, '-']이 된다.

2. 계산 코드

nums = []
for t in output:
    if t not in op:
        nums.append(t)
    else:
        a, b = nums.pop(), nums.pop()
        if t == '+':
            nums.append(b+a)
        elif t == '-':
            nums.append(b-a)
        elif t == '*':
            nums.append(b*a)
        elif t == '/':
            nums.append(b/a)
print(nums)

( 1 + 3 ) * 2 * 4 - 1 = 31

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/792

 

백준 알고리즘 10828번 스택(python)

기본적인 스택 문제이다. import sys class Stack(): def __init__(self): self.li = [] def push(self, n): self.li.append(n) def pop(self): print(self.li.pop() if len(self.li) > 0 else -1) def size(self)..

jinho-study.tistory.com

jinho-study.tistory.com/156

 

백준 알고리즘 9012번 괄호(python)

기본적인 스택 문제이다. for _ in range(int(input())): s = input() stack, ok = [], 1 for c in s: if c == '(': stack.append(c) else: if stack == []: ok = 0 else: stack.pop() print("YES" if stack == []..

jinho-study.tistory.com

jinho-study.tistory.com/49

 

백준 알고리즘 1874번 스택 수열(python)

스택 문제이다. 처음에 문제를 이해를 못해서 시간이 많이 걸렸다. import sys n = int(sys.stdin.readline()) li = [] stack = [] result = [] index = 0 for i in range(n): li.append(int(sys.stdin.readline(..

jinho-study.tistory.com

jinho-study.tistory.com/173

 

백준 알고리즘 10773번 제로(python)

기본적인 스택 문제이다. 입력이 0이 아니면 스택에 추가하고 입력이 0이면 제일 마지막에 추가한 수를 스택에서 제거한다. 마지막에 스택에 들어있는 수들의 합을 출력해주면 된다. li = [] for _ i

jinho-study.tistory.com

jinho-study.tistory.com/793

 

백준 알고리즘 4949번 균형잡힌 세상(python)

문자열 & 스택 문제이다. while 1: s = input() if s == '.': break stack = [] ok = 1 for c in s: if c in '([': stack.append(c) elif c in ')': if stack == [] or stack[-1] != '(': ok = 0 break else: stac..

jinho-study.tistory.com

jinho-study.tistory.com/794

 

백준 알고리즘 3986번 좋은 단어(python)

기본적인 스택 문제이다. cnt = 0 for _ in range(int(input())): s = input() stack = [] for c in s: if c == 'A': if stack == [] or (stack != [] and stack[-1] != 'A'): stack.append(c) else: stack.pop()..

jinho-study.tistory.com

jinho-study.tistory.com/795

 

백준 알고리즘 1935번 후위 표기식2(python)

스택 문제이다. N = int(input()) li = list(input()) nums = [int(input()) for _ in range(N)] output = [] for t in li: if t in "+-*/": a = output.pop() b = output.pop() if t == '+': output.append(b+a)..

jinho-study.tistory.com

jinho-study.tistory.com/796

 

백준 알고리즘 2841번 외계인의 기타 연주(python)

스택을 활용해서 풀어야 되는 문제이다. 리스트 안에 여러 개의 스택이 들어있는 구조이다. else문 안에 있는 아래 코드를 생각하지 못해서 계속 틀렸었다. if li[i] != [] and li[i][-1] == p: continue 해답

jinho-study.tistory.com

jinho-study.tistory.com/797

 

백준 알고리즘 2812번 크게 만들기(python)

그리디 알고리즘 & 스택 문제이다. 스택을 활용하지 않으면 시간 초과가 나온다. 제일 큰 수로 만들려면 앞에 있는 작은 수부터 없애버려야 한다는 점이 핵심인 것 같다. N, K = map(int, input().split())

jinho-study.tistory.com

jinho-study.tistory.com/801

 

백준 알고리즘 6198번 옥상 정원 꾸미기(python)

스택을 활용해서 풀어야 하는 문제이다. for 문을 두 번 써서 풀면 절대 통과할 수가 없다. import sys N = int(sys.stdin.readline()) li = [int(sys.stdin.readline()) for _ in range(N)] stack, res = [], 0 f..

jinho-study.tistory.com

jinho-study.tistory.com/805

 

백준 알고리즘 2504번 괄호의 값(python)

스택 문제이다. 주의해야 될 점이 참 많은 문제다. 그래서 엄청 많이 틀렸다. 마지막 스택에 '(', '['가 들어있다면 잘못된 형태이므로 0을 출력, 그렇지 않다면 숫자들만 있는 것이기 때문에 스택

jinho-study.tistory.com

jinho-study.tistory.com/809

 

백준 알고리즘 12789번 도키도키 간식드리미(python)

스택과 큐를 둘 다 사용해야 되는 문제이다. from collections import deque N = int(input()) queue = deque(map(int, input().split())) stack = deque() i = 1 while queue: if queue and queue[0] == i: queue..

jinho-study.tistory.com

jinho-study.tistory.com/817

 

백준 알고리즘 12605번 단어순서 뒤집기(python)

기본적인 스택 문제이다. from collections import deque for case in range(int(input())): stack = deque(input().split()) print(f"Case #{case+1}: ", end='') while len(stack) > 1: print(stack.pop(), end=..

jinho-study.tistory.com

jinho-study.tistory.com/818

 

백준 알고리즘 17952번 과제는 끝나지 않아!(python)

구현 & 스택 문제이다. 스택이 비어있을 때를 주의해서 잘 처리해줘야 한다. 런타임 에러로 엄청 틀렸다ㅜ import sys from collections import deque stack = deque() score = 0 for _ in range(int(sys.stdin.re..

jinho-study.tistory.com

jinho-study.tistory.com/819

 

백준 알고리즘 20001번 고무오리 디버깅(python)

구현 & 스택 문제이다. 문제가 상당히 깜찍하다. from collections import deque _ = input() stack = deque() while 1: s = input() if s == "고무오리 디버깅 끝": break if s == "문제": stack.append(1) elif..

jinho-study.tistory.com

jinho-study.tistory.com/820

 

백준 알고리즘 17298번 오큰수(python)

스택 문제이다. 처음에 스택에 인덱스 말고 수열의 원소를 넣는 방식으로 생각해서 못 풀었다. 결국 해답을 봤는데 한 끗 차이였다ㅠ 내일 다시 풀어봐야겠다. from collections import deque N = int(input()

jinho-study.tistory.com

jinho-study.tistory.com/827

 

백준 알고리즘 10799번 쇠막대기(python)

기본적인 스택 문제이다. 딱 작년만 해도 이 문제를 못 풀었었는데 이제는 쉽게 풀 수 있게 되었다. 굿!! from collections import deque s = input() stack = deque() res = 0 for c in s: if c == '(': stack.ap..

jinho-study.tistory.com

jinho-study.tistory.com/828

 

백준 알고리즘 2493번 탑(python)

17298번 오큰수 문제와 거의 동일한 스택 문제이다. 오큰수는 앞에서부터 확인하면서 스택을 쌓아다면 이 문제는 뒤에서 부터 확인하면서 스택을 쌓으면 된다. PyPy3로 제출해야 통과된다. from colle

jinho-study.tistory.com

jinho-study.tistory.com/829

 

백준 알고리즘 1918번 후위 표기식(python)

기본적인 스택 문제이다. 내가 스택 맨 처음 공부할 때 봤던 것이 후위 표기식 구현 코드였는데 이렇게 문제로 보니 반갑다! li = list(input()) op = {'(': 0, '+':1, '-': 1, '*': 2, '/': 2, ')': 3} stack, ou..

jinho-study.tistory.com

jinho-study.tistory.com/1046

 

백준 알고리즘 17608번 막대기(python)

기본적인 스택 문제이다. import sys input = sys.stdin.readline N = int(input()) li = [int(input()) for _ in range(N)] stack, cnt = [li.pop()], 1 for n in li[::-1]: if stack[-1] < n: cnt += 1 stack.ap..

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

그리디 알고리즘은 최적해를 구하는 데에 사용되는 근사적인 방법으로, 여러 경우 중 하나를 결정해야 할 때마다 그 순간에 최적이라고 생각되는 것을 선택해 나가는 방식으로 진행하여 최종적인 해답에 도달한다.

정렬을 사용하면 쉽게 풀 수 있는 그리드 알고리즘 문제들이 되게 많다.

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/62

 

백준 알고리즘 1931번 회의실배정(python)

그리디 알고리즘 문제이다. 정렬을 사용하면 쉽게 풀 수 있다! lambda를 사용해 끝나는 시간 순으로 정렬해주는 게 핵심이다. li = [list(map(int, input().split())) for _ in range(int(input()))] li = sorted(..

jinho-study.tistory.com

jinho-study.tistory.com/111

 

백준 알고리즘 2839번 설탕 배달(python)

5킬로그램짜리를 최대한 많이 배달하는 게 포인트다. 입력 N이 5로 나누어질 때까지 3을 계속 빼고 이 과정을 몇 번 반복했는지 새면 된다. 3을 계속 빼도 끝까지 5로 나누었을 때 0이 안된다면 N킬

jinho-study.tistory.com

jinho-study.tistory.com/198

 

백준 알고리즘 11399번 ATM(python)

우선 입력을 리스트에 저장하고 오름차순 정렬해준다. 그 후 첫 번째 값부터 마지막 값까지 누적 값을 순서대로 더해주면 된다. EX) 입력: 3, 1, 4, 3, 2 리스트로 만든 후 정렬 -> [1, 2, 3, 3, 4] 누적 값

jinho-study.tistory.com

jinho-study.tistory.com/195

 

백준 알고리즘 11047번 동전 0(python)

K이하인 동전 중에서 제일 큰 것부터 순서대로 꽉꽉 채운다는 느낌으로 풀면 된다. EX) K = 4200, 입력: 1 5 10 50 100 500 1000 5000 10000 50000 ans = 0 1) 4200 - 1000*4 = 200 -> ans = 0 + 4 = 4 2) 200 - 1..

jinho-study.tistory.com

jinho-study.tistory.com/301

 

백준 알고리즘 5585번 거스름돈(python)

11047번 동전 0과 거의 똑같은 문제이다. 거스름돈보다 싼 동전 중에서 제일 큰 것부터 순서대로 꽉꽉 채운다는 느낌으로 풀면 된다. change = 1000 - int(input()) cnt = 0 for c in [500, 100, 50, 10, 5, 1]: i..

jinho-study.tistory.com

jinho-study.tistory.com/39

 

백준 알고리즘 1541번 잃어버린 괄호(python)

처음으로 '-'가 나오는 순간부터 그 뒤에 있는 숫자들은 무조건 빼야 된다는 것을 이해하면 간단하게 풀 수 있다! EX) 입력이 "55+10-50+40-20+20"이면 li = ["55+10", "50+40", "20+20"]가 되는데 처음 요소인 "5.

jinho-study.tistory.com

jinho-study.tistory.com/75

 

백준 알고리즘 2217번 로프(python)

k개의 로프를 사용할 때 들어 올릴 수 있는 중량은 버틸 수 있는 중량이 제일 작은 로프의 최대 중량 * k라는 점이 핵심이다. EX) 15, 10 로프 2개를 사용할 경우 최대 10 * 2 = 20인데 이유는 15가 10보

jinho-study.tistory.com

jinho-study.tistory.com/36

 

백준 알고리즘 1449번 수리공 항승(python)

물이 샌 곳을 막는데 막대기는 왼쪽 끝과 오른쪽 끝 0.5를 제외한 1만큼의 여유가 필요하다. 현재 물이 샌 곳에 테이프 길이를 더하고 1을 뺀 값이 다음 물이 샌 곳보다 작으면 막대기 한 개가 필

jinho-study.tistory.com

jinho-study.tistory.com/302

 

백준 알고리즘 1439번 뒤집기(python)

입력으로 받은 문자열이 0에서 1로, 1에서 0으로 총 몇 번 바뀌는지를 구하면 쉽게 풀 수 있다. 홀수번 바뀔 경우 -> cnt//2 + 1 짝수번 바뀔 경우 -> cnt//2 s = input() cnt = 0 for i in range(len(s)-1): if s..

jinho-study.tistory.com

jinho-study.tistory.com/303

 

백준 알고리즘 2847번 게임을 만든 동준이(python)

마지막 레벨의 점수부터 확인을 하는데, 만약 뒷 단계보다 앞 단계의 점수가 더 크다면 앞 단계의 점수를 뒷 단계의 점수보다 1 작게 되도록 빼주면 된다. N = int(input()) li = [int(input()) for _ in range(N

jinho-study.tistory.com

jinho-study.tistory.com/304

 

백준 알고리즘 1946번 신입 사원(python)

서류심사 성적을 기준으로 오름차순 정렬 -> 면접 성적의 최솟값(확인한 것 중 제일 높은 순위)이 몇 번 업데이트되는지 확인 for _ in range(int(input())): N = int(input()) li = [list(map(int, input().split..

jinho-study.tistory.com

jinho-study.tistory.com/305

 

백준 알고리즘 4796번 캠핑(python)

간단한 수학 문제이다. min(V%P, L) 부분이 핵심인 것 같다. i = 1 while 1: L, P, V = map(int, input().split()) if L == 0 and P == 0 and V == 0: break res = L*(V//P) + min(V%P, L) print("Case {0}: {1}"...

jinho-study.tistory.com

jinho-study.tistory.com/306

 

백준 알고리즘 13305번 주유소

기름 가격의 최솟값을 잘 사용하면 쉽게 풀 수 있다. -> res += 현재까지 확인한 기름 가격들의 최솟값 * 현재 가야 되는 거리 EX) dis = [2, 3, 1], oil = [5, 2, 4, 1] 처음엔 기름 가격의 최솟값이 5이므로 5*

jinho-study.tistory.com

https://jinho-study.tistory.com/1101

 

백준 알고리즘 11256번 사탕(python)

기본적인 그리디 알고리즘 문제이다. for _ in range(int(input())): j, N = map(int, input().split()) li = [] for i in range(N): r, c = map(int, input().split()) li.append(r*c) li.sort(reverse=True) cnt..

jinho-study.tistory.com

 

728x90
반응형
728x90
반응형

이분 탐색은 정렬된 리스트에서 특정한 값의 위치를 찾아내는 알고리즘이다. 

리스트에서 어떤 특정 값(X)을 찾을 때, 리스트의 가운데 값(M)을 기준으로 비교하면서 탐색하는 방식인데

X가 M보다 크다면 리스트의 오른쪽 부분, X가 M보다 작다면 리스트의 왼쪽 부분을 사용 

-> 다시 가운데 값을 정의 -> 앞의 두 과정을 X == M일 때까지 반복하는 식이다.

def binarySearch(li, n):
    # s: 맨 앞 인덱스, e: 맨 뒤 인덱스
    s, e = 0, len(li)-1
    while s <= e:
        # m:가운데 인덱스
        m = (s + e) // 2 
        if li[m] == n: 
            return 1
        if n > li[m]:
            s = m + 1
        else:
            e = m - 1
    return 0

위 코드는 리스트(li)에 특정 값(n)이 있는지를 확인하는 이분 탐색 함수인데, 아래와 같은 방식으로 돌아간다.

예시

[1,2,3,4,5,6] 리스트에서 5를 찾는 상황인데 

첫 번째 중앙값보다 n이 더 크므로 리스트의 오른쪽 부분을 사용해서 다시 비교한다.

두 번째 중앙값은 5와 같으므로 반복문이 끝이 나는 식이다.

 

아래는 위의 이미지 같은 이분 탐색 과정을 출력해주는 코드이다.

def binarySearch(li, n):
    s, e = 0, len(li)-1
    i = 1
    while s <= e:
        m = (s + e) // 2 
        print("%d번째 반복" % (i))
        print("s: %d e: %d m: %d" % (s, e, m))
        print("n: %d li[m]: %d\n" % (n, li[m]))
        i += 1
        
        if li[m] == n:
            print("목표 찾음!")
            return 1
        if n > li[m]:
            s = m + 1
        else:
            e = m - 1
    print("목표 못찾음!")
    return 0


binarySearch([1, 2, 3, 4, 5, 6], 5)

 

참고로 python에는 bisect라는 이분 탐색 라이브러리가 존재해서 아래와 같은 방식으로 쉽게 사용할 수 있다!

import bisect
mylist = [1, 2, 3, 7, 9, 11, 33]
print(bisect.bisect(mylist, 3))

 

아래는 내가 풀었던 백준 알고리즘에 있는 이분 탐색 관련 문제들이다.

문제를 풀면서 직접 적용해보는 게 나는 이해가 훨씬 빨리 됐던 것 같다. 꼭 문제를 풀어보도록 하자!

 

백준 알고리즘 문제 풀이)

jinho-study.tistory.com/307

 

백준 알고리즘 1920번 수 찾기(python)

아주 기본적인 이분 탐색 문제이다! def binarySearch(li, n): s, e = 0, len(li)-1 while s <= e: m = (s + e) // 2 if li[m] == n: return 1 elif li[m] <= n: s = m + 1 else: e = m - 1 return 0 _ = int(inpu..

jinho-study.tistory.com

jinho-study.tistory.com/293

 

백준 알고리즘 10815번 숫자 카드(python)

간단한 이분 탐색 문제다 def binarySearch(li, n): s, e = 0, len(li)-1 while s <= e: m = (s + e) // 2 if li[m] == n: return 1 if n > li[m]: s = m + 1 else: e = m - 1 return 0 N = int(input()) li1 = so..

jinho-study.tistory.com

jinho-study.tistory.com/295

 

백준 알고리즘 10816번 숫자 카드 2(python)

10815번 숫자 카드 문제랑 비슷한데. 개수를 새야 한다는 점만 다르다. 이 문제는 이분 탐색 또는 딕셔너리를 사용해서 풀 수 있는데, 딕셔너리를 사용해서 푸는 게 효율적인 것 같다. 이분 탐색

jinho-study.tistory.com

jinho-study.tistory.com/296

 

백준 알고리즘 1764번 듣보잡(python)

집합을 사용한 방식 합집합을 사용하면 쉽게 풀 수 있다. a, b = map(int, input().split()) s1, s2 = set(), set() for _ in range(a): s1.add(input()) for _ in range(b): s2.add(input()) li = sorted(s1 & s2..

jinho-study.tistory.com

jinho-study.tistory.com/46

 

백준 알고리즘 1789번 수들의 합(python)

단순한 방식 입력보다 커지기 전까지 1, 2, 3, 4, 5... 를 계속 더하다가 마지막으로 더해진 값을 출력해주면 된다. 1부터 n까지 수의 합 = n * (n+1) // 2 n = int(input()) i = 1 while i * (i+1) // 2 <= n: i..

jinho-study.tistory.com

jinho-study.tistory.com/297

 

백준 알고리즘 2110번 공유기 설치(python)

저번에 푼 적이 있는 문제인데 그때도 해답을 봤는데 이번에도 풀지 못해서 해답을 봤다. 이해를 완전히 못했나 보다. 이분 탐색 문제인데 count 함수가 핵심 부분이다. 나는 저 생각을 못해서 못

jinho-study.tistory.com

jinho-study.tistory.com/298?category=911939

 

백준 알고리즘 1654번 랜선 자르기(python)

이분 탐색 문제이다. 2110번 공유기 설치와 비슷한 문제다. def count(li, m): cnt = 0 for n in li: cnt += (n // m) return cnt def binarySearch(li, K): s, e = 1, max(li) while s <= e: m = (s + e) // 2 if..

jinho-study.tistory.com

jinho-study.tistory.com/308

 

백준 알고리즘 2805번 나무 자르기(python)

이분 탐색을 활용해서 풀어야 되는 문제이다. 절단기의 높이가 m일 때 가져갈 수 있는 나무의 길이가 M 이상이면 절단기의 높이를 올려도 되므로 s = m + 1 작다면 높이를 내려야 하므로 e = m - 1을

jinho-study.tistory.com

jinho-study.tistory.com/309

 

백준 알고리즘 2512번 예산(python)

2805번 나무 자르기와 거의 똑같은 문제이다. 이제 이런 종류의 이분 탐색 문제는 익숙해진 건지 3분 만에 풀었다! def binarySearch(li, M): s, e = 1, max(li) ans = 0 while s <= e: m = (s + e) // 2 t = 0 fo..

jinho-study.tistory.com

jinho-study.tistory.com/311

 

백준 알고리즘 7795번 먹을 것인가 먹힐 것인가(python)

단순하게 A랑 B를 비교하면서 개수를 새면 시간 초과가 나와서 이분 탐색을 사용했다. 이분 탐색을 사용해 B에서 A의 한 요소(a) 보다 작은 수들 중에 제일 큰 수의 위치(인덱스)를 찾는 것이 핵심

jinho-study.tistory.com

jinho-study.tistory.com/338

 

백준 알고리즘 15641번 SUPER SUPER BINARY SEARCH DELUXE 2.5: THE LEGEND OF THE GOLDEN MAZASSUMNIDA, EPISODE 2: THE MAZWAET

1부터 100 사이의 숫자를 찍어서 맞춰야 되는 이상한 구데기 문제이다. 이분 탐색을 코드로 구현하는 게 아니라 직접 하게 만든다ㅋㅋㅋ 내 정답은 19였다.

jinho-study.tistory.com

jinho-study.tistory.com/494

 

백준 알고리즘 4623번 Copier Reduction(python)

단순 사칙연산 문제이다. 처음엔 아래 코드같이 풀었는데 통과가 안됐다. 뭐가 틀린 건지 아직 모르겠다. while 1: A, B, C, D = map(int, input().split()) if A == B == C == D == 0: break s1 = max(A, B)/max(..

jinho-study.tistory.com

jinho-study.tistory.com/685

 

백준 알고리즘 1072번 게임(python)

이분 탐색 문제이다. 100을 나중에 곱해주면 오차가 생겨서 틀린다. 먼저 곱해주고 //을 써서 나누도록 하자 x, y = map(int, input().split()) p = y*100//x s, e = 0, 1000000000 res = 0 while s <= e: m = (s+..

jinho-study.tistory.com

jinho-study.tistory.com/686

 

백준 알고리즘 1590번 캠프가는 영식(python)

이분 탐색 & 브루트포스 알고리즘 문제이다. 이분 탐색을 통해 각 버스별로 기다려야 되는 시간을 구하고, 버스를 탈 수 있는 경우가 없다면(res == []) -1을 출력 버스를 탈 수 있는 경우가 있다면

jinho-study.tistory.com

jinho-study.tistory.com/687

 

백준 알고리즘 2022번 사다리(python)

수학 & 이분 탐색 문제이다. 위 그림에서 w1 : c = w : h2, w2 : c = w : h1라는 점을 통해 w1 = c*w / h2, w2 = c*w / h1 w = w1 + w2 = c*w / h2 + c*w / h1 = c*w*(h1+h2) / (h1*h2) -> 1 = c*(h1+h2) /..

jinho-study.tistory.com

jinho-study.tistory.com/688

 

백준 알고리즘 2343번 기타 레슨(python)

이분 탐색 문제이다. 처음에 s를 1로 했다가 계속 틀렸다. 제일 긴 음악의 길이로 시작하는 게 맞다 -> s = max(li) def count(li, m): t = cnt = 0 for n in li: if t+n > m: cnt += 1 t = n else: t += n return..

jinho-study.tistory.com

jinho-study.tistory.com/689

 

백준 알고리즘 2417번 정수 제곱근(python)

이분 탐색 문제이다. 이분 탐색 안쓰고 그냥 반복문 돌려서 풀면 시간 초과가 나온다. n = int(input()) s, e = 0, int((2**63)**0.5)+1 res = 0 while s <= e: m = (s+e)//2 if m**2 >= n: res = m e = m-1 else:..

jinho-study.tistory.com

jinho-study.tistory.com/690

 

백준 알고리즘 2428번 표절(python)

이분 탐색 문제이다. 이제 이분 탐색에 조금 익숙해진 것 같다! N = int(input()) li = sorted(map(int, input().split())) res = 0 for i in range(N-1): s, e = i+1, N-1 t = -1 while s <= e: m = (s+e)//2 if..

jinho-study.tistory.com

jinho-study.tistory.com/691

 

백준 알고리즘 2776번 암기왕(python)

이분 탐색 문제이다. def bs(li, n): s, e = 0, len(li)-1 while s <= e: m = (s+e)//2 if li[m] == n: return 1 elif li[m] < n: s = m+1 else: e = m-1 return 0 for _ in range(int(input())): N = int(input()..

jinho-study.tistory.com

jinho-study.tistory.com/692

 

백준 알고리즘 3079번 입국심사(python)

이분 탐색 문제이다. N, M = map(int, input().split()) li = [int(input()) for _ in range(N)] s, e = 0, max(li)*M res = 0 while s <= e: m = (s+e)//2 t = sum([m//n for n in li]) if t >= M: res = m e = m..

jinho-study.tistory.com

jinho-study.tistory.com/693

 

백준 알고리즘 6236번 용돈 관리(python)

이분 탐색 문제이다. def count(li, m): t = cnt = 0 for n in li: if t+n > m: t = n cnt += 1 else: t += n return cnt+1 N, M = map(int, input().split()) li = [int(input()) for _ in range(N)] s, e = max(..

jinho-study.tistory.com

jinho-study.tistory.com/694

 

백준 알고리즘 13702번 이상한 술집(python)

이분 탐색 문제이다. N, K = map(int, input().split()) li = [int(input()) for _ in range(N)] s, e = 1, max(li) res = 0 while s <= e: m = (s+e)//2 t = sum(n//m for n in li) if t >= K: res = m s = m+1 e..

jinho-study.tistory.com

jinho-study.tistory.com/717

 

백준 알고리즘 1166번 선물(python)

이분 탐색 문제이다. N, L, W, H = map(int, input().split()) s, e = 0, max(L, W, H) for _ in range(10000): m = (s+e)/2 if (L//m)*(W//m)*(H//m) >= N: s = m else: e = m print("%.10f" %(e)) 처음에 아래같..

jinho-study.tistory.com

jinho-study.tistory.com/718

 

백준 알고리즘 19637번 IF문 좀 대신 써줘(python)

이분 탐색 문제이다. sys.stdin.readline 함수를 사용해서 입력을 받지 않으면 이분 탐색 알고리즘을 사용해도 시간초과가 나온다. import sys def bs(li, n): s, e = 0, len(li)-1 res = 0 while s <= e: m = (s+..

jinho-study.tistory.com

jinho-study.tistory.com/719

 

백준 알고리즘 16401번 과자 나눠주기(python)

이분 탐색 문제이다. M, N = map(int, input().split()) li = list(map(int, input().split())) s, e = 1, max(li) res = 0 while s <= e: m = (s+e)//2 if sum([n//m for n in li]) >= M: res = m s = m+1 else:..

jinho-study.tistory.com

jinho-study.tistory.com/720

 

백준 알고리즘 16564번 히오스 프로게이머(python)

이분 탐색 문제이다. def count(li, m): t = 0 for n in li: if n >= m: break t += m-n return t N, K = map(int, input().split()) li = sorted([int(input()) for _ in range(N)]) s, e = min(li), max(li)+K r..

jinho-study.tistory.com

jinho-study.tistory.com/721

 

백준 알고리즘 17245번 서버실(python)

이분 탐색 문제이다. 2차원 리스트의 총합과 최댓값을 알아야 문제를 풀 수 있어서 코드가 좀 길어진 것 같다. def count(li, m, N): t = 0 for i in range(N): for j in range(N): t += (m if m <= li[i][j] else..

jinho-study.tistory.com

jinho-study.tistory.com/822

 

백준 알고리즘 1300번 K번째 수(python)

의외로 이분 탐색으로 풀 수 있는 문제이다. 내일 다시 한 번 풀어봐야겠다. N, K = int(input()), int(input()) s, e = 1, K ans = 0 while s <= e: m = (s+e)//2 t = 0 for i in range(1, N+1): t += min(N, m//..

jinho-study.tistory.com

jinho-study.tistory.com/850

 

백준 알고리즘 18113번 그르다 김가놈(python)

이분 탐색 문제이다. 처음에 e를 max(li)-2*K로 설정하는 허튼짓을 하는 바람에 엄청나게 많이 틀렸다. s가 0이면 0으로 나눌 경우가 생길 수 있기 때문에 1로 시작해야 된다. PyPy3로 제출해야 통과된

jinho-study.tistory.com

jinho-study.tistory.com/961

 

백준 알고리즘 13777번 Hunt The Rabbit(python)

기본적인 이분 탐색 문제이다. while 1: n = int(input()) if n == 0: break s, e = 1, 50 while s <= e: m = (s+e)//2 print(m, end=' ') if m == n: break elif m < n: s = m+1 else: e = m-1 print()

jinho-study.tistory.com

jinho-study.tistory.com/956

 

백준 알고리즘 17266번 어두운 굴다리(python)

기본적인 이분 탐색 문제이다. def bs(li, m): if li[1]-li[0] > m: return 0 if li[-1]-li[-2] > m: return 0 for i in range(1, len(li)-2): if (li[i+1]-li[i])/2 > m: return 0 return 1 N, M = int(input()),..

jinho-study.tistory.com

jinho-study.tistory.com/1028

 

백준 알고리즘 15810번 풍선 공장(python)

이분 탐색 Or 우선순위 큐 문제라는데, 이분 탐색이 훨씬 효율적일 것 같아서 그냥 이분 탐색으로 풀었다. N, M = map(int, input().split()) li = list(map(int, input().split())) s, e = 0, max(li)*M res = 0..

jinho-study.tistory.com

 

728x90
반응형

+ Recent posts