본문 바로가기
728x90

알고리즘52

[알고리즘개념]구간합 11659. 구간 합 구하기 4 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWr.. 2023. 6. 15.
[백준]230410-230416 문제풀이(Python) 1774. 우주신과의 교감 import sys input = sys.stdin.readline def find(x): if parents[x] != x: parents[x] = find(parents[x]) return parents[x] def union(x, y): x = find(x) y = find(y) if x < y: parents[y] = x else: parents[x] = y N, M = map(int, input().split()) gods = [] for _ in range(N): r, c = map(int, input().split()) gods.append((r, c)) dist = [[0] * (N + 1) for _ in range(N + 1)] for i in range(N).. 2023. 4. 20.
[백준]230403-09 문제풀이(Java) 10809. 알파벳 찾기 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] arr = new int[26]; for(int i = 0; i < arr.length; i++) { arr[i] = -1; } String S = in.nextLine(); for(int i = 0; i < S.length(); i++) { char ch = S.charAt(i); if(arr[ch - 'a'] == -1) { arr[ch - 'a'] = i; } } for(int val : arr) { System.out.print(val + " .. 2023. 4. 9.
[백준]230403-09 문제풀이(Python) 9328. 열쇠 from collections import deque import sys input = sys.stdin.readline dy = [-1, 1, 0, 0] dx = [0, 0, -1, 1] def bfs(y, x): global ans q = deque() q.append((y, x)) visited = [[False] * (w + 2) for _ in range(h + 2)] visited[y][x] = True while q: cnt = 0 now = q.popleft() for d in range(4): ny, nx = now[0] + dy[d], now[1] + dx[d] if ny h + 1 or nx w + 1: continue if .. 2023. 4. 9.
[SWEA]230404 문제풀이 최소 이동거리 def dijkstra(n, s): for i in adj[n]: nxt, d = i if distance[nxt] N - 1 or nx N - 1: continue fuel = 1 if lst[ny][nx] > lst[y][x]: fuel += lst[ny][nx] - lst[y][x] if distance[ny][nx] > distance[y][x] + fuel: distance[ny][nx] = distance[y][x] + fuel heapq.heappush(q, (ny, nx)) ans = distance[-1][-1] print(f'#{tc} {ans}') 01BFS에서 높이 차이에 따른 연료의 소모량까지 고려해줘야 하는 문제. 마찬가지로 효율적인 경로를 우.. 2023. 4. 4.
[백준]230403 문제풀이 10171. 고양이 public class Main { public static void main(String[] args) { System.out.println("\\ /\\"); System.out.println(" ) ( \')"); System.out.println("( / )"); System.out.println(" \\(__)|"); } } 첫 자바 코드 제출기념! 패키지 제외, 메인 클래스는 포함해서 제출한다 2023. 4. 3.
[백준]230327-0402 문제풀이 21278. 호석이 두마리 치킨 from collections import deque import sys input = sys.stdin.readline N, M = map(int, input().split()) adj = [[0] * (N + 1) for _ in range(N + 1)] ans = (0, 0, 1e10) for i in range(M): a, b = map(int, input().split()) adj[a][b] = adj[b][a] = 1 def bfs(n): q = deque() q.append((n, 1)) visited = [n] while q: now, c = q.popleft() for nxt in range(1, N + 1): if adj[now][nxt] == 1 and.. 2023. 4. 3.
[백준]230320-26 문제풀이 23843. 콘센트 import heapq import sys input = sys.stdin.readline N, M = map(int, input().split()) lst = list(map(int, input().split())) lst.sort() q = [] temp = [] ans = 0 while lst: now = lst.pop() heapq.heappush(q, now) if len(q) == M: out = heapq.heappop(q) ans += out for i in range(M - 1): q[i] -= out while q and q[0] == 0: heapq.heappop(q) if q: ans += max(q) print(ans) 힙을 콘센트로 두고 전자기기를 하나씩 넣어.. 2023. 3. 26.
[백준]230313-19 문제풀이 1107. 리모컨 import sys input = sys.stdin.readline def dfs(i, c): if i == len(str(N)): lst.append(c) return cnt = 0 now = int(str(N)[i]) while cnt 0 and now - cnt in fine: dfs(i + 1, c + str(now - cnt)) if now < 9 and now + cnt in fine: dfs(i + 1, c + str(now + cnt)) cnt += 1 N = int(input()) M = int(input()) broken = list(map(int, input().split())) fine = [] for i in range(10): if i.. 2023. 3. 21.
[백준]230310-12 문제풀이 9019. DSLR from collections import deque import sys input = sys.stdin.readline def zero(n): while len(str(n)) 0: return n - 1 else: return 9999 def L(n): return int(n[1:] + n[0]) def R(n): return int(n[-1] + n[:-1]) T = int(input()) for tc in range(T): a, b = map(int, input().split()) queue = deque([]) queue.ap.. 2023. 3. 13.
[백준]230306-09 문제풀이 11053. 가장 긴 증가하는 부분 수열 import sys input = sys.stdin.readline N = int(input()) lst = list(map(int, input().split())) dp = [1] * N ans = 1 for i in range(1, N): for j in range(i): if lst[j] = dp[i]: dp[i] = dp[j] + 1 if dp[i] > ans: ans = dp[i] print(ans) LIS 문제의 기본. dp가 어려워서 쉬운것부터 도전해보려고 했는데 정말 발상부터가 쉽지 않다...이분탐색을 활용해 nlogn으로 푸는 방법도 있지만 일단 쉬운 문제는 n^2으로 해결이 되는 듯하다 2565. 전깃줄 imp.. 2023. 3. 10.
[백준]230303-05 문제풀이 19237. 어른 상어 import sys input = sys.stdin.readline dy = [0, -1, 1, 0, 0] dx = [0, 0, 0, -1, 1] def move(i, j): n = lst[i][j] for d in range(1, 5): yy = i + dy[D[n][now_D[n]][d]] xx = j + dx[D[n][now_D[n]][d]] if yy not in range(N) or xx not in range(N): continue if not smell[yy][xx]: now_D[n] = D[n][now_D[n]][d] return yy, xx for d in range(1, 5): yy = i + dy[D[n][now_D[n]][d]] xx = j + dx[D[n][.. 2023. 3. 6.
[백준]230302 문제풀이 15686. 치킨 배달 import sys from itertools import combinations input = sys.stdin.readline def cd(y1, x1, y2, x2): return abs(y1 - y2) + abs(x1 - x2) N, M = map(int, input().split()) city = [list(map(int, input().split())) for _ in range(N)] chicken = [] house = [] for i in range(N): for j in range(N): if city[i][j] == 2: chicken.append((i, j)) if city[i][j] == 1: house.append((i, j)) cd_list = [[] f.. 2023. 3. 2.
[백준]230228-0301 문제풀이 7569. 토마토 from collections import deque import sys input = sys.stdin.readline dz = [0, 0, 0, 0, -1, 1] dy = [-1, 1, 0, 0, 0, 0] dx = [0, 0, -1, 1, 0, 0] def bfs(): global ripe day = 0 while queue: qpop = queue.popleft() a, b, c, day = qpop[0], qpop[1], qpop[2], qpop[3] visited[a][b][c] = True for d in range(6): if a + dz[d] in range(H) and b + dy[d] in range(N) and c + dx[d] in range(M): if toma.. 2023. 3. 1.
[백준]230226 문제풀이 17298. 오큰수 import sys N = int(sys.stdin.readline()) lst = list(map(int, sys.stdin.readline().split())) stack = [] ans = [] for i in range(N - 1, -1, -1): if not stack: stack.append(lst[i]) while stack: if stack[-1] temp: ans_list.clear() temp = hacking[i] ans_list.append(i) elif hacking[i] == temp: ans_list.append(i) print(*ans_list) dfs, bfs 모두 가능하다고 하는데 재귀 dfs를 했을 때 계속 에러가 떠서 bfs로 풀었다. 신뢰하는 컴퓨.. 2023. 2. 26.
[백준]230225 문제풀이 11559. Puyo Puyo from collections import deque dy = [-1, 1, 0, 0] dx = [0, 0, -1, 1] def puyo(color): global ispuyo temp = [] cnt = 1 while queue: qpop = queue.popleft() temp.append(qpop) for d in range(4): ni, nj = qpop[0] + dy[d], qpop[1] + dx[d] if ni = 12 or nj = 6: continue if visited[ni][nj]: continue if field[ni][nj] == color: visited[ni][nj] = 1 queue.append((ni, nj.. 2023. 2. 25.
[백준]230223-24 문제풀이 1405. 미친 로봇 dy = [0, 0, 1, -1] dx = [1, -1, 0, 0] n, E, W, S, N = map(int, input().split()) dirs = [E, W, S, N] def dfs(y, x, direction, visited, cnt): global percentage if (y, x) in visited: temp = 1 for i in direction: temp *= dirs[i] / 100 percentage -= temp return if cnt == n: return for d in range(4): dfs(y + dy[d], x + dx[d], direction + [d], visited + [(y, x)], cnt + 1) percentage = 1 dfs.. 2023. 2. 24.
[백준]230220 문제풀이 14719. 빗물 h, w = map(int, input().split()) blocks = list(map(int, input().split())) higher = [0] * w higher[0] = blocks[0] water = 0 for i in range(1, w): # 현재 블록이 이전 블록보다 작을때 상한값을 이전의 상한값까지 올려줌 if blocks[i] = blocks[i-1]: # 현재 블록이 이전 상한값보다 작을 때, 더 큰 블록을 만날때까지 땅을 메꾸고 water 올리기 if blocks[i] blocks[i-cnt]: water += blocks[i.. 2023. 2. 21.
[백준]230217 문제풀이 1043. 거짓말 N, M = map(int, input().split()) truth = input() all_party = [] if truth[0] == '0': nolie_num = 0 for i in range(M): input() print(M) else: truth = list(map(int, truth.split())) nolie_num = truth[0] nolie_list = set(truth[1:]) for i in range(M): party = list(map(int, input().split())) people_num = party[0] people = party[1:] all_party.append(people) while True: nolie = nolie_list.pop().. 2023. 2. 18.
[SWEA]230216 문제풀이 배열 최소 합 T = int(input()) for i in range(T): N = int(input()) lst = [] for j in range(N): lst.append(list(map(int, input().split()))) ans = 1e10 def makesum(n, s, v): global ans temp = v + [n] if len(temp) == N and s < ans: ans = s else: for j in range(N): if j not in temp and s + lst[len(temp)][j] < ans: makesum(j, s + lst[len(temp)][j], temp) for k in range(N): makesum(k, lst[0][k], []) print(f.. 2023. 2. 16.
[백준]230215-16 문제풀이 1946. 신입사원 import heapq import sys T = int(input()) for i in range(T): N = int(sys.stdin.readline()) heap = [] pass_list = [] for j in range(N): a, b = map(int, input().split()) heapq.heappush(heap, (a,b)) pass_list.append(heapq.heappop(heap)) while heap: a = heapq.heappop(heap) if a[1] < pass_list[-1][1]: pass_list.append(a) print(len(pass_list)) 대충 로직 맞는데 시간초과 떠서 pypy로 제출해버렸다. 힙에는 주로 배열 형태를 집어.. 2023. 2. 16.
[백준]230214 문제풀이 2638. 치즈 from collections import deque N, M = map(int, input().split()) lst = [] dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] time = 0 for i in range(N): a = list(map(int, input().split())) lst.append(a) while True: cheeze = deque([]) # 공기부분 -1로 변환 lst[0][0] = -1 queue = deque([(0, 0)]) visited = [[False] * M for _ in range(N)] while queue: a = queue.pop() visited[a[0]][a[1]] = True temp = [] for k in .. 2023. 2. 14.
[백준]230213 문제풀이 11000. 강의실 배정 import sys import heapq N = int(sys.stdin.readline()) heap = [] clslst = [] cnt = 0 for i in range(N): a, b = map(int,sys.stdin.readline().split()) heapq.heappush(clslst, (a, b)) for i in range(N): x = heapq.heappop(clslst) while heap and heap[0] cnt: cnt = len(heap) print(cnt) 오늘의 리벤지. 이전에 그리디 문제로 만난적이 있어서 로직 자체는 어렵지 않게 생각했지만 힙에서 쓸 인덱스를 어떻게 할지가 관건이었던 문제. 시작시간과 종료시간을 힙으로 같이 넣은 다음에 .. 2023. 2. 13.
[백준]230210-12 문제풀이 1463. 1로 만들기 N = int(input()) dic = {1: 0} def mini(n): if n in dic.keys(): return dic[n] else: if not n % 3 and not n % 2: dic[n] = min(mini(n//3) + 1, mini(n//2) + 1) elif not n % 3: dic[n] = min(mini(n//3) + 1, mini(n - 1) + 1) elif not n % 2: dic[n] = min(mini(n//2) + 1, mini(n - 1) + 1) else: dic[n] = mini(n - 1) + 1 return dic[n] print(mini(N)) 드디어 먹어본 그 유명한 DP. 잘못된 재귀로 recursion error의 폭격.. 2023. 2. 12.
[SWEA]230209 문제풀이 3143. 가장 빠른 문자열 타이핑 T = int(input()) for i in range(T): a, b = map(str, input().split()) # skip array 생성 skiparr = {} for j in range(len(b)): skiparr[b[j]] = len(b) - 1 - j # 반복문 초기 설정 breaker = True x, y = 0, len(b) inputcnt = 0 same = 0 # 연산 while breaker: temp = a[x:y] # 완전히 같을 때 이동 if temp == b: same += 1 inputcnt += 1 x += len(b) y += len(b) if y > len(a): breaker = False # 완전히 같지 않을 때 else.. 2023. 2. 9.
[백준]230209 문제풀이 10866. 덱 import sys n = int(input()) deque = [] for i in range(n): com = sys.stdin.readline().strip() if com[:4] == 'push': if com[5:9] == 'back': deque.append(int(com[10:])) else: deque.insert(0, int(com[11:])) elif com[:3] == 'pop': if com[4:8] == 'back': if deque: print(deque.pop()) else: print(-1) else: if deque: print(deque.pop(0)) else: print(-1) elif com == 'size': print(len(deque)) elif .. 2023. 2. 9.
[SWEA]230208 문제풀이 어디에 단어가 들어갈 수 있을까 T = int(input()) for i in range(T): N, K = map(int, input().split()) lst = [] for j in range(N): lst.append(list(map(int, input().split()))) ans = [] for j in range(N): rcnt = ccnt = 0 for k in range(N): if lst[j][k]: rcnt += 1 else: ans.append(rcnt) rcnt = 0 if lst[k][j]: ccnt += 1 else: ans.append(ccnt) ccnt = 0 ans.append(rcnt) ans.append(ccnt) print(f'#{i+1} {ans.count(K)}'.. 2023. 2. 8.
[백준]230208 문제풀이 14698. 전생했더니 슬라임 연구자였던 건에 대하여(Hard) import sys import heapq T = int(sys.stdin.readline()) for i in range(T): N = int(sys.stdin.readline()) lst = list(map(int, sys.stdin.readline().split())) lst.sort() mult = 1 if len(lst) > 1: while True: a = heapq.heappop(lst) if lst: a *= heapq.heappop(lst) heapq.heappush(lst, a) mult *= a else: break print(mult % 1000000007) 힙을 좀 더 응용한 형태의 문제. 코드를 최대한 간결하게 하는.. 2023. 2. 8.
[알고리즘개념]힙 뉴진스의 히트곡 제목에도 들어갈 정도로 최근 트렌드로 급부상하고 있는 힙(Heap)은 자료구조의 일종으로 완전 이진 트리를 통해 우선순위 큐를 구현한다. 먼저 큐(Queue)는 자료가 들어온(push) 순서대로 나가는(pop) 자료구조이다. 이를 코드를 통해 보면 다음과 같다. queue = [] for i in range(5): queue.append(i) print(queue) # [0, 1, 2, 3, 4] for i in range(5): print(queue.pop(0)) ''' 0 1 2 3 4 ''' 0부터 4까지 순서대로 입력되고 0부터 4까지 순서대로 나가는 선입선출(FIFO;First-in First-out) 구조이다. 우선순위 큐(Priority Queue)는 큐와 비슷하지만, 들어온.. 2023. 2. 8.
[SWEA]230207 문제풀이 풍선팡2 T = int(input()) di = [0, 0, -1, 1] dj = [-1, 1, 0, 0] for i in range(T): N, M = map(int, input().split()) lst = [] ans = [] for j in range(N): lst.append(list(map(int, input().split()))) for j in range(N): for k in range(M): bls = lst[j][k] for l in range(2): if j+di[l+2] in range(N): bls += lst[j+di[l+2]][k+dj[l+2]] if k+dj[l] in range(M): bls += lst[j+di[l]][k+dj[l]] ans.append(bls) prin.. 2023. 2. 7.
728x90