import sys
from collections import deque
# 까다로웠던 점 
# 회전은 전부 판별이 되고 난뒤에, 작동한다
gears =[ list(deque(map(deque,sys.stdin.readline().split()))) for _ in range(4)]

K = int(sys.stdin.readline())
# 12시 0, 3시 2, 9시 6
# N극은 0 S극은 1
for _ in range(K):
    index,rotate = list(map(int,sys.stdin.readline().split()))
    leftindex = index-1
    leftrotate = -rotate
    rightrotate = -rotate
    rightindex = index+1
    rotatelist = []
    while leftindex >=1:
        origingear = list(gears[leftindex][0])
        leftgear = list(gears[leftindex-1][0])
        if origingear[6] == leftgear[2]:
            break
        else:
            rotatelist.append([leftindex-1,leftrotate])
        leftrotate = -leftrotate
        leftindex-=1
    while rightindex <=4:
        origingear = list(gears[rightindex-2][0])
        rightgear = list(gears[rightindex-1][0])
        if origingear[2] == rightgear[6]:
            break
        else:
            rotatelist.append([rightindex-1,rightrotate])
        rightrotate = -rightrotate
        rightindex+=1
    for rotateindex,rotation in rotatelist:
        gears[rotateindex][0].rotate(rotation)
    gears[index-1][0].rotate(rotate)


result = 0

for i in range(4):
    tw = gears[i][0].popleft()
    if tw == '1':
        result += 2**i

print(result)

이 문제에서 까다로웠던 점은 한번 사이클이 다 돌고 난뒤에 회전을 한다는 것이다. 그 부분을 처음에 놓쳤기에 틀렸다.

deque 모듈에는 rotate라는 메소드가 있으며, 양수를 적으면, 양수만큼 오른쪽으로 이동하고, 음수를 적으면 음수의 크기만큼 왼쪽으로 이동하는 것을 이용하여, 반시계와 시계방향의 회전을 구현했다.

'알고리즘 > 백준' 카테고리의 다른 글

[BOJ] 16918 봄버맨(풀이 방식 2종류)  (0) 2021.01.10
[BOJ] 16236 아기상어  (0) 2021.01.10
[BOJ] 11654 아스키 코드  (0) 2021.01.09
[BOJ] 10989 수 정렬하기3  (0) 2021.01.09
[BOJ] 9498 시험성적  (0) 2021.01.09
print(ord(input()))

'알고리즘 > 백준' 카테고리의 다른 글

[BOJ] 16236 아기상어  (0) 2021.01.10
[BOJ] 14891 톱니바퀴  (0) 2021.01.09
[BOJ] 10989 수 정렬하기3  (0) 2021.01.09
[BOJ] 9498 시험성적  (0) 2021.01.09
[BOJ] 7576 토마토  (0) 2021.01.09
# 출력을 할때에도 여러번 반복하는 것이면 곱해서 하자 곱하기가 된다.


import sys
N = int(sys.stdin.readline())
array = [0 for _ in range(10001)]
for _ in range(N):
    num = int(sys.stdin.readline())
    array[num] += 1
for k in range(10001):
    print(f'{k}\n'*array[k],end='')

처음에 출력을 할떄

if array[k]:
   for _ in range(array[k]):
        pirnt(k)

위와 같은 식으로 했었다. 그랬더니 무수한 메모리 초과 오류가 발생했다.

아마도 매번 range(array[k]) 만큼의 리스트를 만들어줘야했기에, 메모리가 초과 된것 같다.

 

크게 두가지 방법이 있는것 같아다.

 

sys에 있는 write를 이용해 출력을 하는방법과

print()를 횟수만큼 곱해서 하는방법이 있었다.

그 중에서 나는 후자를 선택했다.

'알고리즘 > 백준' 카테고리의 다른 글

[BOJ] 14891 톱니바퀴  (0) 2021.01.09
[BOJ] 11654 아스키 코드  (0) 2021.01.09
[BOJ] 9498 시험성적  (0) 2021.01.09
[BOJ] 7576 토마토  (0) 2021.01.09
[BOJ] 7569 토마토  (0) 2021.01.09
N = int(input())

if N >= 90:
    print('A')
elif N >= 80:
    print('B')
elif N >= 70:
    print('C')
elif N >= 60:
    print('D')
else:
    print('F')

 

'알고리즘 > 백준' 카테고리의 다른 글

[BOJ] 11654 아스키 코드  (0) 2021.01.09
[BOJ] 10989 수 정렬하기3  (0) 2021.01.09
[BOJ] 7576 토마토  (0) 2021.01.09
[BOJ] 7569 토마토  (0) 2021.01.09
[BOJ] 2751 수 정렬하기 2  (0) 2021.01.09
# 7576번 문제 
# 1은 익은 토마토 0은 익지않은 토마토

N,M = map(int,input().split())

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

dx = [-1,1,0,0]
dy = [0,0,1,-1]
tomatocnt = 0
total = N*M
tomato = []
for x in range(M):
    for y in range(N):
        if tomatoarray[x][y] == 1:
            tomato.append((x,y))
            tomatocnt += 1
        elif tomatoarray[x][y] == -1:
            total -= 1
result = -1
day = 0
if total == tomatocnt:
    result = 0
else:
    while tomato:
        new_tomato = []
        for x,y in tomato:
            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]
                if 0<=nx<M and 0<=ny<N:
                    if not tomatoarray[nx][ny]:
                        tomatoarray[nx][ny] = 1
                        new_tomato.append((nx,ny))
                        tomatocnt += 1


        day += 1
        if tomatocnt == total:
            result = day
            break
        if len(new_tomato):
            tomato = [row[:] for row in new_tomato]
        else:
            result = -1
            break



print(result)

익은 토마토를 기준으로 상하좌우로 인접한 토마토들만 익는다. 

 

1일차의 토마토가 익힌 인접 토마토들이 2일차에 새로운 토마토들을 익히게 된다.

그러므로 1일차의 토마토들은 필요 없어진다.

 

이런한 점을 이용해, 반복문을 통해 새롭게 익은 토마토들을 찾아내고, 그때 토마토 개수를 늘려준다. 

 

그리고 난뒤 전체 행렬의 크기와 토마토 개수가 같으면 반복문을 탈출하고,

 

새롭게 익은 토마토들이 있으면, 더 익힐 가능성이 있으므로, 그 리스트를 복사해서 반복해준다.

 

하지만 새롭게 익은 토마토들이 없으면, 더이상 익힐 가능성이 없으므로, 반복문을 탈출해서 -1을 출력해주면 된다.

'알고리즘 > 백준' 카테고리의 다른 글

[BOJ] 10989 수 정렬하기3  (0) 2021.01.09
[BOJ] 9498 시험성적  (0) 2021.01.09
[BOJ] 7569 토마토  (0) 2021.01.09
[BOJ] 2751 수 정렬하기 2  (0) 2021.01.09
[BOJ] 2606 바이러스  (0) 2021.01.09
# 7569 토마토

M,N,H = map(int,input().split())

dx = [-1,1,0,0,0,0]
dy = [0,0,-1,1,0,0]
dz = [0,0,0,0,-1,1]

tomatoarray =[ [list(map(int,input().split())) for _ in range(N)] for _ in range(H)]
# tomato dz dx dy
# H,N,M

total = N*M*H
tomatocnt = 0
tomatos = []
result = -1
day = 0
for x in range(N):
    for y in range(M):
        for z in range(H):
            if tomatoarray[z][x][y] == 1:
                tomatos.append((x,y,z))
                tomatocnt += 1
            elif tomatoarray[z][x][y] == -1:
                total -= 1
if total == tomatocnt:
    result = 0
else:
    while tomatos:
        new_tomato = []
        for x,y,z in tomatos:
            for i in range(6):
                nx = x + dx[i]
                ny = y + dy[i]
                nz = z + dz[i]
                if 0<=nx<N and 0<=ny<M and 0<=nz<H:
                    if not tomatoarray[nz][nx][ny]:
                        tomatoarray[nz][nx][ny] = 1
                        tomatocnt += 1
                        new_tomato.append((nx,ny,nz))
        day += 1
        if tomatocnt == total:
            result = day
            break
        if len(new_tomato):
            tomatos = [row[:] for row in new_tomato]
        else:
            result = -1
            break
print(result)

 

이 문제는 7576번 문제의 3D 버전이다 여기서 조심해야할 것은 3차원이고, x,y,z의 순서를 조심해주면 된다.

보통 문제를 풀때 나같은 경우 x축을 행으로 하고 y축을 열로 한다. 자신만의 기준을 가지고, 헷갈리지 않게 조심하면 될 것 같다.

기본 원리는 7576번하고 같다.

'알고리즘 > 백준' 카테고리의 다른 글

[BOJ] 9498 시험성적  (0) 2021.01.09
[BOJ] 7576 토마토  (0) 2021.01.09
[BOJ] 2751 수 정렬하기 2  (0) 2021.01.09
[BOJ] 2606 바이러스  (0) 2021.01.09
[BOJ] 2178 미로탐색  (0) 2021.01.09
import sys

N = int(sys.stdin.readline())
array = [0]* 2000001
for _ in range(N):
    num = int(sys.stdin.readline())
    num += 1000000
    array[num] += 1

for num in range(2000001):
    print(f'{num-1000000}\n'*array[num],end='')

 

문제에서 수의 크기가 100만이므로 200만1개의 리스트를 만들어주고 반복문을 돌려주었다.

 

'알고리즘 > 백준' 카테고리의 다른 글

[BOJ] 7576 토마토  (0) 2021.01.09
[BOJ] 7569 토마토  (0) 2021.01.09
[BOJ] 2606 바이러스  (0) 2021.01.09
[BOJ] 2178 미로탐색  (0) 2021.01.09
[BOJ] 1764 듣보잡  (0) 2021.01.09
def dfs(N):
    stack = [1]
    visted = [0]*(N+1)
    cnt = 0
    visted[1] = 1
    while stack:
        num = stack.pop()
        cnt += 1
        for ind in graph[num]:
            if not visted[ind]:
                visted[ind] = 1
                stack.append(ind)
    return cnt - 1

N = int(input())
M = int(input())
graph = [[] for _ in range(N+1)]
for _ in range(M):
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)


print(dfs(N))

기본적인 DFS였다. 방향성이 없기 때문에, graph라는 리스트에 양방향으로 전부 저장시켜주고, 방문을 표시해준뒤, 1번 컴퓨터에 연결된 모든 노드들을 찾아주면 된다.

'알고리즘 > 백준' 카테고리의 다른 글

[BOJ] 7569 토마토  (0) 2021.01.09
[BOJ] 2751 수 정렬하기 2  (0) 2021.01.09
[BOJ] 2178 미로탐색  (0) 2021.01.09
[BOJ] 1764 듣보잡  (0) 2021.01.09
[BOJ] 1697 숨바꼭질  (0) 2021.01.09

+ Recent posts