├── Baekjoon ├── eugene │ ├── 15_week │ │ ├── 부등호.py │ │ ├── 빗물.py │ │ └── 최솟값.py │ ├── 16_week │ │ ├── 구간 곱 구하기.py │ │ └── 스타트와 링크.py │ ├── 17_week │ │ ├── 최소 스패닝 트리.py │ │ └── 퇴사.py │ ├── 18_week │ │ ├── 극장 좌석.py │ │ └── 행복 유치원.py │ ├── 19_week │ │ └── 지구 온난화.py │ ├── 20_week │ │ ├── 2×n 타일링 2.py │ │ ├── LCS.py │ │ └── 소형기관차.py │ ├── 22_week │ │ ├── 마법사 상어와 토네이도.py │ │ └── 빙고.py │ ├── 23_week │ │ ├── 바이러스.py │ │ └── 연구소.py │ ├── 25_week │ │ └── 단어 수학.py │ ├── 39_week │ │ └── 토마토.py │ ├── 40_week │ │ └── 진우의 민트초코우유.py │ ├── 41_week │ │ └── 그림.py │ ├── 42_week │ │ └── 네트워크 연결.py │ └── README.md ├── jiwoo │ ├── 15_week │ │ ├── 부등호.py │ │ ├── 빗물.py │ │ └── 최솟값.py │ ├── 16_week │ │ ├── 구간곱구하기.py │ │ └── 스타트와링크.py │ ├── 17_week │ │ ├── 최소스패닝트리.py │ │ └── 퇴사.py │ ├── 18_week │ │ ├── 극장좌석.py │ │ └── 행복유치원.py │ ├── 19_week │ │ └── 지구온난화.py │ ├── 20_week │ │ ├── 2Xn타일링2.py │ │ ├── LCS.py │ │ └── 소형기관차.py │ ├── 21_week │ │ ├── 철벽보안알고리즘.py │ │ └── 치킨배달.py │ ├── 22_week │ │ ├── 마법사상어와토네이도.py │ │ └── 빙고.py │ ├── 23_week │ │ ├── 바이러스.py │ │ └── 연구소.py │ ├── 25_week │ │ └── 단어수학.py │ ├── 39_week │ │ └── 토마토.py │ ├── 40_week │ │ └── 진우의민트초코우유.py │ └── README.md └── suyeon │ ├── 15_week │ ├── 10868_최솟값.py │ ├── 14719_빗물.py │ └── 2529_부등호.py │ ├── 16_week │ ├── 구간 곱 구하기.py │ └── 스타트와 링크.py │ ├── 17_week │ ├── 최소 스패닝 트리.py │ └── 퇴사.py │ ├── 18_week │ ├── 극장 좌석.py │ └── 행복 유치원.py │ ├── 19_week │ └── 지구 온난화.py │ ├── 20_week │ ├── 2xn 타일링 2.py │ ├── LCS.py │ └── 소형기관차.py │ ├── 21_week │ ├── 철벽 보안 알고리즘.py │ └── 치킨 배달.py │ ├── 22_week │ ├── 마법사 상어와 토네이도.py │ └── 빙고.py │ ├── 23_week │ ├── 바이러스.py │ └── 연구소.py │ ├── 25_week │ └── 단어 수학.py │ ├── 39_week │ └── 토마토.py │ ├── 40_week │ └── 진우의 민트초코우유.py │ ├── 41_week │ └── 그림.py │ ├── 42_week │ └── 네트워크 연결.py │ ├── 43_week │ └── 로봇 청소기.py │ ├── 44_week │ └── 벽 부수고 이동하기.py │ ├── 45_week │ └── 일루미네이션.py │ ├── 46_week │ └── 탈출.py │ ├── 47_week │ └── 평범한 배낭.py │ ├── 48_week │ └── 상자 배달.py │ ├── 49_week │ ├── 드래곤 커브.py │ └── 퇴사 2.py │ ├── 51_week │ └── 숨바꼭질 2.py │ ├── 52_week │ └── N번째 큰 수.py │ ├── 53_week │ └── 뱀.py │ ├── 54_week │ └── 트리의 독립집합.py │ └── README.md ├── Programmers ├── .DS_Store ├── 42_week │ └── 점프와 순간 이동.py ├── eugene │ ├── .DS_Store │ ├── 2018_kakao_blind │ │ ├── 뉴스 클러스터링.py │ │ ├── 캐시.py │ │ └── 프랜즈4블록.py │ ├── 2019_kakao_blind │ │ ├── 실패율.py │ │ ├── 오픈채팅방.py │ │ └── 후보키.py │ ├── 2020_kakao_blind │ │ ├── 괄호 변환.py │ │ ├── 문자열 압축.py │ │ └── 자물쇠와 열쇠.py │ ├── 2021_kakao_blind │ │ ├── 메뉴 리뉴얼.py │ │ ├── 순위 검색.py │ │ └── 신규 아이디 추천.py │ ├── 24_week │ │ └── 숫자 문자열과 영단어.py │ ├── 25_week │ │ └── 거리두기 확인하기.py │ ├── 26_week │ │ └── 수식 최대화.py │ ├── 27_week │ │ └── 튜플.py │ ├── 28_week │ │ └── 파일명 정렬.py │ ├── 29_week │ │ └── n진수 게임.py │ ├── 30_week │ │ └── 주차 요금 계산.py │ ├── 31_week │ │ └── k진수에서 소수 개수 구하기.py │ ├── 32_week │ │ └── 멀쩡한 사각형.py │ ├── 33_week │ │ └── 불량 사용자.py │ ├── 34_week │ │ └── 방금 그곡.py │ ├── 35_week │ │ └── 모음사전.py │ ├── 36_week │ │ └── n^2 배열 자르기.py │ ├── 37_week │ │ └── 피로도.py │ ├── 38_week │ │ └── 교점에 별 만들기.py │ ├── 39_week │ │ └── 삼각 달팽이.py │ ├── 40_week │ │ └── 빛의 경로 사이클.py │ ├── README.md │ ├── binary_search │ │ ├── 입국심사.py │ │ └── 징검다리.py │ ├── brute_force │ │ ├── 소수 찾기.py │ │ └── 카펫.py │ ├── dfs_bfs │ │ ├── 네트워크.py │ │ ├── 단어 변환.py │ │ └── 타겟 넘버.py │ ├── dynamic_programming │ │ ├── N으로 표현.py │ │ ├── 등굣길.py │ │ └── 정수 삼각형.py │ ├── graph │ │ ├── 가장 먼 노드.py │ │ ├── 방의 개수.py │ │ └── 순위.py │ ├── greedy │ │ ├── 조이스틱.py │ │ └── 큰 수 만들기.py │ ├── hash │ │ ├── 베스트앨범.py │ │ ├── 위장.py │ │ └── 전화번호 목록.py │ ├── heap │ │ ├── 더 맵게.py │ │ ├── 디스크 컨트롤러.py │ │ └── 이중우선순위큐.py │ ├── sort │ │ ├── H-Index.py │ │ ├── K번째수.py │ │ └── 가장 큰 수.py │ └── stack_queue │ │ ├── 주식가격.py │ │ └── 프린터.py ├── jiwoo │ ├── 2018_kakao_blind │ │ ├── 뉴스클러스터링.py │ │ ├── 캐시.py │ │ └── 프렌즈4블록.py │ ├── 2019_kakao_blind │ │ ├── 실패율.py │ │ ├── 오픈채팅방.py │ │ └── 후보키.py │ ├── 2020_kakao_blind │ │ ├── 괄호변환.py │ │ ├── 문자열압축.py │ │ └── 자물쇠와열쇠.py │ ├── 2021_kakao_blind │ │ ├── 메뉴리뉴얼.py │ │ ├── 순위검색.py │ │ └── 신규아이디추천.py │ ├── 24_week │ │ └── 숫자 문자열과 영단어.py │ ├── 25_week │ │ └── 거리두기 확인하기.py │ ├── 26_week │ │ └── 수식 최대화.py │ ├── 27_week │ │ └── 튜플.py │ ├── 28_week │ │ └── 파일명정렬.py │ ├── 29_week │ │ └── n진수게임.py │ ├── 30_week │ │ └── 주차요금계산.py │ ├── 31_week │ │ └── k진수에서 소수 개수 구하기.py │ ├── 32_week │ │ └── 멀쩡한사각형.py │ ├── 33_week │ │ └── 불량사용자.py │ ├── 34_week │ │ └── 방금그곡.py │ ├── 35_week │ │ └── 모음사전.py │ ├── 36_week │ │ └── n^2배열자르기.py │ ├── 37_week │ │ └── 피로도.py │ ├── 39_week │ │ └── 삼각달팽이.py │ ├── README.md │ ├── binary_search │ │ ├── 입국심사.py │ │ └── 징검다리.py │ ├── brute_force │ │ ├── 소수찾기.py │ │ └── 카펫.py │ ├── dfs_bfs │ │ ├── 네트워크.py │ │ ├── 단어변환.py │ │ └── 타켓넘버.py │ ├── dynamic_programming │ │ ├── N으로표현.py │ │ ├── 등굣길.py │ │ └── 정수삼각형.py │ ├── graph │ │ ├── 가장먼노드.py │ │ ├── 방의개수.py │ │ └── 순위.py │ ├── hash │ │ ├── 베스트앨범.py │ │ ├── 위장.py │ │ └── 전화번호목록.py │ ├── heap │ │ ├── 더맵게.py │ │ ├── 디스크컨트롤러.py │ │ └── 이중우선순위큐.py │ ├── sort │ │ ├── HIndex.py │ │ ├── K번째수.py │ │ └── 가장큰수.py │ └── stack_queue │ │ ├── 주식가격.py │ │ └── 프린터.py └── suyeon │ ├── 2018_kakao_blind │ ├── 뉴스 클러스터링.py │ ├── 캐시.py │ └── 프렌즈4블록.py │ ├── 2019_kakao_blind │ ├── 실패율.py │ ├── 오픈채팅방.py │ └── 후보키.py │ ├── 2020_kakao_blind │ ├── 괄호 변환.py │ ├── 문자열 압축.py │ └── 자물쇠와 열쇠.py │ ├── 2021_kakao_blind │ ├── 메뉴 리뉴얼.py │ ├── 순위 검색.py │ └── 신규 아이디 추천.py │ ├── 24_week │ └── 숫자 문자열과 영단어.py │ ├── 25_week │ └── 거리두기 확인하기.py │ ├── 26_week │ └── 수식 최대화.py │ ├── 27_week │ └── 튜플.py │ ├── 28_week │ └── 파일명 정렬.py │ ├── 29_week │ └── n진수 게임.py │ ├── 30_week │ └── 주차 요금 계산.py │ ├── 31_week │ └── k 진수에서 소수 개수 구하기.py │ ├── 32_week │ └── 멀쩡한 사각형.py │ ├── 33_week │ └── 불량 사용자.py │ ├── 34_week │ └── 방금그곡.py │ ├── 35_week │ └── 모음 사전.py │ ├── 36_week │ └── n^2 배열 자르기.py │ ├── 37_week │ └── 피로도.py │ ├── 38_week │ └── 교점에 별 만들기.py │ ├── 39_week │ └── 삼각 달팽이.py │ ├── 40_week │ └── 빛의 경로 사이클.py │ ├── 42_week │ └── 점프와 순간 이동.py │ ├── 43_week │ └── 스킬트리.py │ ├── 44_week │ └── 양과 늑대.py │ ├── 45_week │ └── 카드 짝 맞추기.py │ ├── 46_week │ └── 2개 이하로 다른 비트.py │ ├── 47_week │ └── 110 옮기기.py │ ├── 48_week │ └── 배달.py │ ├── 50_week │ └── 기능 개발.py │ ├── 51_week │ └── 두 큐 합 같게 만들기.py │ ├── 52_week │ └── 전력망을 둘로 나누기.py │ ├── 53_week │ └── JadenCase 문자열 만들기.py │ ├── 54_week │ └── 124 나라의 숫자.py │ ├── 55_week │ └── 양궁대회.py │ ├── README.md │ ├── binary_search │ ├── 입국심사.py │ └── 징검다리.py │ ├── brute_force │ ├── 소수 찾기.py │ └── 카펫.py │ ├── dfs_bfs │ ├── 네트워크.py │ ├── 단어 변환.py │ └── 타겟 넘버.py │ ├── dynamic_programming │ ├── N으로 표현.py │ ├── 등굣길.py │ └── 정수 삼각형.py │ ├── graph │ ├── 가장 먼 노드.py │ ├── 방의 개수.py │ └── 순위.py │ ├── greedy │ ├── 조이스틱.py │ └── 큰 수 만들기.py │ ├── hash │ ├── 베스트앨범.py │ ├── 위장.py │ └── 전화번호 목록.py │ ├── heap │ ├── 더 맵게.py │ ├── 디스크 컨트롤러.py │ └── 이중우선순위큐.py │ ├── sort │ ├── H-Index.py │ ├── K번째수.py │ └── 가장 큰 수.py │ └── stack_queue │ ├── 주식가격.py │ └── 프린터.py └── README.md /Baekjoon/eugene/15_week/부등호.py: -------------------------------------------------------------------------------- 1 | num=int(input()) 2 | oper=input().split() 3 | visited=[False]*(10) 4 | max_num, min_num="","" 5 | 6 | def check_num(i,j,oper): 7 | return ij 8 | 9 | def solution(cnt,ansList): 10 | global max_num, min_num 11 | 12 | if cnt == num+1: 13 | if not min_num : min_num=ansList 14 | else: max_num=ansList 15 | return 16 | 17 | for i in range(10): 18 | if not visited[i]: 19 | if cnt == 0 or check_num(ansList[-1], str(i), oper[cnt-1]): 20 | visited[i]=True 21 | solution(cnt+1, ansList+str(i)) 22 | visited[i]=False 23 | 24 | solution(0,"") 25 | print(max_num) 26 | print(min_num) 27 | -------------------------------------------------------------------------------- /Baekjoon/eugene/15_week/빗물.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | H,W = map(int, input().split()) 3 | block=list(map(int, input().split())) 4 | answer=0 5 | 6 | for i in range(W): 7 | left=max(block[:i+1]) 8 | right=max(block[i:]) 9 | 10 | height=min(left, right) 11 | answer+= height-block[i] 12 | print(answer) 13 | -------------------------------------------------------------------------------- /Baekjoon/eugene/15_week/최솟값.py: -------------------------------------------------------------------------------- 1 | from math import ceil, log 2 | import sys 3 | 4 | def init(start, end, node): 5 | if start==end: 6 | tree[node]=tree[size+start] 7 | return tree[node] 8 | 9 | mid=(start+end)//2 10 | tree[node]=min(init(start,mid,node*2), init(mid+1, end, node*2+1)) 11 | return tree[node] 12 | 13 | def query(start, end, node, q_start, q_end): 14 | if start > q_end or end < q_start: 15 | return 1000000000 16 | elif q_start<=start and end <= q_end: 17 | return tree[node] 18 | mid=(start+end)//2 19 | return min(query(start, mid, node*2, q_start, q_end),query(mid+1,end, node*2+1, q_start, q_end)) 20 | 21 | 22 | if __name__ =="__main__": 23 | N,M=[int(x) for x in sys.stdin.readline().split()] 24 | size =2**(ceil(log(N,2))+1) 25 | tree_size=2*size 26 | tree=[0]*tree_size 27 | 28 | for i in range(N): 29 | tree[size+i]=int(sys.stdin.readline()) 30 | 31 | init(0,N-1,1) 32 | 33 | for _ in range(M): 34 | q_start, q_end= map(int, sys.stdin.readline().split()) 35 | print(query(0,N-1,1,q_start-1, q_end-1)) 36 | -------------------------------------------------------------------------------- /Baekjoon/eugene/16_week/구간 곱 구하기.py: -------------------------------------------------------------------------------- 1 | from math import ceil,log 2 | import sys 3 | 4 | MOD = 1000000007 5 | 6 | def init(start, end, node): 7 | if start==end: 8 | tree[node]=arr[start] 9 | return tree[node] % MOD 10 | mid= (start+end)//2 11 | tree[node]=init(start, mid, node*2) * init(mid+1, end, node*2+1) % MOD 12 | return tree[node] 13 | 14 | def update(start, end, node, idx, num): 15 | if idx < start or end < idx: return 16 | if start == end: 17 | tree[node]=num 18 | return 19 | 20 | mid=(start+end)//2 21 | update(start, mid, node*2, idx, num) 22 | update(mid+1, end, node*2+1, idx, num) 23 | tree[node]=(tree[node*2]*tree[node*2+1]) % MOD 24 | return tree[node] 25 | 26 | def query(start, end, node, left, right): 27 | if right < start or end < left: return 1 28 | if left <=start and end <= right: return tree[node] % MOD 29 | 30 | mid=(start+end)//2 31 | return query(start,mid, node*2, left, right)*query(mid+1, end, node*2+1, left, right) % MOD 32 | 33 | if __name__ =="__main__": 34 | N,M,K=map(int, input().split()) 35 | size=2**(ceil(log(N,2))+1) 36 | tree=[1]*size 37 | arr=[] 38 | for i in range(N): 39 | arr.append(int(sys.stdin.readline())) 40 | 41 | init(0,N-1,1) 42 | 43 | for _ in range(M+K): 44 | a,b,c=map(int, sys.stdin.readline().split()) 45 | if a==1: 46 | update(0, N-1, 1, b-1, c) 47 | elif a==2: 48 | print(query(0, N-1, 1, b-1, c-1)) 49 | -------------------------------------------------------------------------------- /Baekjoon/eugene/16_week/스타트와 링크.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | import sys 3 | 4 | def solution(potential, n): 5 | minimum = 10000 6 | StartLink = set(range(n)) 7 | for startTeam in combinations(range(n),n//2): 8 | sum1,sum2 = 0,0 9 | startTeam=list(startTeam) 10 | linkTeam = list(StartLink-set(startTeam)) 11 | 12 | for a in range(n//2): 13 | for b in range(a+1,n//2): 14 | Sx, Sy = startTeam[a], startTeam[b] 15 | sum1 += potential[Sx][Sy]+potential[Sy][Sx] 16 | 17 | Lx, Ly = linkTeam[a], linkTeam[b] 18 | sum2 += potential[Lx][Ly]+potential[Ly][Lx] 19 | ans=abs(sum1-sum2) 20 | 21 | if not ans : return 0 22 | if ans < minimum: minimum = ans 23 | 24 | return minimum 25 | 26 | if __name__ == "__main__": 27 | potential = [] 28 | N = int(input()) 29 | 30 | for _ in range(N): 31 | potential.append(list(map(int, sys.stdin.readline().split()))) 32 | print(solution(potential, N)) 33 | -------------------------------------------------------------------------------- /Baekjoon/eugene/17_week/최소 스패닝 트리.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def find_parent(parent, x): 4 | if parent[x] != x: 5 | parent[x] = find_parent(parent, parent[x]) 6 | return parent[x] 7 | 8 | def union_parent(parent, a, b): 9 | a = find_parent(parent, a) 10 | b = find_parent(parent, b) 11 | if a < b : parent[b] = a 12 | else : parent[a] = b 13 | 14 | if __name__ =="__main__" : 15 | v, e = map(int, input().split()) 16 | 17 | parent = [0] * (v+1) 18 | edges=[] 19 | result=0 20 | 21 | for i in range(1, v+1): 22 | parent[i]=i 23 | 24 | for i in range(e): 25 | a, b, c = map(int, sys.stdin.readline().split()) 26 | edges.append((c, a, b)) 27 | 28 | edges.sort() 29 | 30 | for edge in edges: 31 | cost, a, b = edge 32 | if find_parent(parent, a) != find_parent(parent, b): 33 | union_parent(parent, a, b) 34 | result+=cost 35 | print(result) 36 | -------------------------------------------------------------------------------- /Baekjoon/eugene/17_week/퇴사.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | n = int(input()) 3 | dp = [0]*(n+1) 4 | time, pay = [],[] 5 | 6 | for i in range(n): 7 | t, p = map(int, input().split()) 8 | time.append(t) 9 | pay.append(p) 10 | 11 | for i in range(n-1, -1, -1): 12 | if time[i]+i > n : 13 | dp[i] = dp[i+1] 14 | else : 15 | dp[i] = max(dp[i+1], pay[i]+dp[i+time[i]]) 16 | print(dp[0]) 17 | -------------------------------------------------------------------------------- /Baekjoon/eugene/18_week/극장 좌석.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | if __name__ =="__main__": 4 | n = int(input()) 5 | m = int(input()) 6 | 7 | x, y = 1,2 8 | fibo = [1] * (n+1) 9 | for i in range(2,n+1): 10 | fibo[i] = fibo[i-1]+fibo[i-2] 11 | idx, answer = 1,1 12 | for _ in range(m): 13 | x = int(sys.stdin.readline()) 14 | answer *= fibo[x-idx] 15 | idx = x+1 16 | 17 | if idx < n : 18 | answer *= fibo[n-idx+1] 19 | print(answer) 20 | -------------------------------------------------------------------------------- /Baekjoon/eugene/18_week/행복 유치원.py: -------------------------------------------------------------------------------- 1 | if __name__ =="__main__": 2 | n,k = map(int, input().split()) 3 | people = list(map(int, input().split())) 4 | 5 | diff=[0]*(n-1) 6 | for i in range(n-1): 7 | diff[i] = people[i+1]-people[i] 8 | diff.sort() 9 | print(sum(diff[:n-k])) 10 | -------------------------------------------------------------------------------- /Baekjoon/eugene/19_week/지구 온난화.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | R, C = map(int, input().split()) 3 | 4 | map_info=['.' * (C+2)] 5 | for _ in range(R): 6 | map_info.append('.' + input() + '.') 7 | map_info.append('.' * (C+2)) 8 | 9 | answer = map_info[:] 10 | x_start, x_end = R + 10, 0 11 | y_start, y_end = C + 10, 0 12 | for x in range(1, R+1): 13 | for y in range(1, C+1): 14 | if map_info[x][y] == '.': 15 | continue 16 | 17 | cnt=0 18 | if map_info[x-1][y] == '.': cnt += 1 19 | if map_info[x][y-1] == '.': cnt += 1 20 | if map_info[x][y+1] == '.': cnt += 1 21 | if map_info[x+1][y] == '.': cnt += 1 22 | 23 | if cnt >= 3: 24 | answer[x]=str(answer[x][ :y] + answer[0][0] + answer[x][y+1: ]) 25 | else : 26 | x_start, x_end = min(x, x_start), max(x, x_end) 27 | y_start, y_end = min(y, y_start), max(y,y_end) 28 | 29 | for x_idx in range(x_start, x_end+1): 30 | print(answer[x_idx][y_start:y_end+1]) 31 | -------------------------------------------------------------------------------- /Baekjoon/eugene/20_week/2×n 타일링 2.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | if n == 1: 3 | return 1 4 | 5 | ans = [1] * n 6 | ans[1] =3 7 | 8 | for i in range(2,n): 9 | ans[i]=(ans[i-1] + ans[i-2]*2)%10007 10 | return ans[-1] 11 | 12 | if __name__ =="__main__": 13 | n=int(input()) 14 | print(solution(n)) 15 | -------------------------------------------------------------------------------- /Baekjoon/eugene/20_week/LCS.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | first = input() 3 | second = input() 4 | 5 | len_first = len(first) 6 | len_second = len(second) 7 | 8 | LCS = [[0]*(len_first+1) for _ in range(len_second+1)] 9 | for i in range(1, len_second+1) : #1~3 10 | for j in range(1, len_first+1) : #1~2 11 | if first[j-1] == second[i-1] : 12 | LCS[i][j] = LCS[i-1][j-1]+1 13 | else : 14 | LCS[i][j] = max(LCS[i][j-1], LCS[i-1][j]) 15 | 16 | print(LCS[-1][-1]) 17 | -------------------------------------------------------------------------------- /Baekjoon/eugene/20_week/소형기관차.py: -------------------------------------------------------------------------------- 1 | if __name__ =="__main__": 2 | n = int(input()) 3 | people = list(map(int, input().split())) 4 | max_n = int(input()) 5 | 6 | S=[0] 7 | sum_val = 0 8 | 9 | for p in people: 10 | sum_val += p 11 | S.append(sum_val) 12 | 13 | dp = [[0] *(n+1) for _ in range(4)] 14 | 15 | for x in range(1,4): 16 | for y in range(x*max_n, n+1): 17 | if x == 1: 18 | dp[x][y] = max(dp[x][y-1], S[y]-S[y-max_n]) 19 | else : 20 | dp[x][y] = max(dp[x][y-1], dp[x-1][y-max_n] + S[y]-S[y-max_n]) 21 | print(dp[-1][-1]) 22 | -------------------------------------------------------------------------------- /Baekjoon/eugene/22_week/빙고.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | chulsu = [input().split() for _ in range(5)] 4 | visited = [ [False] * 5 for _ in range(5)] 5 | 6 | vertical = [False] * 5 7 | horizontal = [False] * 5 8 | diagonal = [False] * 2 9 | 10 | 11 | def visit_bingo(number): 12 | for i in range(5): 13 | for j in range(5): 14 | if chulsu[i][j] == number: 15 | visited[i][j] = True 16 | return 17 | 18 | 19 | def check_bingo(matrix): 20 | for x in range(5): 21 | # Step1. Horizontal, x 22 | if all(matrix[x]): 23 | horizontal[x] = True 24 | 25 | #Step2. Vertical, y 26 | for y in range(5): 27 | if not matrix[y][x]: 28 | break 29 | if y == 4: 30 | vertical[x] = True 31 | 32 | 33 | # Step3. diagonal 34 | if x == y : 35 | for i in range(5): 36 | if not matrix[i][i]: 37 | break 38 | if i == 4: 39 | diagonal[0] = True 40 | if x + y == 4: 41 | for i in range(5): 42 | if not matrix[i][4-i]: 43 | break 44 | if i == 4: 45 | diagonal[1] = True 46 | 47 | 48 | def cnt_bingo(): 49 | cnt = 0 50 | for i in range(5): 51 | if vertical[i]: 52 | cnt += 1 53 | if horizontal[i]: 54 | cnt += 1 55 | 56 | for i in range(2): 57 | if diagonal[i]: 58 | cnt += 1 59 | return cnt 60 | 61 | 62 | 63 | def bingo(): 64 | for i in range(5): 65 | mc = input().split() 66 | for j in range(5): 67 | visit_bingo(mc[j]) 68 | check_bingo(visited) 69 | 70 | if cnt_bingo() >= 3 : 71 | return i*5+j+1 72 | 73 | print(bingo()) 74 | -------------------------------------------------------------------------------- /Baekjoon/eugene/23_week/바이러스.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | 5 | def bfs(graph, start): 6 | queue = deque([start]) 7 | visited[start] = True 8 | cnt_virus = 0 9 | while queue: 10 | v = queue.popleft() 11 | for idx in graph[v]: 12 | if not visited[idx]: 13 | queue.append(idx) 14 | visited[idx] = True 15 | cnt_virus += 1 16 | return cnt_virus 17 | 18 | 19 | node_n, edge_n = int(input()), int(input()) 20 | 21 | visited = [False] * (node_n+1) 22 | graph = [[] for _ in range(node_n + 1)] 23 | 24 | for _ in range(edge_n): 25 | start, end = map(int, sys.stdin.readline().split()) 26 | graph[start].append(end) 27 | graph[end].append(start) 28 | 29 | print(bfs(graph, 1)) 30 | -------------------------------------------------------------------------------- /Baekjoon/eugene/23_week/연구소.py: -------------------------------------------------------------------------------- 1 | import copy 2 | from itertools import combinations 3 | from collections import deque 4 | 5 | EMPTY, WALL, VIRUS = '0', '1', '2' 6 | 7 | moving = [(-1, 0), (1, 0), (0, -1), (0, 1)] 8 | empty_list, virus_list = [], [] 9 | lab_map = [] 10 | 11 | 12 | def bfs(new_map): 13 | visited = [[False] * col for _ in range(row)] 14 | queue = deque(virus_list) 15 | infect_cnt = 0 16 | while queue: 17 | vy, vx = queue.popleft() 18 | for i in range(4): 19 | mx = vx + moving[i][1] 20 | my = vy + moving[i][0] 21 | if my < 0 or my >= row or mx < 0 or mx >= col: 22 | continue 23 | if new_map[my][mx] == EMPTY and not visited[my][mx]: 24 | queue.append([my, mx]) 25 | new_map[my][mx] = VIRUS 26 | visited[my][mx] = True 27 | infect_cnt += 1 28 | 29 | return len(empty_list) - infect_cnt - 3 30 | 31 | 32 | row, col = map(int, input().split()) 33 | for i in range(row): 34 | temp = input().split() 35 | lab_map.append(temp) 36 | 37 | for j in range(col): 38 | if temp[j] == EMPTY: 39 | empty_list.append([i, j]) 40 | elif temp[j] == VIRUS: 41 | virus_list.append([i, j]) 42 | 43 | max_safe_area = 0 44 | for empty1, empty2, empty3 in list(combinations(empty_list, 3)): 45 | y1, x1 = empty1 46 | y2, x2 = empty2 47 | y3, x3 = empty3 48 | 49 | new_map = copy.deepcopy(lab_map) 50 | new_map[y1][x1] = WALL 51 | new_map[y2][x2] = WALL 52 | new_map[y3][x3] = WALL 53 | 54 | safe_area = bfs(new_map) 55 | max_safe_area = max(safe_area, max_safe_area) 56 | 57 | print(max_safe_area) 58 | -------------------------------------------------------------------------------- /Baekjoon/eugene/25_week/단어 수학.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | 3 | num_list = {i: [] for i in range(10)} 4 | alphabet_num = {} 5 | 6 | for _ in range(n): 7 | word = list(input()) 8 | for idx, value in enumerate(word): 9 | alphabet_num[value] = 0 10 | num_list[len(word) - idx] += value 11 | 12 | for key in range(9, -1, -1): 13 | for num in num_list[key]: 14 | alphabet_num[num] += 10**(key-1) 15 | 16 | sorted_alphabet = sorted(alphabet_num.items(), key = lambda item: item[1], reverse=True) 17 | 18 | answer = 0 19 | for idx, (_, operand) in enumerate(sorted_alphabet): 20 | answer += operand * (9-idx) 21 | print(answer) 22 | -------------------------------------------------------------------------------- /Baekjoon/eugene/39_week/토마토.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | m, n, h = map(int, input().split()) 5 | farm = [[list(map(int,sys.stdin.readline().split())) for _ in range(n)] for _ in range(h)] 6 | 7 | day = 0 8 | dx = [0, 0, 0, 0, -1, 1] 9 | dy = [0, 0, -1, 1, 0, 0] 10 | dz = [-1, 1, 0, 0, 0, 0] 11 | 12 | queue = deque() 13 | for i in range(h): 14 | for j in range(n): 15 | for k in range(m): 16 | if farm[i][j][k] == 1: 17 | queue.append((i, j, k)) 18 | 19 | while queue: 20 | day += 1 21 | for _ in range(len(queue)): 22 | x, y, z = queue.popleft() 23 | for i in range(6): 24 | nx = x + dx[i] 25 | ny = y + dy[i] 26 | nz = z + dz[i] 27 | 28 | if 0 <= nx < h and 0 <= ny < n and 0 <= nz < m and farm[nx][ny][nz] == 0: 29 | farm[nx][ny][nz] = 1 30 | queue.append((nx, ny, nz)) 31 | else: 32 | continue 33 | 34 | for i in range(h): 35 | for j in range(n): 36 | for k in range(m): 37 | if not farm[i][j][k]: 38 | print(-1) 39 | exit(0) 40 | print(day-1) 41 | -------------------------------------------------------------------------------- /Baekjoon/eugene/40_week/진우의 민트초코우유.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def dfs(x, y, hp): 4 | for mint_x, mint_y in mint: 5 | if map_info[mint_x][mint_y] == 2: 6 | temp = abs(mint_x - x) + abs(mint_y, y) 7 | if temp <= hp: 8 | map_info[mint_x][mint_y] = 0 9 | dfs(mint_x, mint_y, hp - temp + h) 10 | map_info[mint_x][mint_y] = 2 11 | 12 | if abs(x - home_x) + abs(y, home_y) <= hp: 13 | result_milk = max(result_milk, ) 14 | 15 | 16 | n, m, h = map(int, input().split()) 17 | map_info = [list(map(int, sys.stdin.readline().split())) for _ in range(n)] 18 | 19 | mint = [] 20 | result_milk = 0 21 | 22 | for i in range(n): 23 | for j in range(n): 24 | if map_info[i][j] == 1: 25 | home_x, home_y = i, j 26 | elif map_info[i][j] == 2: 27 | mint.append((i, j)) 28 | 29 | dfs(home_x, home_y, m) 30 | -------------------------------------------------------------------------------- /Baekjoon/eugene/41_week/그림.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | def bfs(i, j): 5 | queue = deque() 6 | queue.append((i, j)) 7 | 8 | dx = [0, 1, 0, -1] 9 | dy = [1, 0, -1, 0] 10 | 11 | area = 1 12 | while queue: 13 | x, y = queue.popleft() 14 | paper[x][y] = 0 15 | for d in range(4): 16 | nx = x + dx[d] 17 | ny = y + dy[d] 18 | # 유효한 좌표 확인 및 그림 여부 확인 19 | if 0<=nxb 13 | 14 | def solve(count, num_str): 15 | global max_num, min_num 16 | if count == num+1: 17 | if not min_num: 18 | min_num = num_str 19 | else: 20 | max_num = num_str 21 | return 22 | for i in range(10): 23 | if not visited[i]: 24 | if count == 0 or check_oper(num_str[-1], str(i), operator[count-1]): 25 | visited[i] = True 26 | solve(count+1, num_str+str(i)) 27 | visited[i] = False 28 | 29 | solve(0, "") 30 | print(max_num) 31 | print(min_num) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/15_week/빗물.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | H, W = map(int, input().split()) 3 | blocks = list(map(int, input().split())) 4 | 5 | rain_area = 0 6 | 7 | for i in range(W): 8 | left_high = max(blocks[:i+1]) 9 | right_high = max(blocks[i:]) 10 | 11 | height = min(left_high, right_high) 12 | rain_area += height - blocks[i] 13 | print(rain_area) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/15_week/최솟값.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | max_ = 1000000000 5 | 6 | def query(left, right, node, query_left, query_right): 7 | if query_right < left or right < query_left: 8 | return max_ 9 | elif query_left <= left and right <= query_right: 10 | return tree[node] 11 | else: 12 | mid = (left+right) // 2 13 | left_result = query(left, mid, node*2, query_left, query_right) 14 | right_result = query(mid+1, right, node*2+1, query_left, query_right) 15 | return min(left_result, right_result) 16 | 17 | N, M = map(int, input().split()) 18 | size = 1 19 | while size < N: 20 | size *= 2 21 | 22 | #init tree 23 | tree = [max_] * (size * 2) 24 | 25 | for i in range(N): 26 | tree[size+i] = int(input()) 27 | for i in range(size-1, 0, -1): 28 | tree[i] = min(tree[i*2], tree[i*2+1]) 29 | 30 | for _ in range(M): 31 | a, b = map(int, input().split()) 32 | print(query(1, size, 1, a, b)) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/16_week/구간곱구하기.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from math import * 3 | 4 | input = sys.stdin.readline 5 | NUM = 1000000007 6 | 7 | def init(node, start, end): 8 | if start == end: 9 | tree[node] = arr[start] 10 | return tree[node] % NUM 11 | mid= (start+end) // 2 12 | tree[node] = init(node*2, start, mid) * init(node*2+1, mid+1, end) % NUM 13 | return tree[node] 14 | 15 | def update(node, start, end, index, value): 16 | if index < start or end < index: return 17 | if start == end: 18 | tree[node] = value 19 | return 20 | mid = (start+end) // 2 21 | update(node*2, start, mid, index, value) 22 | update(node*2+1, mid+1, end, index, value) 23 | tree[node] = (tree[node*2] * tree[node*2+1]) % NUM 24 | return tree[node] 25 | 26 | def query(node, start, end, left, right): 27 | if right < start or end < left: 28 | return 1 29 | if left <= start and end <= right: 30 | return tree[node] % NUM 31 | 32 | mid = (start+end) // 2 33 | return query(node*2, start, mid, left, right) * query(node*2+1, mid+1, end, left, right) % NUM 34 | 35 | N, M, K = map(int, input().split()) 36 | tree_size = 2**(ceil(log2(N)) + 1) 37 | 38 | tree = [1] * tree_size 39 | arr=[] 40 | for i in range(N): 41 | arr.append(int(input())) 42 | 43 | init(1, 0, N-1) 44 | 45 | for _ in range(M+K): 46 | a, b, c = map(int, input().split()) 47 | if a == 1: 48 | update(1, 0, N-1, b-1, c) 49 | else: 50 | print(query(1, 0, N-1, b-1, c-1)) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/16_week/스타트와링크.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | 3 | N = int(input()) 4 | soccer_map = [0 for i in range(N+1)] 5 | for i in range(N): 6 | soccer_map[i] = list(map(int, input().split())) 7 | 8 | teams = list(combinations(range(1, N+1), N//2)) 9 | 10 | dif_score = [] 11 | 12 | for i in range(len(teams)//2): 13 | start_score = 0 14 | link_score = 0 15 | start_team = teams[i] 16 | link_team = teams[len(teams)-i-1] 17 | 18 | start_team_ = list(combinations(start_team, 2)) 19 | link_team_ = list(combinations(link_team, 2)) 20 | for a, b in start_team_: 21 | start_score += (soccer_map[a-1][b-1] + soccer_map[b-1][a-1]) 22 | for a, b in link_team_: 23 | link_score += (soccer_map[a-1][b-1] + soccer_map[b-1][a-1]) 24 | dif_score.append(abs(start_score-link_score)) 25 | 26 | print(min(dif_score)) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/17_week/최소스패닝트리.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | 3 | def union(a, b): 4 | a = find(a) 5 | b = find(b) 6 | 7 | if b < a: 8 | parent[a] = b 9 | else: 10 | parent[b] = a 11 | 12 | def find(a): 13 | if a == parent[a]: 14 | return a 15 | parent[a] = find(parent[a]) # 경로 압축 16 | return parent[a] 17 | 18 | input = stdin.readline 19 | V, S = map(int, input().split()) 20 | 21 | edge = [] 22 | for _ in range(S): 23 | a, b, w = map(int, input().split()) 24 | edge.append((w, a, b)) 25 | 26 | edge.sort(key=lambda x: x[0]) 27 | 28 | parent = list(range(V + 1)) 29 | 30 | sum = 0 31 | for w, s, e in edge: 32 | if find(s) != find(e): 33 | union(s, e) 34 | sum += w 35 | 36 | print(sum) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/17_week/퇴사.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | 3 | meeting = [list(map(int, input().split())) for i in range(N)] 4 | dp = [0] * (N+1) 5 | 6 | for i in range(N-1, -1, -1): 7 | if i + meeting[i][0] > N: 8 | dp[i] = dp[i+1] 9 | else: 10 | dp[i] = max(meeting[i][1] + dp[i+meeting[i][0]], dp[i+1]) 11 | 12 | print(dp[0]) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/18_week/극장좌석.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | M = int(input()) 3 | 4 | vip = [] 5 | for i in range(M): 6 | vip_n = int(input()) 7 | vip.append(vip_n) 8 | 9 | sit = [1, 1, 2] 10 | for i in range(3, N+1): 11 | sit.append(sit[i-2] + sit[i-1]) 12 | 13 | answer = 1 14 | if M >= 1: 15 | start_num = 0 16 | for i in range(M): 17 | answer *= sit[vip[i]-1-start_num] 18 | start_num = vip[i] 19 | answer *= sit[N-start_num] 20 | else: 21 | answer = sit[N] 22 | print(answer) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/18_week/행복유치원.py: -------------------------------------------------------------------------------- 1 | N, K = map(int, input().split()) 2 | people = list(map(int, input().split())) 3 | 4 | difference = [] 5 | for i in range(N-1): 6 | difference.append(people[i+1]-people[i]) 7 | difference.sort() 8 | 9 | answer = 0 10 | if K == N: 11 | print(answer) 12 | else: 13 | for i in range(N-K): 14 | answer += difference[i] 15 | print(answer) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/19_week/지구온난화.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | move = [(-1, 0), (0, 1), (1, 0), (0, -1)] 5 | 6 | def get_dot(): 7 | sea_point = [] 8 | for i in range(R): 9 | for j in range(C): 10 | if sea_map[i][j] == '.': 11 | continue 12 | 13 | count = 0 14 | for mx, my in move: 15 | nx = i + mx 16 | ny = j + my 17 | 18 | if nx < 0 or nx >= R or ny < 0 or ny >= C: 19 | count += 1 20 | continue 21 | 22 | elif sea_map[nx][ny] == '.': 23 | count += 1 24 | 25 | if count >= 3: 26 | sea_point.append((i, j)) 27 | else: 28 | get_min(i, j) 29 | return sea_point 30 | 31 | def get_min(i, j): 32 | global start_row, end_row, start_col, end_col 33 | if start_row > i: 34 | start_row = i 35 | if end_row < i: 36 | end_row = i 37 | if start_col > j: 38 | start_col = j 39 | if end_col < j: 40 | end_col = j 41 | 42 | R, C = map(int, input().split()) 43 | sea_map = [list(input().strip()) for _ in range(R)] 44 | 45 | start_row, end_row = R-1, 0 46 | start_col, end_col = C-1, 0 47 | for x, y in get_dot(): 48 | sea_map[x][y] = '.' 49 | 50 | for l in sea_map[start_row:end_row+1]: 51 | print(''.join(l[start_col:end_col+1])) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/20_week/2Xn타일링2.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | 3 | DP = [0, 1, 3] 4 | 5 | for i in range(3, N+1): 6 | DP.append(((DP[i-2] * 2) + DP[i-1]) % 10007) 7 | 8 | print(DP[N]) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/20_week/LCS.py: -------------------------------------------------------------------------------- 1 | S1 = input() 2 | S2 = input() 3 | 4 | count_s1 = len(S1) + 1 5 | count_s2 = len(S2) + 1 6 | 7 | LCS = [[0] * (count_s1) for _ in range(count_s2)] 8 | 9 | for i in range(1, count_s2): 10 | for j in range(1, count_s1): 11 | if S1[j-1] == S2[i-1]: 12 | LCS[i][j] = LCS[i-1][j-1] + 1 13 | else: 14 | LCS[i][j] = max(LCS[i-1][j], LCS[i][j-1]) 15 | 16 | print(LCS[-1][-1]) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/20_week/소형기관차.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N = int(input()) 6 | people_train = [0] + list(map(int, input().split())) 7 | max_train = int(input()) 8 | 9 | for i in range(1, len(people_train)): 10 | people_train[i] += people_train[i-1] 11 | 12 | dp = [[0] * (N+1) for _ in range(4)] 13 | for i in range(1, 4): 14 | for j in range(i * max_train, N+1): 15 | if i == 1: 16 | dp[i][j] = max(dp[i][j-1], people_train[j] - people_train[j-max_train]) 17 | else: 18 | dp[i][j] = max(dp[i][j-1], dp[i-1][j-max_train] + people_train[j] - people_train[j-max_train]) 19 | print(dp[3][N]) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/21_week/철벽보안알고리즘.py: -------------------------------------------------------------------------------- 1 | def check_index(a, n): 2 | for i in range(n): 3 | index_.append(a[1].index(a[0][i])) 4 | 5 | def print_key(a, b): 6 | for i in b: 7 | print(a[2][i], end=' ') 8 | 9 | T = int(input()) 10 | 11 | for i in range(T): 12 | n = int(input()) 13 | 14 | input_ = [] 15 | for j in range(3): 16 | input_.append(input().split()) 17 | 18 | index_ = [] 19 | check_index(input_, n) 20 | 21 | print_key(input_, index_) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/21_week/치킨배달.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | 3 | N, M = map(int, input().split()) 4 | 5 | city = [] 6 | for i in range(N): 7 | city.append(list(map(int, input().split()))) 8 | 9 | homes = [] 10 | chickens = [] 11 | for i in range(N): 12 | for j in range(N): 13 | if city[i][j] == 1: 14 | homes.append((i,j)) 15 | elif city[i][j] == 2: 16 | chickens.append((i,j)) 17 | 18 | pick_chicken = list(combinations(chickens, M)) 19 | distance = [0] * len(pick_chicken) 20 | 21 | for home in homes: 22 | for j in range(len(pick_chicken)): 23 | d = 1e9 24 | for pick in pick_chicken[j]: 25 | temp = abs(home[0] - pick[0]) + abs(home[1] - pick[1]) 26 | d = min(d, temp) 27 | distance[j] += d 28 | print(min(distance)) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/22_week/마법사상어와토네이도.py: -------------------------------------------------------------------------------- 1 | # 참고 코드라 코드 리뷰 후 한 번 더 해 볼 예정 2 | 3 | import sys; 4 | 5 | input = sys.stdin.readline 6 | 7 | def sand_move(position, direction_ind, sand): 8 | rate = [2, 10, 7, 1, 5, 10, 7, 1, 2] 9 | sand_matrix = [ 10 | [(-2, 0), (-1, -1), (-1, 0), (-1, 1), (0, -2), (1, -1), (1, 0), (1, 1), (2, 0)], 11 | [(0, -2), (1, -1), (0, -1), (-1, -1), (2, 0), (1, 1), (0, 1), (-1, 1), (0, 2)] 12 | ] 13 | ret = 0 14 | y = sand[position[0]][position[1]] 15 | sand[position[0]][position[1]] = 0 16 | alpha = y 17 | for index, pos_tmp in enumerate(sand_matrix[direction_ind % 2]): 18 | r = position[0] + pos_tmp[0] * (-1) ** (direction_ind // 2) 19 | c = position[1] + pos_tmp[1] * (-1) ** (direction_ind // 2) 20 | temp = (y * rate[index]) // 100 21 | if temp: 22 | alpha -= temp 23 | if 0 <= r < N and 0 <= c < N: 24 | sand[r][c] += temp 25 | else: 26 | ret += temp 27 | r = position[0] + direction[direction_ind][0] 28 | c = position[1] + direction[direction_ind][1] 29 | if 0 <= r < N and 0 <= c < N: 30 | sand[r][c] += alpha 31 | else: 32 | ret += alpha 33 | return ret 34 | 35 | 36 | N = int(input()) 37 | sand = [list(map(int, input().split())) for _ in range(N)] 38 | check = [[0 for _ in range(N)] for _ in range(N)] 39 | out_sand = 0 40 | 41 | s = [N//2, N//2] 42 | direction = [(0, -1), (1, 0), (0, 1), (-1, 0)] # l d r u 43 | ind = 0 44 | check[s[0]][s[1]] = 1 45 | while s != [0, 0]: 46 | s[0] += direction[ind][0] 47 | s[1] += direction[ind][1] 48 | check[s[0]][s[1]] = 1 49 | 50 | out_sand += sand_move(s, ind, sand) 51 | 52 | ind = (ind+1) % 4 53 | if check[s[0] + direction[ind][0]][s[1] + direction[ind][1]]: 54 | ind = (ind-1) % 4 55 | print(out_sand) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/22_week/빙고.py: -------------------------------------------------------------------------------- 1 | bingo = [list(map(int, input().split())) for _ in range(5)] 2 | 3 | numbers = [] 4 | for _ in range(5): 5 | numbers += list(map(int, input().split())) 6 | 7 | counting = [0] * 12 8 | 9 | bingo_line = 0 10 | flag = False 11 | for n in range(0, 26): 12 | if flag == True: 13 | break 14 | for i in range(5): 15 | if flag == True: 16 | break 17 | for j in range(5): 18 | if flag == True: 19 | break 20 | if numbers[n] == bingo[i][j]: 21 | bingo[i][j] = 0 22 | counting[i] += 1 23 | counting[j+5] += 1 24 | if i == j: 25 | counting[10] += 1 26 | if i+j == 4: 27 | counting[11] += 1 28 | for count in range(12): 29 | if counting[count] == 5: 30 | counting[count] = 0 31 | bingo_line += 1 32 | if bingo_line == 3: 33 | flag = True 34 | break 35 | print(n) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/23_week/바이러스.py: -------------------------------------------------------------------------------- 1 | def dfs(com): 2 | global count 3 | visited[com] = 1 4 | for i in connection[com]: 5 | if visited[i] == 0: 6 | dfs(i) 7 | count += 1 8 | 9 | com_num = int(input()) 10 | net_com = int(input()) 11 | 12 | count = 0 13 | visited = [0] * (com_num + 1) 14 | 15 | connection = [[] * com_num for _ in range(com_num + 1)] 16 | for _ in range(net_com): 17 | a, b = map(int, input().split()) 18 | connection[a].append(b) 19 | connection[b].append(a) 20 | 21 | dfs(1) 22 | print(count) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/23_week/연구소.py: -------------------------------------------------------------------------------- 1 | import sys 2 | input = sys.stdin.readline 3 | 4 | N, M = map(int, input().split()) 5 | virus_map = [list(map(int, input().split())) for _ in range(N)] 6 | temp = [[0] * M for _ in range(N)] 7 | 8 | dx = [-1, 0, 1, 0] 9 | dy = [0, 1, 0, -1] 10 | 11 | result = 0 12 | def virus(x, y): 13 | for i in range(4): 14 | nx = x + dx[i] 15 | ny = y + dy[i] 16 | 17 | if 0 <= nx and nx < N and 0 <= ny and ny < M: 18 | if temp[nx][ny] == 0: 19 | temp[nx][ny] = 2 20 | virus(nx, ny) 21 | 22 | def safe(): 23 | count = 0 24 | for i in range(N): 25 | for j in range(M): 26 | if temp[i][j] == 0: 27 | count += 1 28 | return count 29 | 30 | def dfs(count): 31 | global result 32 | if count == 3: 33 | for i in range(N): 34 | for j in range(M): 35 | temp[i][j] = virus_map[i][j] 36 | for i in range(N): 37 | for j in range(M): 38 | if temp[i][j] == 2: 39 | virus(i, j) 40 | result = max(result, safe()) 41 | return 42 | for i in range(N): 43 | for j in range(M): 44 | if virus_map[i][j] == 0: 45 | virus_map[i][j] = 1 46 | count += 1 47 | dfs(count) 48 | virus_map[i][j] = 0 49 | count -= 1 50 | 51 | dfs(0) 52 | print(result) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/25_week/단어수학.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | N = int(input()) 5 | 6 | word_list = [] 7 | alpha_count_list = {} 8 | sum_list = [] 9 | 10 | for i in range(N): 11 | word_list.append(input().rstrip()) 12 | 13 | for i in range(N): 14 | for j in range(len(word_list[i])): 15 | if word_list[i][j] in alpha_count_list: 16 | alpha_count_list[word_list[i][j]] += 10 ** (len(word_list[i]) - j - 1) 17 | else: 18 | alpha_count_list[word_list[i][j]] = 10 ** (len(word_list[i]) - j - 1) 19 | 20 | for num in alpha_count_list.values(): 21 | sum_list.append(num) 22 | 23 | sum_list.sort(reverse = True) 24 | 25 | sum = 0 26 | cal_num = 9 27 | for i in sum_list: 28 | sum += cal_num * i 29 | cal_num -= 1 30 | 31 | print(sum) 32 | -------------------------------------------------------------------------------- /Baekjoon/jiwoo/39_week/토마토.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | M, N, H = map(int, input().split()) 4 | box = [[list(map(int, input().split())) for i in range(N)] for j in range(H)] 5 | 6 | dx = [1, -1, 0, 0, 0, 0] 7 | dy = [0, 0, -1, 1, 0, 0] 8 | dz = [0, 0, 0, 0, -1, 1] 9 | 10 | def bfs(): 11 | while queue: 12 | z, x, y = queue.popleft() 13 | for i in range(6): 14 | a = x + dx[i] 15 | b = y + dy[i] 16 | c = z + dz[i] 17 | 18 | if 0 <= a < N and 0 <= b < M and 0 <= c < H: 19 | if box[c][a][b] == 0: 20 | queue.append([c, a, b]) 21 | box[c][a][b] = box[z][x][y] + 1 22 | queue = deque() 23 | for i in range(H): 24 | for j in range(N): 25 | for k in range(M): 26 | if box[i][j][k] == 1: 27 | queue.append([i, j, k]) 28 | 29 | bfs() 30 | z = 1 31 | result = -1 32 | 33 | for i in box: 34 | for j in i: 35 | for k in j: 36 | if k == 0: 37 | z = 0 38 | result = max(result, k) 39 | 40 | if z == 0: 41 | print(-1) 42 | elif result == 1: 43 | print(0) 44 | else: 45 | print(result-1) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/40_week/진우의민트초코우유.py: -------------------------------------------------------------------------------- 1 | import sys 2 | readline = lambda: sys.stdin.readline().strip() 3 | 4 | def dfs(x, y, HP, mint): 5 | global result 6 | 7 | for nx, ny in mint_milks: 8 | if village[nx][ny] == 2: 9 | distance = abs(nx - x) + abs(ny - y) 10 | if distance <= HP: 11 | village[nx][ny] = 0 12 | dfs(nx, ny, HP + H - distance, mint + 1) 13 | village[nx][ny] = 2 14 | if abs(x - a) + abs(y - b) <= HP: 15 | result = max(result, mint) 16 | 17 | N, M, H = map(int, readline().split()) 18 | village = [list(map(int, readline().split())) for _ in range(N)] 19 | 20 | mint_milks = [] 21 | a, b = 0, 0 22 | 23 | for i in range(N): 24 | for j in range(N): 25 | if village[i][j] == 1: 26 | a, b = i, j 27 | if village[i][j] == 2: 28 | mint_milks.append((i, j)) 29 | 30 | result = 0 31 | dfs(a, b, M, 0) 32 | 33 | print(result) -------------------------------------------------------------------------------- /Baekjoon/jiwoo/README.md: -------------------------------------------------------------------------------- 1 | # 2021-Algorithm-Study-Python 2 | 3 | > 유형별 문제 풀이 4 | 5 | | 주차 | 문제명_1 | 문제명_2 | 6 | | --- | ------ | ----- | 7 | | 18_week | [극장좌석](https://jjuyaa.tistory.com/210) | [행복유치원](https://jjuyaa.tistory.com/211) | -------------------------------------------------------------------------------- /Baekjoon/suyeon/15_week/10868_최솟값.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | INF = int(1e9) 5 | 6 | 7 | def query(left, right, node, query_left, query_right): 8 | # 연관 없음 -> 결과에 영향이 없는 값 return 9 | if query_right < left or right < query_left: 10 | return INF 11 | # 판단 가능 -> 현재 노드 값 return 12 | elif query_left <= left and right <= query_right: 13 | return tree[node] 14 | # 판단 불가 -> 자식에게 위임, 자식에서 올라온 값의 min을 return 15 | else: 16 | mid = (left + right) // 2 17 | left_result = query(left, mid, node * 2, query_left, query_right) 18 | right_result = query(mid + 1, right, node * 2 + 1, query_left, query_right) 19 | return min(left_result, right_result) 20 | 21 | 22 | n, m = map(int, input().split()) 23 | s = 1 24 | while s < n: 25 | s *= 2 26 | 27 | # init tree 28 | tree = [INF] * (2 * s) 29 | for i in range(n): 30 | tree[s + i] = int(input()) 31 | for i in range(s - 1, 0, -1): 32 | tree[i] = min(tree[i * 2], tree[i * 2 + 1]) 33 | 34 | for _ in range(m): 35 | a, b = map(int, input().split()) 36 | print(query(1, s, 1, a, b)) 37 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/15_week/14719_빗물.py: -------------------------------------------------------------------------------- 1 | def move(idx, w, blocks): 2 | max_idx, max_height = idx, 0 3 | for i in range(idx + 1, w): 4 | if blocks[i] >= blocks[idx]: 5 | return i 6 | 7 | if blocks[i] >= max_height: 8 | max_height = blocks[i] 9 | max_idx = i 10 | return max_idx 11 | 12 | 13 | def rain(idx, max_idx, blocks): 14 | total_rain = 0 15 | max_height = min(blocks[idx], blocks[max_idx]) 16 | for i in range(idx + 1, max_idx): 17 | total_rain += max_height - blocks[i] 18 | return total_rain 19 | 20 | 21 | def main(): 22 | h, w = map(int, input().split()) 23 | blocks = list(map(int, input().split())) 24 | 25 | idx, answer = 0, 0 26 | while idx < w - 1: 27 | max_idx = move(idx, w, blocks) 28 | answer += rain(idx, max_idx, blocks) 29 | idx = max_idx 30 | print(answer) 31 | 32 | 33 | if __name__ == '__main__': 34 | main() 35 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/15_week/2529_부등호.py: -------------------------------------------------------------------------------- 1 | # backtracking 2 | MIN_NUM = 9999999999 3 | MAX_NUM = 0 4 | 5 | 6 | def backtracking(first, idx, answer): 7 | if idx == len(inequalities): 8 | global MIN_NUM, MAX_NUM 9 | answer = int(answer + str(first)) 10 | if answer < MIN_NUM: 11 | MIN_NUM = answer 12 | if answer > MAX_NUM: 13 | MAX_NUM = answer 14 | return 15 | 16 | numbers[first] = True 17 | for second in range(10): 18 | if not numbers[second]: 19 | if inequalities[idx] == '<' and first < second: 20 | backtracking(second, idx + 1, answer + str(first)) 21 | if inequalities[idx] == '>' and first > second: 22 | backtracking(second, idx + 1, answer + str(first)) 23 | numbers[first] = False 24 | 25 | 26 | k = int(input()) 27 | inequalities = list(map(str, input().split())) 28 | numbers = [False] * 10 # 0 ~ 9 29 | 30 | for i in range(10): 31 | backtracking(i, 0, '') 32 | 33 | print(str(MAX_NUM).zfill(k + 1)) 34 | print(str(MIN_NUM).zfill(k + 1)) 35 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/16_week/구간 곱 구하기.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | DEFAULT_NUM = 1 5 | DIVIDE_NUM = 1_000_000_007 6 | 7 | 8 | # Bottom - Up 방식 9 | def update(target, value): 10 | # target에 value 반영 11 | node = s + target - 1 12 | tree[node] = value 13 | # Root에 도달할 때까지 반복문 돌기 (좌측, 우측의 곱을 노드에 저장) 14 | node //= 2 15 | while node > 0: 16 | tree[node] = (tree[node * 2] * tree[node * 2 + 1]) % DIVIDE_NUM 17 | node //= 2 18 | 19 | 20 | # Top - Down 방식 21 | def query(left, right, node, query_left, query_right): 22 | # 연관 없음 -> 결과에 영향이 없는 값 return 23 | if query_right < left or right < query_left: 24 | return DEFAULT_NUM 25 | # 판단 가능 -> 현재 노드 값 return 26 | elif query_left <= left and right <= query_right: 27 | return tree[node] 28 | # 판단 불가 -> 자식에게 위임, 자식에서 올라온 값의 곱을 return 29 | mid = (left + right) // 2 30 | left_result = query(left, mid, node * 2, query_left, query_right) 31 | right_result = query(mid + 1, right, node * 2 + 1, query_left, query_right) 32 | return (left_result * right_result) % DIVIDE_NUM 33 | 34 | 35 | n, m, k = map(int, input().split()) # 개수, 변경, 구간 곱 36 | s = 1 37 | while s < n: 38 | s *= 2 39 | 40 | # init tree 41 | tree = [DEFAULT_NUM] * (2 * s) 42 | for i in range(n): 43 | tree[s + i] = int(input()) 44 | for i in range(s - 1, 0, -1): 45 | tree[i] = (tree[i * 2] * tree[i * 2 + 1]) % DIVIDE_NUM 46 | 47 | for _ in range(m + k): 48 | a, b, c = map(int, input().split()) 49 | if a == 1: 50 | update(b, c) 51 | else: 52 | print(query(1, s, 1, b, c)) 53 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/16_week/스타트와 링크.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | combination_list = [] 5 | 6 | 7 | def get_min(n): 8 | answer = int(1e9) 9 | 10 | team = set(numbers) 11 | for start_team in combination_list: 12 | link_team = list(team - set(start_team)) 13 | 14 | start, link = 0, 0 15 | for i in range(n): 16 | for j in range(i + 1, n): 17 | x1, y1 = start_team[i], start_team[j] 18 | start += matrix[x1][y1] + matrix[y1][x1] 19 | 20 | x2, y2 = link_team[i], link_team[j] 21 | link += matrix[x2][y2] + matrix[y2][x2] 22 | 23 | diff = abs(start - link) 24 | 25 | if diff < answer: 26 | answer = diff 27 | if not answer: 28 | break 29 | return answer 30 | 31 | 32 | def combination(n, k, idx, current): 33 | global combination_list 34 | # 종료 조건 35 | if not k: 36 | combination_list.append(current) 37 | return 38 | if n == k: 39 | temp = current.copy() 40 | temp.extend(numbers[idx:]) 41 | combination_list.append(temp) 42 | return 43 | 44 | # 값을 뽑는 경우 45 | temp = current.copy() 46 | temp.append(numbers[idx]) 47 | combination(n - 1, k - 1, idx + 1, temp) 48 | # 값을 뽑지 않는 경우 49 | combination(n - 1, k, idx + 1, current) 50 | 51 | 52 | N = int(input()) 53 | 54 | matrix = [] 55 | for _ in range(N): 56 | matrix.append(list(map(int, input().split()))) 57 | 58 | numbers = [i for i in range(N)] 59 | combination(N, N // 2, 0, []) 60 | print(get_min(N // 2)) 61 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/17_week/최소 스패닝 트리.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | 6 | def find(x): 7 | if parent[x] != x: 8 | parent[x] = find(parent[x]) 9 | return parent[x] 10 | 11 | 12 | def union(x, y): 13 | x = find(x) 14 | y = find(y) 15 | if x < y: 16 | parent[y] = x 17 | else: 18 | parent[x] = y 19 | 20 | 21 | v, e = map(int, input().split()) 22 | parent = [0] * (v + 1) 23 | 24 | edges = [] 25 | result = 0 26 | 27 | for i in range(1, v + 1): 28 | parent[i] = i 29 | 30 | for _ in range(e): 31 | a, b, cost = map(int, input().split()) 32 | edges.append((cost, a, b)) 33 | 34 | edges.sort() # 비용순으로 정렬 35 | 36 | for cost, a, b in edges: 37 | if find(a) != find(b): 38 | union(a, b) 39 | result += cost 40 | 41 | print(result) -------------------------------------------------------------------------------- /Baekjoon/suyeon/17_week/퇴사.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | n = int(input()) 6 | schedule = [tuple(map(int, input().split())) for _ in range(n)] 7 | 8 | answer = 0 9 | dp = [0] * (n + 1) 10 | for i in range(n - 1, -1, -1): 11 | term, price = schedule[i] 12 | if i + term <= n: 13 | answer = max(price + dp[i + term], answer) 14 | dp[i] = answer 15 | 16 | print(answer) -------------------------------------------------------------------------------- /Baekjoon/suyeon/18_week/극장 좌석.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N, M = int(input()), int(input()) 6 | dp = [1] * (N + 1) 7 | for i in range(2, N + 1): 8 | dp[i] = dp[i - 1] + dp[i - 2] 9 | 10 | prev_num, answer = 0, 1 11 | for _ in range(M): 12 | current_num = int(input()) 13 | answer *= dp[current_num - prev_num - 1] 14 | prev_num = current_num 15 | answer *= dp[N - prev_num] 16 | 17 | print(answer) -------------------------------------------------------------------------------- /Baekjoon/suyeon/18_week/행복 유치원.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N, K = map(int, input().split()) 6 | 7 | children = list(map(int, input().split())) 8 | print(sum(sorted([children[i] - children[i - 1] for i in range(1, N)])[:N - K])) -------------------------------------------------------------------------------- /Baekjoon/suyeon/19_week/지구 온난화.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | move = [(-1, 0), (1, 0), (0, -1), (0, 1)] # (dx, dy) 상, 하, 좌, 우 5 | 6 | 7 | def get_sea_point(): 8 | sea_point = [] 9 | for r in range(R): 10 | for c in range(C): 11 | if matrix[r][c] == '.': 12 | continue 13 | 14 | count = 0 15 | for dx, dy in move: 16 | nx = r + dx 17 | ny = c + dy 18 | 19 | if nx < 0 or ny < 0 or nx >= R or ny >= C: 20 | count += 1 21 | elif matrix[nx][ny] == '.': 22 | count += 1 23 | 24 | if count >= 3: 25 | sea_point.append((r, c)) 26 | else: 27 | get_minimum(r, c) 28 | 29 | return sea_point 30 | 31 | 32 | def get_minimum(r, c): 33 | global start_row, end_row, start_col, end_col 34 | if start_row > r: 35 | start_row = r 36 | if end_row < r: 37 | end_row = r 38 | if start_col > c: 39 | start_col = c 40 | if end_col < c: 41 | end_col = c 42 | 43 | 44 | if __name__ == '__main__': 45 | R, C = map(int, input().split()) 46 | matrix = [list(input().strip()) for _ in range(R)] 47 | 48 | start_row, end_row, start_col, end_col = R - 1, 0, C - 1, 0 49 | for x, y in get_sea_point(): 50 | matrix[x][y] = '.' 51 | 52 | for m in matrix[start_row:end_row + 1]: 53 | print(''.join(m[start_col:end_col + 1])) 54 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/20_week/2xn 타일링 2.py: -------------------------------------------------------------------------------- 1 | def get_number_of_cases(): 2 | dp = [0] * (n + 2) # n이 1일 때 인덱스 에러 방지 3 | dp[1], dp[2] = 1, 3 4 | for i in range(3, n + 1): 5 | dp[i] = (dp[i - 1] + dp[i - 2] * 2) % 10_007 6 | return dp[n] 7 | 8 | 9 | if __name__ == '__main__': 10 | n = int(input()) 11 | print(get_number_of_cases()) -------------------------------------------------------------------------------- /Baekjoon/suyeon/20_week/LCS.py: -------------------------------------------------------------------------------- 1 | def get_lcs(): 2 | lcs = [[0] * (len_first + 1) for _ in range(len_second + 1)] 3 | for i in range(1, len_second + 1): 4 | for j in range(1, len_first + 1): 5 | if first[j - 1] == second[i - 1]: 6 | lcs[i][j] = lcs[i - 1][j - 1] + 1 7 | else: 8 | lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]) 9 | return lcs[-1][-1] 10 | 11 | 12 | if __name__ == '__main__': 13 | first, second = input(), input() 14 | len_first, len_second = len(first), len(second) 15 | print(get_lcs()) -------------------------------------------------------------------------------- /Baekjoon/suyeon/20_week/소형기관차.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | 6 | def get_max_passenger(): 7 | dp = [[0] * (n + 1) for _ in range(4)] 8 | for i in range(1, 4): 9 | for j in range(i * max_transit, n + 1): 10 | if i == 1: 11 | dp[i][j] = max(dp[i][j - 1], trains[j] - trains[j - max_transit]) 12 | else: 13 | dp[i][j] = max(dp[i][j - 1], dp[i - 1][j - max_transit] + trains[j] - trains[j - max_transit]) 14 | return dp[3][n] 15 | 16 | 17 | if __name__ == '__main__': 18 | n = int(input()) 19 | trains = [0] + list(map(int, input().split())) 20 | max_transit = int(input()) 21 | 22 | for idx in range(1, len(trains)): 23 | trains[idx] += trains[idx - 1] 24 | print(get_max_passenger()) 25 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/21_week/철벽 보안 알고리즘.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | 6 | def decrypt(): 7 | public_key_dict = dict.fromkeys(public_key_2, 0) 8 | for idx, key in enumerate(public_key_1): 9 | public_key_dict[key] = idx 10 | 11 | decrypted_cryptogram = [''] * N 12 | for idx, value in enumerate(public_key_dict.values()): 13 | decrypted_cryptogram[value] = cryptogram[idx] 14 | return ' '.join(decrypted_cryptogram) 15 | 16 | 17 | if __name__ == "__main__": 18 | T = int(input()) 19 | for _ in range(T): 20 | N = int(input()) 21 | public_key_1, public_key_2, cryptogram = input().split(), input().split(), input().split() 22 | print(decrypt()) 23 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/21_week/치킨 배달.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from itertools import combinations 3 | 4 | input = sys.stdin.readline 5 | 6 | 7 | if __name__ == "__main__": 8 | N, M = map(int, input().split()) 9 | matrix = [list(map(int, input().split())) for _ in range(N)] 10 | 11 | home_set, chicken_set = set(), set() 12 | for i in range(N): 13 | for j in range(N): 14 | if matrix[i][j] == 1: 15 | home_set.add((i, j)) 16 | elif matrix[i][j] == 2: 17 | chicken_set.add((i, j)) 18 | 19 | answer = int(1e9) 20 | for chicken_list in combinations(chicken_set, M): 21 | min_sum = 0 22 | for home_i, home_j in home_set: 23 | min_sum += min([abs(home_i - chicken_i) + abs(home_j - chicken_j) for chicken_i, chicken_j in chicken_list]) 24 | if answer <= min_sum: 25 | break 26 | if min_sum < answer: 27 | answer = min_sum 28 | print(answer) 29 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/22_week/마법사 상어와 토네이도.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | 6 | def tornado(move_count, direction): 7 | global answer, sx, sy 8 | 9 | for _ in range(move_count): 10 | dx, dy = move[direction] 11 | sx, sy = sx + dx, sy + dy 12 | 13 | if sx < 0 or sy < 0: 14 | break 15 | 16 | spreads = 0 17 | for dx, dy, rate in rates[direction]: 18 | nx, ny = sx + dx, sy + dy 19 | if not rate: 20 | sand = sand_matrix[sx][sy] - spreads 21 | else: 22 | sand = int(sand_matrix[sx][sy] * rate) 23 | 24 | if 0 <= nx < N and 0 <= ny < N: 25 | sand_matrix[nx][ny] += sand 26 | else: 27 | answer += sand 28 | spreads += sand 29 | 30 | 31 | if __name__ == "__main__": 32 | N = int(input()) 33 | sand_matrix = [list(map(int, input().split())) for _ in range(N)] 34 | 35 | answer = 0 36 | sx, sy = N // 2, N // 2 # 시작 지점 초기화 37 | move = {"left": (0, -1), "right": (0, 1), "up": (-1, 0), "down": (1, 0)} 38 | 39 | left = [ 40 | (-2, 0, 0.02), (2, 0, 0.02), (-1, -1, 0.1), (-1, 0, 0.07), (-1, 1, 0.01), 41 | (1, -1, 0.1), (1, 0, 0.07), (1, 1, 0.01), (0, -2, 0.05), (0, -1, 0) 42 | ] 43 | right = [(dx, -dy, rate) for dx, dy, rate in left] 44 | down = [(-dy, dx, rate) for dx, dy, rate in left] 45 | up = [(-dx, dy, rate) for dx, dy, rate in down] 46 | rates = {'left': left, 'right': right, 'down': down, 'up': up} 47 | 48 | for i in range(N): 49 | if i % 2 == 0: 50 | tornado(i + 1, "left") 51 | tornado(i + 1, "down") 52 | else: 53 | tornado(i + 1, "right") 54 | tornado(i + 1, "up") 55 | 56 | print(answer) 57 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/22_week/빙고.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | 6 | def is_bingo(): 7 | bingo_count = 0 8 | diagonal_1, diagonal_2 = 0, 0 9 | for i in range(N): 10 | if not sum(bingo_matrix[i]): # horizontal 11 | bingo_count += 1 12 | for j in range(N): 13 | if i == j: # (0, 0) (1, 1) (2, 2) (3, 3) (4, 4) 14 | diagonal_1 += bingo_matrix[i][j] 15 | if j == N - 1 - i: # (0, 4) (1, 3) (2, 2) (3, 1) (4, 0) 16 | diagonal_2 += bingo_matrix[i][j] 17 | for j in range(N): 18 | vertical = 0 19 | for i in range(N): 20 | vertical += bingo_matrix[i][j] 21 | if not vertical: 22 | bingo_count += 1 23 | 24 | if not diagonal_1: 25 | bingo_count += 1 26 | if not diagonal_2: 27 | bingo_count += 1 28 | 29 | if bingo_count >= 3: 30 | return True 31 | return False 32 | 33 | 34 | if __name__ == "__main__": 35 | N = 5 36 | bingo_matrix, bingo_index = [], {} 37 | for r in range(N): 38 | bingo_matrix.append(list(map(int, input().split()))) 39 | for c in range(N): 40 | bingo_index[bingo_matrix[r][c]] = (r, c) 41 | 42 | for i in range(N): 43 | input_numbers = list(map(int, input().split())) 44 | for j, input_number in enumerate(input_numbers): 45 | r, c = bingo_index[input_number] 46 | bingo_matrix[r][c] = 0 # check 47 | if is_bingo(): 48 | print(i * N + (j + 1)) 49 | exit() 50 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/23_week/바이러스.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | input = sys.stdin.readline 5 | 6 | START_INDEX = 1 7 | 8 | 9 | def get_count_of_virus_computer(start): 10 | count_of_virus_computer = 0 11 | 12 | queue = deque([start]) 13 | visited[start] = True 14 | 15 | while queue: 16 | v = queue.popleft() 17 | 18 | for i in network[v]: 19 | if not visited[i]: 20 | queue.append(i) 21 | visited[i] = True 22 | count_of_virus_computer += 1 23 | 24 | return count_of_virus_computer 25 | 26 | 27 | if __name__ == "__main__": 28 | N = int(input()) 29 | 30 | network = [[] for _ in range(N + 1)] 31 | visited = [False] * (N + 1) 32 | for _ in range(int(input())): 33 | a, b = map(int, input().split()) 34 | network[a].append(b) 35 | network[b].append(a) 36 | 37 | print(get_count_of_virus_computer(START_INDEX)) 38 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/23_week/연구소.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from itertools import combinations 3 | from copy import deepcopy 4 | 5 | input = sys.stdin.readline 6 | 7 | EMPTY, WALL, VIRUS = 0, 1, 2 8 | MAX_WALL = 3 9 | 10 | dx = [1, -1, 0, 0] 11 | dy = [0, 0, 1, -1] 12 | 13 | 14 | def spread_virus(matrix, x, y): 15 | global empty_space_count 16 | 17 | for i in range(4): 18 | nx, ny = x + dx[i], y + dy[i] 19 | 20 | if nx < 0 or nx >= N or ny < 0 or ny >= M: 21 | continue 22 | if matrix[nx][ny] == EMPTY: 23 | matrix[nx][ny] = VIRUS 24 | empty_space_count -= 1 25 | spread_virus(matrix, nx, ny) 26 | 27 | 28 | if __name__ == "__main__": 29 | N, M = map(int, input().split()) 30 | 31 | lab_matrix, empty_space, virus_space = [], [], [] 32 | for i in range(N): 33 | temp = list(map(int, input().split())) 34 | 35 | for j in range(M): 36 | if temp[j] == EMPTY: 37 | empty_space.append((i, j)) 38 | elif temp[j] == VIRUS: 39 | virus_space.append((i, j)) 40 | 41 | lab_matrix.append(temp) 42 | 43 | safe_space_count = 0 44 | for first, second, third in combinations(empty_space, MAX_WALL): 45 | copy_lab_matrix = deepcopy(lab_matrix) 46 | 47 | copy_lab_matrix[first[0]][first[1]] = WALL 48 | copy_lab_matrix[second[0]][second[1]] = WALL 49 | copy_lab_matrix[third[0]][third[1]] = WALL 50 | 51 | empty_space_count = len(empty_space) - 3 52 | for r, c in virus_space: 53 | spread_virus(copy_lab_matrix, r, c) 54 | 55 | safe_space_count = max(empty_space_count, safe_space_count) 56 | 57 | print(safe_space_count) 58 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/25_week/단어 수학.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import defaultdict 3 | 4 | input = sys.stdin.readline 5 | 6 | words = [] 7 | alphabet_sum_dict = defaultdict(int) 8 | 9 | N = int(input()) 10 | for _ in range(N): 11 | word = input().strip() 12 | words.append(word) 13 | 14 | word_length = len(word) 15 | for index, alphabet in enumerate(word): 16 | alphabet_sum_dict[alphabet] += pow(10, word_length - index - 1) 17 | 18 | sum_number = 0 19 | remain_number = 9 20 | for key, value in sorted(alphabet_sum_dict.items(), reverse=True, key=lambda item: item[1]): 21 | sum_number += value * remain_number 22 | remain_number -= 1 23 | 24 | print(sum_number) 25 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/39_week/토마토.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | input = sys.stdin.readline 5 | 6 | # -1 토마토 없음 / 0 안 익은 토마토 / 1 익은 토마토 7 | 8 | # 위, 아래, 상, 하, 좌, 우 9 | dz = [-1, 1, 0, 0, 0, 0] 10 | dy = [0, 0, 0, 0, -1, 1] 11 | dx = [0, 0, -1, 1, 0, 0] 12 | 13 | def bfs(): 14 | while queue: 15 | z, y, x = queue.popleft() 16 | 17 | for i in range(6): 18 | nz = z + dz[i] 19 | ny = y + dy[i] 20 | nx = x + dx[i] 21 | 22 | if nz < 0 or ny < 0 or nx < 0 or nz >= h or ny >= n or nx >= m: 23 | continue 24 | 25 | if dimen_3[nz][ny][nx] == -1: 26 | continue 27 | 28 | if dimen_3[nz][ny][nx] == 0: 29 | queue.append((nz, ny, nx)) 30 | dimen_3[nz][ny][nx] = dimen_3[z][y][x] + 1 31 | 32 | m, n, h = map(int, input().split()) 33 | 34 | def get_min_day(): 35 | max_day = -1 36 | 37 | for z in range(h): 38 | for y in range(n): 39 | for x in range(m): 40 | if dimen_3[z][y][x] == 0: 41 | return -1 42 | 43 | if dimen_3[z][y][x] > max_day: 44 | max_day = dimen_3[z][y][x] 45 | 46 | if max_day == 1: 47 | return 0 48 | 49 | return max_day - 1 50 | 51 | dimen_3 = [] 52 | queue = deque([]) 53 | 54 | for z in range(h): 55 | dimen_2 = [] 56 | for y in range(n): 57 | dimen_1 = list(map(int, input().split())) 58 | for x in range(m): 59 | if dimen_1[x] == 1: 60 | queue.append((z, y, x)) 61 | dimen_2.append(dimen_1) 62 | dimen_3.append(dimen_2) 63 | 64 | bfs() 65 | print(get_min_day()) -------------------------------------------------------------------------------- /Baekjoon/suyeon/40_week/진우의 민트초코우유.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | from itertools import permutations 4 | 5 | input = sys.stdin.readline 6 | 7 | 8 | def solution(prev, count, hp, visited): 9 | if count == 0: 10 | x, y = milk[prev] 11 | distance = abs(home[0] - x) + abs(home[1] - y) 12 | 13 | if distance <= hp: 14 | return True 15 | return False 16 | 17 | if hp <= 0: 18 | return False 19 | 20 | for idx in range(len(milk)): 21 | if not visited[idx]: 22 | visited[idx] = True 23 | 24 | x, y = milk[idx] 25 | p_x, p_y = None, None 26 | 27 | if prev == -1: # 처음 시작일 경우 28 | p_x, p_y = home[0], home[1] 29 | else: # 중간 단계일 경우 30 | p_x, p_y = milk[prev][0], milk[prev][1] 31 | 32 | distance = abs(p_x - x) + abs(p_y - y) 33 | if distance <= hp: 34 | if solution(idx, count - 1, hp - distance + h, visited): 35 | return True 36 | visited[idx] = False 37 | 38 | 39 | 40 | n, m, h = map(int, input().split()) 41 | 42 | town = [] 43 | 44 | home = None 45 | milk = [] 46 | 47 | for row in range(n): 48 | temp = list(map(int, input().split())) 49 | town.append(temp) 50 | 51 | for col in range(n): 52 | if temp[col] != 0: 53 | if temp[col] == 2: 54 | milk.append((row, col)) 55 | else: 56 | home = (row, col) 57 | 58 | answer = 0 59 | visited = [False] * len(milk) 60 | 61 | for count in range(len(milk), 0, -1): 62 | if solution(-1, count, m, visited): 63 | answer = count 64 | break 65 | 66 | print(answer) -------------------------------------------------------------------------------- /Baekjoon/suyeon/41_week/그림.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | input = sys.stdin.readline 5 | 6 | # 상, 하, 좌, 우 7 | dx = [-1, 1, 0, 0] 8 | dy = [0, 0, -1, 1] 9 | 10 | 11 | def bfs(x, y): 12 | queue = deque() 13 | queue.append((x, y)) 14 | 15 | count = 0 16 | 17 | while queue: 18 | x, y = queue.popleft() 19 | 20 | if matrix[x][y] != 1: 21 | continue 22 | 23 | count += 1 24 | matrix[x][y] = 0 25 | 26 | for i in range(4): 27 | nx = x + dx[i] 28 | ny = y + dy[i] 29 | 30 | if nx < 0 or nx >= n or ny < 0 or ny >= m: 31 | continue 32 | 33 | if matrix[nx][ny] == 1: 34 | queue.append((nx, ny)) 35 | 36 | return count 37 | 38 | 39 | n, m = map(int, input().split()) 40 | 41 | matrix = [list(map(int, input().split())) for _ in range(n)] 42 | 43 | picture = [] 44 | 45 | for x in range(n): 46 | for y in range(m): 47 | if matrix[x][y] == 1: 48 | picture.append(bfs(x, y)) 49 | 50 | print(len(picture)) 51 | print(max(picture) if len(picture) else 0) -------------------------------------------------------------------------------- /Baekjoon/suyeon/42_week/네트워크 연결.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | 6 | # 집합을 하나로 합침 7 | def union(parent, x, y): 8 | x_root = find(parent, x) 9 | y_root = find(parent, y) 10 | parent[y_root] = x_root 11 | 12 | 13 | # 집합의 대표번호를 반환 14 | def find(parent, x): 15 | if parent[x] != x: 16 | parent[x] = find(parent, parent[x]) 17 | return parent[x] 18 | 19 | 20 | # union-find 초기화 21 | def init_union_find(): 22 | return [i for i in range(n + 1)] 23 | 24 | 25 | n, m = int(input()), int(input()) 26 | 27 | # 크루스칼 알고리즘 - 비용에 따라 오름차순 정렬 28 | edges = sorted([tuple(map(int, input().split())) for _ in range(m)], key=lambda x:x[2]) 29 | 30 | answer = 0 31 | parent = init_union_find() 32 | 33 | for a, b, cost in edges: 34 | if find(parent, a) != find(parent, b): 35 | union(parent, a, b) 36 | answer += cost 37 | 38 | print(answer) -------------------------------------------------------------------------------- /Baekjoon/suyeon/43_week/로봇 청소기.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | EMPTY, WALL, CLEAN = 0, 1, 2 6 | 7 | # 북(상) 동(좌) 남(하) 서(우) - 반시계 방향 8 | dx = [-1, 0, 1, 0] 9 | dy = [0, 1, 0, -1] 10 | 11 | n, m = map(int, input().split()) 12 | x, y, d = map(int, input().split()) 13 | 14 | matrix = [list(map(int, input().split()))for _ in range(n)] 15 | 16 | answer = 1 17 | matrix[x][y] = CLEAN 18 | 19 | while True: 20 | check = False 21 | 22 | for _ in range(4): 23 | d = (d + 3) % 4 24 | nx = x + dx[d] 25 | ny = y + dy[d] 26 | 27 | if 0 <= nx < n and 0 <= ny < m and matrix[nx][ny] == EMPTY: 28 | matrix[nx][ny] = CLEAN 29 | answer += 1 30 | 31 | check = True 32 | x, y = nx, ny 33 | 34 | break 35 | 36 | if not check: 37 | nx = x - dx[d] 38 | ny = y - dy[d] 39 | 40 | if 0 <= nx < n and 0 <= ny < m and matrix[nx][ny] == WALL: 41 | break 42 | x, y = nx, ny 43 | 44 | print(answer) -------------------------------------------------------------------------------- /Baekjoon/suyeon/44_week/벽 부수고 이동하기.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | input = sys.stdin.readline 5 | 6 | EMPTY, WALL = 0, 1 7 | 8 | dx = [0, 0, 1, -1] 9 | dy = [1, -1, 0, 0] 10 | 11 | def bfs(): 12 | queue = deque() 13 | queue.append((0, 0, 0)) 14 | visited[0][0][0] = 1 15 | 16 | while queue: 17 | x, y, w = queue.popleft() 18 | 19 | if x == n - 1 and y == m - 1: 20 | return visited[x][y][w] 21 | 22 | for i in range(4): 23 | nx = x + dx[i] 24 | ny = y + dy[i] 25 | 26 | if nx < 0 or nx >= n or ny < 0 or ny >= m: 27 | continue 28 | 29 | if matrix[nx][ny] == EMPTY and visited[nx][ny][w] == 0: 30 | visited[nx][ny][w] = visited[x][y][w] + 1 31 | queue.append((nx, ny, w)) 32 | elif matrix[nx][ny] == WALL and w == 0: 33 | visited[nx][ny][1] = visited[x][y][w] + 1 34 | queue.append((nx, ny, 1)) 35 | 36 | return -1 37 | 38 | 39 | n, m = map(int, input().split()) 40 | matrix = [list(map(int, input().strip())) for _ in range(n)] 41 | visited = [[[0, 0] for _ in range(m)] for _ in range(n)] 42 | 43 | print(bfs()) -------------------------------------------------------------------------------- /Baekjoon/suyeon/45_week/일루미네이션.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | WALL, EMPTY = 1, 0 5 | 6 | input = sys.stdin.readline 7 | 8 | dx = [-1, 1, 0, 0] 9 | dy = [0, 0, -1, 1] 10 | 11 | 12 | def count_light(x, y): 13 | count = 0 14 | 15 | for d in range(4): 16 | nx, ny = x + dx[d], y + dy[d] 17 | 18 | if matrix[nx][ny] == 2: 19 | count += 1 20 | 21 | return count 22 | 23 | 24 | def spread_bfs(): 25 | queue = deque([(0, 0)]) 26 | matrix[0][0] = 2 27 | 28 | while queue: 29 | x, y = queue.popleft() 30 | 31 | for d in range(4): 32 | nx, ny = x + dx[d], y + dy[d] 33 | 34 | if nx < 0 or nx >= matrix_h or ny < 0 or ny >= matrix_w: 35 | continue 36 | 37 | if matrix[nx][ny] == EMPTY: 38 | matrix[nx][ny] = 2 39 | queue.append((nx, ny)) 40 | 41 | 42 | w, h = map(int, input().split()) 43 | 44 | walls = set() 45 | matrix = [[0] * (w * 2 + 3) for _ in range(h + 2)] 46 | matrix_h, matrix_w = len(matrix), len(matrix[0]) 47 | 48 | for i in range(h): 49 | row = i + 1 50 | col = 1 if i % 2 else 2 51 | 52 | for input_type in map(int, input().split()): 53 | if input_type == WALL: 54 | matrix[row][col] = WALL 55 | matrix[row][col + 1] = WALL 56 | walls.update([(row, col), (row, col + 1)]) 57 | 58 | col += 2 59 | 60 | spread_bfs() 61 | 62 | answer = 0 63 | for row, col in walls: 64 | if matrix[row][col] == WALL: 65 | answer += count_light(row, col) 66 | 67 | print(answer) 68 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/46_week/탈출.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | # 상 하 좌 우 5 | dx = [-1, 1, 0, 0] 6 | dy = [0, 0, -1, 1] 7 | 8 | 9 | def spread_water(): 10 | global water_set 11 | new_water_set = set() 12 | 13 | for x, y in water_set: 14 | for d in range(4): 15 | nx = x + dx[d] 16 | ny = y + dy[d] 17 | 18 | if nx < 0 or nx >= r or ny < 0 or ny >= c: 19 | continue 20 | 21 | if matrix[nx][ny] == EMPTY: 22 | matrix[nx][ny] = WATER 23 | new_water_set.add((nx, ny)) 24 | 25 | water_set = new_water_set 26 | 27 | 28 | def bfs(): 29 | queue = deque([start]) 30 | matrix[start[0]][start[1]] = 0 31 | 32 | while queue: 33 | spread_water() 34 | 35 | for _ in range(len(queue)): 36 | x, y = queue.popleft() 37 | 38 | for d in range(4): 39 | nx = x + dx[d] 40 | ny = y + dy[d] 41 | 42 | if nx < 0 or nx >= r or ny < 0 or ny >= c: 43 | continue 44 | 45 | if matrix[nx][ny] == EMPTY: 46 | matrix[nx][ny] = matrix[x][y] + 1 47 | queue.append((nx, ny)) 48 | elif matrix[nx][ny] == BEAVER: 49 | return matrix[x][y] + 1 50 | 51 | return "KAKTUS" 52 | 53 | 54 | EMPTY, WATER, STONE = '.', '*', 'X' 55 | BEAVER, HEDGEHOG = 'D', 'S' 56 | 57 | r, c = map(int, input().split()) 58 | 59 | matrix = [] 60 | water_set = set() 61 | start, end = (0, 0), (0, 0) 62 | 63 | for i in range(r): 64 | matrix.append(list(sys.stdin.readline().strip())) 65 | 66 | for j, token in enumerate(matrix[i]): 67 | if token == BEAVER: 68 | end = (i, j) 69 | elif token == HEDGEHOG: 70 | start = (i, j) 71 | elif token == WATER: 72 | water_set.add((i, j)) 73 | 74 | print(bfs()) 75 | 76 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/47_week/평범한 배낭.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | n, k = map(int, input().split()) 4 | dp = [0] * (k + 1) 5 | 6 | for _ in range(n): 7 | weight, value = map(int, sys.stdin.readline().split()) 8 | 9 | for i in range(k, weight - 1, -1): 10 | dp[i] = max(value + dp[i - weight], dp[i]) 11 | 12 | print(dp[-1]) 13 | 14 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/48_week/상자 배달.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soo5717/2021-Algorithm-Study/6f75ec962a8b877dbf953b271012b64c4c02ca5f/Baekjoon/suyeon/48_week/상자 배달.py -------------------------------------------------------------------------------- /Baekjoon/suyeon/49_week/드래곤 커브.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | MATRIX_SIZE = 101 4 | 5 | # 우0 상1 좌2 하3 6 | dx = [1, 0, -1, 0] 7 | dy = [0, -1, 0, 1] 8 | 9 | 10 | def draw_dragon_curve(info): 11 | start_x, start_y, direction, generation = info 12 | 13 | move = [direction] 14 | for _ in range(generation): 15 | move.extend([(d + 1) % 4 for d in move[::-1]]) 16 | 17 | nx, ny = start_x, start_y 18 | matrix[nx][ny] = True 19 | 20 | for d in move: 21 | nx, ny = nx + dx[d], ny + dy[d] 22 | matrix[nx][ny] = True 23 | 24 | 25 | def get_rectangle_count(): 26 | count = 0 27 | 28 | for i in range(1, MATRIX_SIZE): 29 | for j in range(1, MATRIX_SIZE): 30 | if matrix[i - 1][j - 1] and matrix[i - 1][j] and matrix[i][j - 1] and matrix[i][j]: 31 | count += 1 32 | 33 | return count 34 | 35 | 36 | N = int(input()) 37 | matrix = [[False] * MATRIX_SIZE for _ in range(MATRIX_SIZE)] 38 | 39 | for _ in range(N): 40 | draw_dragon_curve(map(int, sys.stdin.readline().split())) 41 | 42 | print(get_rectangle_count()) 43 | 44 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/49_week/퇴사 2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | N = int(input()) 4 | matrix = [tuple(map(int, sys.stdin.readline().split())) for _ in range(N)] 5 | 6 | max_price = 0 7 | dp = [0] * (N + 1) 8 | 9 | for day in range(N - 1, -1, -1): 10 | term, price = matrix[day] 11 | 12 | if day + term <= N: 13 | max_price = max(price + dp[day + term], max_price) 14 | 15 | dp[day] = max_price 16 | 17 | print(max_price) 18 | 19 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/51_week/숨바꼭질 2.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | MAX_LENGTH = 100_001 4 | 5 | 6 | def bfs(start, visited): 7 | if n >= k: 8 | return n - k, 1 9 | 10 | count = 0 11 | 12 | queue = deque([start]) 13 | visited[start] = 0 14 | 15 | while queue: 16 | x = queue.popleft() 17 | 18 | if x == k: 19 | count += 1 20 | continue 21 | 22 | for nx in (x * 2, x + 1, x - 1): 23 | if nx < 0 or nx >= MAX_LENGTH or nx >= 2 * k: 24 | continue 25 | 26 | if visited[nx] == -1 or visited[nx] == visited[x] + 1: # 첫 방문 or 시간 같은 경우 27 | visited[nx] = visited[x] + 1 28 | queue.append(nx) 29 | 30 | return visited[k], count 31 | 32 | 33 | n, k = map(int, input().split()) 34 | 35 | min_time, min_count = bfs(n, [-1] * MAX_LENGTH) 36 | 37 | print(min_time) 38 | print(min_count) 39 | 40 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/52_week/N번째 큰 수.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from heapq import heappush, heappop, heapify 3 | 4 | n = int(input()) 5 | 6 | min_heap = list(map(int, sys.stdin.readline().split())) 7 | heapify(min_heap) 8 | 9 | for _ in range(n - 1): 10 | for num in map(int, sys.stdin.readline().split()): 11 | if min_heap[0] < num: 12 | heappop(min_heap) 13 | heappush(min_heap, num) 14 | 15 | print(min_heap[0]) 16 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/53_week/뱀.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | input = lambda: sys.stdin.readline() 5 | 6 | EMPTY, SNAKE, APPLE = 0, 1, 2 7 | LEFT, RIGHT = 'L', 'D' 8 | 9 | # 오른쪽, 아래, 왼쪽, 위 (시계 방향) 10 | dx = [0, 1, 0, -1] 11 | dy = [1, 0, -1, 0] 12 | 13 | 14 | def rotate(time, direction): 15 | if time not in rotations: 16 | return direction 17 | 18 | if rotations[time] == RIGHT: 19 | return (direction + 1) % 4 20 | 21 | if rotations[time] == LEFT: 22 | return 3 if not direction else direction - 1 23 | 24 | 25 | def move(): 26 | time, direction = 0, 0 27 | 28 | head_x, head_y = 0, 0 29 | snakes = deque([(head_x, head_y)]) 30 | 31 | while True: 32 | direction = rotate(time, direction) 33 | nx = head_x + dx[direction] 34 | ny = head_y + dy[direction] 35 | 36 | time += 1 37 | 38 | if nx < 0 or nx >= n or ny < 0 or ny >= n: 39 | break 40 | 41 | if matrix[nx][ny] == SNAKE: 42 | break 43 | 44 | if matrix[nx][ny] != APPLE: 45 | tail_x, tail_y = snakes.popleft() 46 | matrix[tail_x][tail_y] = EMPTY 47 | 48 | matrix[nx][ny] = SNAKE 49 | snakes.append((nx, ny)) 50 | head_x, head_y = nx, ny 51 | 52 | return time 53 | 54 | 55 | n = int(input()) 56 | 57 | rotations = {} 58 | matrix = [[EMPTY] * n for _ in range(n)] 59 | 60 | for _ in range(int(input())): 61 | row, col = map(int, input().split()) 62 | matrix[row - 1][col - 1] = APPLE 63 | 64 | for _ in range(int(input())): 65 | second, rotation = input().split() 66 | rotations[int(second)] = rotation 67 | 68 | print(move()) 69 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/54_week/트리의 독립집합.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = lambda: sys.stdin.readline() 4 | 5 | 6 | def dfs(start_node): 7 | # 노드 방문 체크 8 | visited[start_node] = True 9 | 10 | # 루트 포함만 dp 가중치 더하기 & path 추가 11 | dp[start_node][1] += weights[start_node] 12 | path[start_node][1].append(start_node) 13 | 14 | for node in tree[start_node]: 15 | if not visited[node]: 16 | sub_path = dfs(node) 17 | 18 | # 부모를 포함 하지 않을 시 -> 자식 포함 or 미포함 경우의 수 19 | dp[start_node][0] += max(dp[node][0], dp[node][1]) 20 | path[start_node][0] += sub_path[0 if dp[node][0] > dp[node][1] else 1] 21 | 22 | # 부모를 포함할 경우 -> 자식 포함 할 수 없음 23 | dp[start_node][1] += dp[node][0] 24 | path[start_node][1] += sub_path[0] 25 | 26 | return path[start_node] 27 | 28 | 29 | n = int(input()) 30 | weights = [0] + list(map(int, input().split())) 31 | 32 | tree = [[] for _ in range(n + 1)] 33 | visited = [False] * (n + 1) 34 | 35 | # 0 - 루트 노드 미포함, 1 - 루트 노드 포함 36 | dp = [[0, 0] for _ in range(n + 1)] # 최대 독립 집합 크기 37 | path = [[[], []] for _ in range(n + 1)] # 독립 집합 원소 38 | 39 | for _ in range(n - 1): 40 | a, b = map(int, input().split()) 41 | 42 | tree[a].append(b) 43 | tree[b].append(a) 44 | 45 | dfs(1) 46 | idx = 0 if dp[1][0] > dp[1][1] else 1 47 | 48 | print(dp[1][idx]) 49 | print(*sorted(path[1][idx])) 50 | -------------------------------------------------------------------------------- /Baekjoon/suyeon/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soo5717/2021-Algorithm-Study/6f75ec962a8b877dbf953b271012b64c4c02ca5f/Baekjoon/suyeon/README.md -------------------------------------------------------------------------------- /Programmers/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soo5717/2021-Algorithm-Study/6f75ec962a8b877dbf953b271012b64c4c02ca5f/Programmers/.DS_Store -------------------------------------------------------------------------------- /Programmers/42_week/점프와 순간 이동.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | ans = 0 3 | while n > 0: 4 | ans += n % 2 5 | n = n // 2 6 | 7 | return ans 8 | -------------------------------------------------------------------------------- /Programmers/eugene/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soo5717/2021-Algorithm-Study/6f75ec962a8b877dbf953b271012b64c4c02ca5f/Programmers/eugene/.DS_Store -------------------------------------------------------------------------------- /Programmers/eugene/2018_kakao_blind/뉴스 클러스터링.py: -------------------------------------------------------------------------------- 1 | def solution(str1, str2): 2 | str1=str1.lower() 3 | str2=str2.lower() 4 | 5 | #두 글짜씩 끊어서 다중집합 생성 6 | MultiSetX,MultiSetY=[],[] 7 | for i in range(len(str1)-1): 8 | if str1[i:i+2].isalpha(): MultiSetX.append(str1[i:i+2]) 9 | for i in range(len(str2)-1): 10 | if str2[i:i+2].isalpha(): MultiSetY.append(str2[i:i+2]) 11 | 12 | #다중집합 교집합, 합집합 13 | temp_u, temp_i=MultiSetX.copy(),MultiSetX.copy() 14 | union_XY = MultiSetX.copy() 15 | intersection_XY=[] 16 | 17 | for i in MultiSetY: 18 | union_XY.append(i) if i not in temp_u else temp_u.remove(i) 19 | if i in temp_i: 20 | temp_i.remove(i) 21 | intersection_XY.append(i) 22 | 23 | len_uni=len(union_XY) 24 | len_inter=len(intersection_XY) 25 | answer = len_inter/len_uni if len_uni else 1 26 | 27 | return int(answer*65536) 28 | -------------------------------------------------------------------------------- /Programmers/eugene/2018_kakao_blind/캐시.py: -------------------------------------------------------------------------------- 1 | def solution(cacheSize, cities): 2 | answer = 0 3 | my_cache=[] 4 | 5 | if cacheSize ==0: 6 | return len(cities)*5 7 | 8 | for city in cities: 9 | city=city.lower() 10 | if city in my_cache: #my_cache에 city가 있으면 11 | answer+=1 12 | my_cache.remove(city) 13 | else: #없으면 14 | answer+=5 15 | if len(my_cache)==cacheSize: 16 | del my_cache[0] #cache가 꽉 차있으면 맨 앞을 비우기 17 | my_cache.append(city) #city추가. 18 | return answer 19 | -------------------------------------------------------------------------------- /Programmers/eugene/2018_kakao_blind/프랜즈4블록.py: -------------------------------------------------------------------------------- 1 | def solution(m, n, board): 2 | answer = 0 3 | for b in range(m): board[b]=list(board[b]) 4 | 5 | while True: 6 | index_list=[] 7 | for i in range(m-1): 8 | for j in range(n-1): 9 | if board[i][j] == board[i][j+1] == board[i+1][j] == board[i+1][j+1] != "0": 10 | index_list+=[(i, j), (i, j+1),(i+1, j), (i+1, j+1)] 11 | 12 | 13 | set_index_len= len(set(index_list)) 14 | if set_index_len ==0: #지울 블록 없으면 종료 15 | break 16 | answer+=set_index_len 17 | 18 | for x,y in index_list: #지울 블록 지우기 19 | board[x][y]="0" 20 | 21 | for x,y in reversed(index_list): 22 | chk_drop=x-1 23 | while chk_drop >=0: 24 | if board[x][y]=="0" and board[chk_drop][y] !="0": 25 | board[x][y]=board[chk_drop][y] #아래로 내리고 26 | board[chk_drop][y]="0" #내린 부분 0으로 채우기 27 | x-=1 28 | chk_drop-=1 #윗 줄로 올라가서 또 확인. 맨 윗줄까지 29 | return answer 30 | -------------------------------------------------------------------------------- /Programmers/eugene/2019_kakao_blind/실패율.py: -------------------------------------------------------------------------------- 1 | def solution(N, stages): 2 | answer = [] 3 | result={} 4 | 5 | for i in range(1,N+2): result[i] =0 6 | for stage in stages: result[stage]+=1 7 | 8 | for i in range(1,N+1): 9 | stage_num,noclear=0,0 10 | for j in range(i,N+2) : 11 | stage_num+=result[j] 12 | noclear= result[i] 13 | answer+= [(i,noclear/stage_num)] if stage_num else [(i,0)] 14 | 15 | answer=sorted(answer, key=lambda x:x[1], reverse=True) 16 | return [k[0] for k in answer] 17 | -------------------------------------------------------------------------------- /Programmers/eugene/2019_kakao_blind/오픈채팅방.py: -------------------------------------------------------------------------------- 1 | def solution(record): 2 | answer = [] 3 | names={} 4 | for r in record: 5 | temp=r.split() 6 | #user_id에 따른 이름 설정 7 | if temp[0]=='Enter' or temp[0] =='Change': 8 | names[temp[1]]=temp[2] 9 | 10 | for r in record: 11 | temp=r.split() 12 | if temp[0]=='Enter': 13 | answer+=[names[temp[1]]+"님이 들어왔습니다."] 14 | elif temp[0] =='Leave': 15 | answer+=[names[temp[1]]+"님이 나갔습니다."] 16 | return answer 17 | -------------------------------------------------------------------------------- /Programmers/eugene/2019_kakao_blind/후보키.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | 3 | def solution(relation): 4 | combi=[] 5 | result=0 6 | col_len=len(relation[0]) 7 | col_list=[i for i in range(col_len)] 8 | for i in range(1,col_len+1): 9 | combi+=list(combinations(col_list,i)) 10 | 11 | while combi: 12 | temp=list(combi) 13 | if candidate_check(combi[0],relation): #0번째 조합이 후보키인지 판별: 14 | result+=1 15 | for c in combi: 16 | if include_check(c,combi[0]): 17 | temp.remove(c) 18 | else: temp.remove(combi[0]) 19 | combi=temp 20 | return result 21 | 22 | def candidate_check(c,relation): #받은 인자 c가 후보키인지 판별 23 | candi_temp=[[] for _ in range(len(relation))] 24 | c=list(c) 25 | for i in c: 26 | for j in range(len(relation)): 27 | candi_temp[j]+=[relation[j][i]] 28 | return False if len(candi_temp) != len(set(list(map(tuple,candi_temp)))) else True 29 | 30 | def include_check(items,item): 31 | for n in item: 32 | if n not in items: return False 33 | return True 34 | -------------------------------------------------------------------------------- /Programmers/eugene/2020_kakao_blind/괄호 변환.py: -------------------------------------------------------------------------------- 1 | def solution(p): 2 | if not p: return "" #step1 3 | 4 | u,v,proper = divide_correct(p) #step2+3 5 | 6 | if proper : #step3 7 | return u+solution(v) 8 | else : #step4 9 | reverse=''.join([')' if i=='(' else '(' for i in u[1:len(u)-1] ]) 10 | return '('+solution(v)+')'+reverse 11 | 12 | 13 | def divide_correct(s): #u,v 분리+올바른 괄호 판별 14 | left,right=0,0 15 | proper=True 16 | 17 | for i in range(len(s)): 18 | if s[i]=="(": left+=1 19 | else: right+=1 20 | 21 | if left < right:#한번이라도 right가 크면 올바르지 않은 문자열 22 | proper=False 23 | 24 | if(left==right): #균형잡힌 괄호 문자열 u,v 분리 25 | u= s[:i+1] 26 | v= s[i+1:] 27 | return u,v,proper 28 | -------------------------------------------------------------------------------- /Programmers/eugene/2020_kakao_blind/문자열 압축.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | answer=[] 3 | for i in range(1, len(s)//2+1): 4 | result = "" 5 | word=s 6 | while word: 7 | first=word[:i] 8 | word=word[i:] 9 | cnt=1 10 | while (first==word[:i]): 11 | cnt+=1 12 | word=word[i:] 13 | result += str(first) if cnt== 1 else str(cnt)+str(first) 14 | answer+=[len(result)] 15 | return 1 if answer==[] else min(answer) 16 | -------------------------------------------------------------------------------- /Programmers/eugene/2020_kakao_blind/자물쇠와 열쇠.py: -------------------------------------------------------------------------------- 1 | def solution(key, lock): 2 | m,n=len(key),len(lock) 3 | case_turn=turn(key,m) 4 | 5 | for case in case_turn: 6 | for i in range(n+m-1): 7 | for j in range(n+m-1): 8 | if check(case,lock,i,j,m,n): return True 9 | return False 10 | 11 | def check(key, lock, x, y, m, n): 12 | 13 | #lock 중앙 배치의 확장 base 14 | base=[ [0]*(n+2*(m-1)) for _ in range(n+2*(m-1))] 15 | 16 | for i in range(n): 17 | for j in range(n): 18 | base[m+i-1][m+j-1]=lock[i][j] 19 | 20 | #base에 key값 더하기 21 | for i in range(m): 22 | for j in range(m): 23 | base[x+i][y+j]+=key[i][j] 24 | 25 | #base의 lock 영역을 돌면서 1이 아닌 값이 있는지 체크. 26 | start = m-1 27 | end = start+n 28 | for i in range(start, end): 29 | for j in range(start,end): 30 | if base[i][j] != 1: return False 31 | return True 32 | 33 | def turn(key,m): #회전하는 모든 경우 34 | case_turn=[] 35 | for _ in range(4): 36 | case=[] 37 | for i in range(m): 38 | case+= [[key[m-j-1][i] for j in range(m)]] 39 | case_turn+=[case] 40 | key=case 41 | return case_turn 42 | -------------------------------------------------------------------------------- /Programmers/eugene/2021_kakao_blind/메뉴 리뉴얼.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | from collections import Counter 3 | 4 | def solution(orders, course): 5 | final_set_menu = [] 6 | 7 | 8 | for c in course: #각 개수의 조합 구하기 9 | set_menu_list=[] 10 | for order in orders: #손님이 시킨 메뉴에서 11 | set_menu_list += combinations(sorted(order), c) 12 | #최소 2명 이상의 손님으로부터 주문된 조합에 대해서만 후보에 포함. 13 | set_menu_list = Counter(set_menu_list).most_common() 14 | 15 | for set_menu,cnt in set_menu_list: 16 | if cnt >1 and cnt==set_menu_list[0][1]: #가장 많이 함께 주문한, 2명 이상의 손님이 주문한 17 | final_set_menu += [set_menu] 18 | 19 | 20 | return [''.join(menu) for menu in sorted(final_set_menu)] 21 | -------------------------------------------------------------------------------- /Programmers/eugene/2021_kakao_blind/순위 검색.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | from collections import defaultdict 3 | import bisect 4 | 5 | def solution(info, query): 6 | answer = [] 7 | people = defaultdict(list) 8 | 9 | for i in info: 10 | people_info = i.split() 11 | score = int(people_info[-1]) #점수 12 | people[''.join(people_info[:-1])].append(score) 13 | 14 | for j in range(4): 15 | combi = list(combinations(people_info[:-1], j)) 16 | for c in combi: 17 | people[''.join(c)].append(score) 18 | 19 | for i in people: 20 | people[i].sort() #탐색을 위해 정렬 21 | 22 | for q in query: #쿼리 조건에 맞게 탐색 23 | key = q.split() 24 | score = int(key.pop()) 25 | key = ''.join(key) 26 | key = key.replace('and', '').replace(' ', '').replace('-', '') # 27 | answer.append(len(people[key])-bisect.bisect_left(people[key], score)) 28 | return answer 29 | -------------------------------------------------------------------------------- /Programmers/eugene/2021_kakao_blind/신규 아이디 추천.py: -------------------------------------------------------------------------------- 1 | import re 2 | def solution(new_id): 3 | answer = '' 4 | 5 | #step1. 6 | new_id=new_id.lower() 7 | #step2. 8 | new_id=''.join(re.findall('[a-z0-9-_.]+', new_id)) 9 | #step3. 10 | new_id = re.sub('[..]+', '.', new_id) 11 | #step4. 12 | new_id = new_id.strip('.') 13 | #step5. 14 | if not new_id: 15 | new_id = 'a' 16 | 17 | #step6. 18 | new_id=new_id[:15].strip('.') 19 | #step7. 20 | lenNewId = len(new_id) 21 | if lenNewId <=2: 22 | new_id=new_id+new_id[-1]*(3-lenNewId) 23 | 24 | return new_id 25 | -------------------------------------------------------------------------------- /Programmers/eugene/24_week/숫자 문자열과 영단어.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | answer = "" 3 | temp = "" 4 | 5 | num_dict = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] 6 | 7 | for x in s: 8 | if x.isdigit(): 9 | answer += x 10 | else: 11 | temp += x 12 | for i in range(10): 13 | if temp == num_dict[i]: 14 | answer += str(i) 15 | temp = "" 16 | 17 | return int(answer) 18 | -------------------------------------------------------------------------------- /Programmers/eugene/25_week/거리두기 확인하기.py: -------------------------------------------------------------------------------- 1 | def rule_check(room): 2 | manhattan = [(-2, 0), (-1, -1), (-1, 0), (-1, 1), (0, -2), (0, -1), (0, 1), (0, 2), (1, -1), (1, 0), (1, 1), (2, 0) ] 3 | 4 | for x, row in enumerate(room): 5 | for y, col in enumerate(row): 6 | if col != 'P': 7 | continue 8 | for mx, my in manhattan: 9 | nx = x + mx 10 | ny = y + my 11 | 12 | if nx < 0 or ny < 0 or nx >= 5 or ny >=5: 13 | continue 14 | 15 | if room[nx][ny] == 'P': #거리두기 실패. 그러나 파티션 확인해보기 16 | if (abs(mx) + abs(my) == 1): # 거리 1 : 상하좌우(파티션 고려X) 17 | return 0 18 | else : #거리 2 19 | if not mx or not my: #동일 직선 상 20 | if mx > 0: cx = x+1 21 | elif mx < 0: cx = x-1 22 | else: cx = x 23 | 24 | if my > 0: cy = y+1 25 | elif my < 0: cy = y-1 26 | else: cy = y 27 | 28 | if room[cx][cy] == 'O': 29 | return 0 30 | else: 31 | if room[x][ny] == 'O' or room[nx][y] =='O': 32 | return 0 33 | return 1 34 | 35 | def solution(places): 36 | result = [] 37 | for p in places: 38 | result.append(rule_check(p)) 39 | return result 40 | -------------------------------------------------------------------------------- /Programmers/eugene/26_week/수식 최대화.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | import copy 3 | 4 | def solution(expression): 5 | answer = 0 6 | operator_case = [["+", "-", "*"], ["+", "*", "-"], 7 | ["-", "+", "*"],["-", "*", "+"], 8 | ["*", "+", "-"],["*", "-", "+"]] 9 | 10 | temp="" 11 | operand, operator= [], [] 12 | for e in expression: 13 | if not e.isdigit(): 14 | operand.append(temp) 15 | operator.append(e) 16 | temp = "" 17 | else: 18 | temp += e 19 | operand.append(temp) 20 | 21 | max_num = 0 22 | for case in operator_case: 23 | temp_operand = copy.deepcopy(operand) 24 | temp_operator = copy.deepcopy(operator) 25 | 26 | for c in case: 27 | while c in temp_operator: 28 | idx = temp_operator.index(c) 29 | temp_operand[idx] = str(eval(temp_operand[idx]+ c+temp_operand[idx+1])) 30 | 31 | del temp_operand[idx+1] 32 | del temp_operator[idx] 33 | 34 | max_num = max(max_num, abs(int(temp_operand[0]))) 35 | return max_num 36 | -------------------------------------------------------------------------------- /Programmers/eugene/27_week/튜플.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | answer, result = [], [] 3 | 4 | s_split = s[2:-2].split("},{") 5 | for i in range(len(s_split)): 6 | answer.append(s_split[i].split(",")) 7 | 8 | prev = set() 9 | for ans in sorted(answer, key=len): 10 | set_ans = set(ans) 11 | result.append(list(set_ans - prev)[0]) 12 | prev = set_ans 13 | 14 | result = list(map(int,result)) 15 | return result 16 | -------------------------------------------------------------------------------- /Programmers/eugene/28_week/파일명 정렬.py: -------------------------------------------------------------------------------- 1 | def solution(files): 2 | answer = [] 3 | 4 | for file in files: 5 | head, number = '', '' 6 | for f in file: 7 | if f.isdigit(): 8 | number += f 9 | elif number == '': 10 | head += f 11 | else: 12 | break 13 | 14 | answer.append((file, head.lower(), int(number))) 15 | 16 | answer.sort(key = lambda x: (x[1], x[2])) 17 | return [file[0] for file in answer] 18 | -------------------------------------------------------------------------------- /Programmers/eugene/29_week/n진수 게임.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | def convert(num, base): 4 | tmp = string.digits + string.ascii_uppercase 5 | q, r = divmod(num, base) 6 | if q == 0: 7 | return tmp[r] 8 | else: 9 | return convert(q, base) + tmp[r] 10 | 11 | def solution(n, t, m, p): 12 | 13 | answer, numbers = '', '' 14 | max_cnt = t * m 15 | 16 | cnt = 0 17 | while cnt < max_cnt: 18 | numbers += convert(cnt, n) 19 | cnt += 1 20 | 21 | 22 | return numbers[p-1::m][:t] 23 | -------------------------------------------------------------------------------- /Programmers/eugene/30_week/주차 요금 계산.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | def solution(fees, records): 4 | answer = [] 5 | 6 | base_time, base_fee, unit_time, unit_fee = fees 7 | cars_info, time_temp, cars_stat = dict(), dict(), dict() 8 | 9 | for record in records: 10 | _, car_number, _ = record.split(' ') 11 | cars_info[car_number] = 0 12 | 13 | for record in records: 14 | time, car_number, status = record.split(' ') 15 | cars_stat[car_number] = status 16 | 17 | if status == 'IN': 18 | time_temp[car_number] = time 19 | 20 | else: 21 | in_time = datetime.datetime.strptime(time_temp[car_number], "%H:%M") 22 | out_time = datetime.datetime.strptime(time, "%H:%M") 23 | time_interval = (out_time - in_time) 24 | 25 | cars_info[car_number] += time_interval.seconds//60 26 | 27 | 28 | for car_number, status in cars_stat.items(): 29 | if status == 'IN': 30 | in_time = datetime.datetime.strptime(time_temp[car_number], "%H:%M") 31 | out_time = datetime.datetime.strptime('23:59', "%H:%M") 32 | time_interval = (out_time - in_time) 33 | 34 | cars_info[car_number] += time_interval.seconds//60 35 | 36 | cars_info = sorted(cars_info.items(), key=lambda x : int(x[0])) 37 | 38 | for _, time in cars_info: 39 | unit = 0 40 | if time > base_time: 41 | unit = (time - base_time) // unit_time 42 | if (time - base_time) % unit_time: 43 | unit += 1 44 | 45 | total_fee = base_fee + unit * unit_fee 46 | answer.append(total_fee) 47 | 48 | return answer 49 | -------------------------------------------------------------------------------- /Programmers/eugene/31_week/k진수에서 소수 개수 구하기.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def solution(n, k): 4 | answer = 0 5 | 6 | numbers = change(n, k) 7 | temp = '' 8 | 9 | kkk = numbers.split('0') 10 | 11 | for k in kkk: 12 | if k != '' and isPrime(int(k)): 13 | answer += 1 14 | return answer 15 | 16 | def isPrime(x): 17 | if x == 2: 18 | return True 19 | 20 | if x == 1 or x % 2 == 0: 21 | return False 22 | 23 | for i in range(3, int(math.sqrt(x))+1, 2): 24 | if x % i == 0 : 25 | return False 26 | return True 27 | 28 | def change(n, q): 29 | rev_base = '' 30 | 31 | while n > 0: 32 | n, mod = divmod(n, q) 33 | rev_base += str(mod) 34 | 35 | return rev_base[::-1] 36 | -------------------------------------------------------------------------------- /Programmers/eugene/32_week/멀쩡한 사각형.py: -------------------------------------------------------------------------------- 1 | def gcd(x, y): 2 | while y: 3 | x, y = y, x % y 4 | return x 5 | 6 | def solution(w,h): 7 | return w * h - (w + h - gcd(w, h)) 8 | -------------------------------------------------------------------------------- /Programmers/eugene/33_week/불량 사용자.py: -------------------------------------------------------------------------------- 1 | from itertools import product 2 | 3 | def solution(user_id, banned_id): 4 | answer = 0 5 | temp_id = [] 6 | 7 | candi = [[] for _ in banned_id] 8 | exclude_list = [] 9 | 10 | for idx, b_id in enumerate(banned_id): 11 | for u_id in user_id: 12 | if len(b_id) != len(u_id): 13 | continue 14 | temp_id = list(u_id) 15 | for i in range(len(b_id)): 16 | if b_id[i] == '*': 17 | temp_id[i] = '*' 18 | if ''.join(temp_id) == b_id: 19 | candi[idx] += [u_id] 20 | 21 | candi_case = [] 22 | all_case = list(product(*candi)) 23 | for case in all_case: 24 | set_case = set(case) 25 | if len(set_case) != len(candi): 26 | continue 27 | if set_case not in candi_case: 28 | candi_case.append(set_case) 29 | 30 | return len(candi_case) 31 | -------------------------------------------------------------------------------- /Programmers/eugene/34_week/방금 그곡.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | def solution(m, musicinfos): 4 | play_times = dict() 5 | 6 | 7 | #Step1. m 재구성 8 | now_song_code = melody_find(m) 9 | #Step2. 곡 찾기 10 | for musicinfo in musicinfos: 11 | start, end, name, code = musicinfo.split(',') 12 | play_times[name]=0; 13 | # 시간 계산 14 | time = time_converter(start, end) 15 | 16 | # code 재구성 17 | song_code = melody_find(code) 18 | #네오가 기억한 멜로디(now_song_code)가 time분 안에 music(song_code)과 일치하는 시간 계산 = play_time 19 | total_song = song_code * (time //len(song_code)) + song_code[:time %len(song_code)] 20 | for i in range(len(total_song)): 21 | if (total_song[i:i+len(now_song_code)] == now_song_code): 22 | play_times[name] += len(now_song_code) 23 | # Step3. play_times에서 가장 긴 시간 -> 먼저 입력된 -> None 순서로 결과 RETURN 24 | # print(play_times) 25 | sorted_dict = sorted(play_times.items(), key = lambda item: item[1],reverse=True) 26 | if sorted_dict[0][1] == 0: 27 | return "(None)" 28 | 29 | return sorted_dict[0][0] 30 | 31 | 32 | def time_converter(start, end): 33 | time = datetime.datetime.strptime(end, "%H:%M") - datetime.datetime.strptime(start, "%H:%M") 34 | return time.seconds//60 35 | 36 | 37 | def melody_find(m): 38 | melody = [] 39 | 40 | for i in range(len(m)): 41 | if i == len(m) - 1: 42 | if m[i] != '#': 43 | melody.append(m[i]) 44 | break 45 | 46 | if m[i] == '#': 47 | continue 48 | 49 | if m[i+1] != '#': 50 | melody.append(m[i]) 51 | else: 52 | melody.append(m[i]+m[i+1]) 53 | 54 | return melody 55 | -------------------------------------------------------------------------------- /Programmers/eugene/35_week/모음사전.py: -------------------------------------------------------------------------------- 1 | def solution(word): 2 | answer = 0 3 | alphabet={"A":0, "E":1, "I":2, "O":3, "U":4} 4 | 5 | for i in range(len(word)): 6 | for j in range(4, i, -1): 7 | answer += 5 ** (j-i) * alphabet[word[i]] 8 | answer += 1 + alphabet[word[i]] 9 | return answer 10 | -------------------------------------------------------------------------------- /Programmers/eugene/36_week/n^2 배열 자르기.py: -------------------------------------------------------------------------------- 1 | def solution(n, left, right): 2 | answer = [] 3 | 4 | start_i, start_j = left // n, left % n 5 | end_i, end_j = right // n, right % n 6 | 7 | i, j = start_i, start_j 8 | while True: 9 | answer.append(max(i, j)+1) 10 | 11 | if i == end_i and j == end_j: 12 | break 13 | 14 | if j >= n-1: 15 | i += 1 16 | j = 0 17 | else: 18 | j+=1 19 | 20 | return answer 21 | -------------------------------------------------------------------------------- /Programmers/eugene/37_week/피로도.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def solution(k, dungeons): 4 | answer = -1 5 | len_dungeons = len(dungeons) 6 | 7 | for data in permutations(dungeons, len_dungeons): 8 | hp, cnt = k, 0 9 | for min_tired, use_tired in data: 10 | if hp < min_tired: 11 | continue 12 | hp -= use_tired 13 | cnt += 1 14 | 15 | answer = answer if answer > cnt else cnt 16 | if answer == len_dungeons: 17 | break 18 | 19 | return answer 20 | -------------------------------------------------------------------------------- /Programmers/eugene/38_week/교점에 별 만들기.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | import math 3 | 4 | MAXNUM = 1000000000000001 5 | 6 | def solution(line): 7 | case = list(combinations(line, 2)) 8 | point_list = [] 9 | 10 | min_x, min_y = MAXNUM , MAXNUM 11 | max_x, max_y = -MAXNUM , -MAXNUM 12 | for line1, line2 in case: 13 | a, b, e = line1 14 | c, d, f = line2 15 | 16 | den = a*d - b*c 17 | x_mol = b*f - e*d 18 | y_mol = e*c - a*f 19 | 20 | if den == 0: 21 | continue 22 | 23 | x, y = (b*f-e*d)/(a*d - b*c) , (e*c-a*f)/(a*d - b*c) 24 | if x.is_integer() and y.is_integer(): 25 | point_list.append([int(x), int(y)]) 26 | min_x, max_x = min(min_x, int(x)), max(max_x, int(x)) 27 | min_y, max_y = min(min_y, int(y)), max(max_y, int(y)) 28 | 29 | answer = [["."] * (abs(max_x - min_x)+1) for j in range(abs(max_y - min_y)+1)] 30 | 31 | # 2. 맵 그리기 32 | for point_x, point_y in point_list: 33 | x, y = abs(max_y - point_y), abs(min_x - point_x) 34 | answer[x][y] = '*' 35 | 36 | answer = [str(''.join(a)) for a in answer] 37 | return answer 38 | -------------------------------------------------------------------------------- /Programmers/eugene/39_week/삼각 달팽이.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | snail = [[0 for _ in range(i)] for i in range(1, n+1) ] 3 | 4 | num, x, y = 0, -1, 0 5 | dx = [1, 0, -1] 6 | dy = [0, 1, -1] 7 | 8 | for nn in range(n): 9 | i = nn%3 10 | for k in range(n-nn): 11 | num += 1 12 | x = x+dx[i] 13 | y = y+dy[i] 14 | snail[x][y] = num 15 | 16 | return sum(snail, []) 17 | -------------------------------------------------------------------------------- /Programmers/eugene/40_week/빛의 경로 사이클.py: -------------------------------------------------------------------------------- 1 | def cycle(x, y, d, grid): 2 | cnt = 0 3 | end = (x, y, d) 4 | visited[x][y][d] = True 5 | 6 | dx = [0, 1, 0, -1] 7 | dy = [1, 0, -1, 0] 8 | nx, ny, nd = x, y, d 9 | while True: 10 | # 좌표 갱신 nx, ny 11 | nx = (nx+dx[nd]) % len(grid) 12 | ny = (ny+dy[nd]) % len(grid[0]) 13 | 14 | cnt += 1 15 | if grid[nx][ny] == 'R': 16 | nd = (nd+1)%4 17 | elif grid[nx][ny] == 'L': 18 | nd = (nd-1)%4 19 | 20 | #종료조건 : 최초의 시작점과 방향이 모두 일치하면 21 | if visited[nx][ny][nd]: 22 | if x == nx and y == ny and d == nd: 23 | return cnt 24 | else: 25 | return 0 26 | #사이클이 생기지 않는 걸 확신할 수 있는 조건을 모르겠다. 27 | visited[nx][ny][nd] = True 28 | 29 | def solution(grid): 30 | global visited 31 | answer = [] 32 | visited = [[[False]*4 for _ in range(len(grid[0]))] for _ in range(len(grid))] 33 | 34 | for row in range(len(grid)): 35 | for col in range(len(grid[0])): 36 | for d in range(4): #direction 37 | if not visited[row][col][d]: 38 | dist = cycle(row, col, d, grid) 39 | if dist: 40 | answer.append(dist) 41 | answer.sort() 42 | return answer 43 | -------------------------------------------------------------------------------- /Programmers/eugene/README.md: -------------------------------------------------------------------------------- 1 | [풀이 과정 보러가기-EugLog.Dev](https://www.notion.so/1712850/Programmers-6696067137834967b75f66ace3afc504) 2 | -------------------------------------------------------------------------------- /Programmers/eugene/binary_search/입국심사.py: -------------------------------------------------------------------------------- 1 | def solution(n, times): 2 | left=n*min(times)//len(times) 3 | right=n*max(times)//len(times) 4 | 5 | while(left<=right): 6 | people=0 7 | mid=(left+right)//2 8 | for i in times: 9 | people+=mid//i 10 | 11 | if people >= n: 12 | right=mid-1 13 | else: 14 | left=mid+1 15 | return right -------------------------------------------------------------------------------- /Programmers/eugene/binary_search/징검다리.py: -------------------------------------------------------------------------------- 1 | def solution(distance, rocks, n): 2 | left, right=0, distance 3 | 4 | rocks.sort() 5 | rocks.append(distance) 6 | 7 | while(left<=right): 8 | brk_rocks, stay_rock = 0,0 9 | mid=(left+right)//2 10 | for rock in rocks: 11 | if (rock - stay_rock >= mid): 12 | stay_rock = rock 13 | else : 14 | brk_rocks +=1 15 | 16 | if brk_rocks > n: 17 | right=mid-1 18 | else: 19 | left=mid+1 20 | return right -------------------------------------------------------------------------------- /Programmers/eugene/brute_force/소수 찾기.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def prime_tf(number): #소수 판별 4 | return all([(number%n) for n in range(2, int(number**0.5)+1)]) and number>1 5 | 6 | def solution(numbers): 7 | answer = 0 8 | numbers=list(numbers) 9 | prime_list=[] 10 | 11 | for i in range(1, len(numbers)+1): 12 | prime_list += list(map(int, map(''.join,permutations(numbers, i)))) #모든 조합을 prime_list에 추가 13 | prime_list=set(prime_list) #중복 제외 14 | 15 | for j in prime_list : 16 | if prime_tf(j) : #True 17 | answer+=1 18 | return answer 19 | -------------------------------------------------------------------------------- /Programmers/eugene/brute_force/카펫.py: -------------------------------------------------------------------------------- 1 | def solution(brown, yellow): 2 | answer = [] 3 | half_round = brown//2 4 | for i in range(3, half_round): 5 | if (half_round-i)*(i-2) == yellow: 6 | return [half_round+2-i,i] 7 | -------------------------------------------------------------------------------- /Programmers/eugene/dfs_bfs/네트워크.py: -------------------------------------------------------------------------------- 1 | def solution(n, computers): 2 | answer = 0 3 | visited = [False]*n 4 | 5 | for i in range(n): 6 | if visited[i] == False : #방문하지 않은 컴퓨터면 탐색 7 | dfs(computers, i, visited) #dfs함수 실행 8 | answer+=1 #더 이상 연결된 네트워크가 없으면, 위 dfs를 빠져나오고 네트워크를 추가한다. 9 | return answer 10 | 11 | def dfs(graph, v, visited): 12 | visited[v]=True 13 | 14 | for i in range(len(graph)): 15 | if graph[v][i] and not visited[i]: #현재 graph에서 연결되어 있고, 방문하지 않은 노드 16 | dfs(graph, i ,visited) #재귀함수 17 | -------------------------------------------------------------------------------- /Programmers/eugene/dfs_bfs/단어 변환.py: -------------------------------------------------------------------------------- 1 | def solution(begin, target, words): 2 | answer = 0 3 | stacks=[begin] 4 | if target not in words: 5 | return 0 6 | 7 | visited = [0 for i in words] 8 | 9 | while stacks: 10 | stack = stacks.pop() 11 | 12 | for w in range(len(words)): 13 | # 조건 1. 한 개의 알파벳만 다른 경우 14 | if len([i for i in range(0,len(words[w])) if words[w][i]!=stack[i]]) == 1 and not visited[w]: 15 | visited[w] = 1 16 | stacks.append(words[w]) 17 | 18 | if words[w]== target: 19 | answer+=1 20 | return answer 21 | answer +=1 22 | 23 | if stack != target: #모든 스택을 돌고 나서도 target과 같지 않다면 0을 출력 24 | return 0 -------------------------------------------------------------------------------- /Programmers/eugene/dfs_bfs/타겟 넘버.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(numbers, target): 4 | 5 | queue = deque([0]) 6 | for n in numbers : 7 | sub_q = [] 8 | for i in queue : 9 | sub_q.append(i+n) 10 | sub_q.append(i-n) 11 | queue = sub_q 12 | return queue.count(target) 13 | -------------------------------------------------------------------------------- /Programmers/eugene/dynamic_programming/N으로 표현.py: -------------------------------------------------------------------------------- 1 | def solution(N, number): 2 | if N == number: return 1 3 | 4 | DP = [{}, { N }] 5 | for i in range(2, 9): 6 | temp = { int(str(N) * i) } 7 | 8 | for j in range(1, i//2 + 1): 9 | for x in DP[j]: 10 | for y in DP[i - j]: 11 | temp.add(x + y) 12 | temp.add(x - y) 13 | temp.add(x - y) 14 | temp.add(x * y) 15 | if y: temp.add(x // y) 16 | if x: temp.add(y // x) 17 | 18 | if number in temp: return i 19 | DP.append(temp) 20 | return -1 21 | -------------------------------------------------------------------------------- /Programmers/eugene/dynamic_programming/등굣길.py: -------------------------------------------------------------------------------- 1 | def solution(m, n, puddles): 2 | location=[[1,1]] 3 | arr = [[0] * (n+1) for _ in range(m+1)] 4 | arr[1][1] = 1 5 | for x in range(1,m+1): 6 | for y in range(1, n+1): 7 | if [x,y] in puddles: 8 | continue 9 | if [x,y]==[1,1]: #출발점에 10 | continue 11 | arr[x][y] = arr[x-1][y] + arr[x][y-1] 12 | return arr[-1][-1] % 1000000007 13 | -------------------------------------------------------------------------------- /Programmers/eugene/dynamic_programming/정수 삼각형.py: -------------------------------------------------------------------------------- 1 | def solution(triangle): 2 | for i in range (1,len(triangle)): #전체 3 | for j in range(i+1): #한 줄씩 4 | if (j==0): #줄의 맨 처음 5 | triangle[i][j] += triangle[i-1][0] 6 | elif j==i : #줄의 맨 끝 7 | triangle[i][j] += triangle[i-1][-1] 8 | else : #중간 9 | triangle[i][j] += max(triangle[i - 1][j - 1], triangle[i - 1][j]) 10 | #전체 다 돌고, 마지막 temp에서 가장 큰 값 리턴 11 | return max(triangle[-1]) 12 | -------------------------------------------------------------------------------- /Programmers/eugene/graph/가장 먼 노드.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(n, edge): 4 | m=len(edge) 5 | graph=[[] for _ in range(n+1)] 6 | for i in range(m): 7 | a,b = edge[i] 8 | graph[a].append(b) 9 | graph[b].append(a) 10 | distance = [-1]*(n+1) 11 | distance[1] = 0 12 | q=deque([1]) 13 | while q: 14 | now=q.popleft() 15 | for next_node in graph[now]: 16 | if distance[next_node]==-1: 17 | distance[next_node] = distance[now]+1 18 | q.append(next_node) 19 | 20 | k=max(distance) 21 | cnt=0 22 | for i in range(1,n+1): 23 | if distance[i] ==k: 24 | cnt+=1 25 | 26 | return cnt 27 | -------------------------------------------------------------------------------- /Programmers/eugene/graph/방의 개수.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | def solution(arrows): 4 | 5 | move = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)] 6 | now = (0,0) 7 | 8 | visited = collections.defaultdict(int) #노드 방문 체크 9 | visited_dir = collections.defaultdict(int) #노드 간 경로 방문 체크 10 | queue = collections.deque([now]) 11 | 12 | for arr in arrows: 13 | for _ in range(2): 14 | buf = (now[0]+move[arr][0], now[1]+move[arr][1]) 15 | queue.append(buf) 16 | now=buf 17 | 18 | now = queue.popleft() 19 | visited[now] = 1 20 | cnt=0 21 | 22 | while queue: 23 | next = queue.popleft() 24 | if visited[next] == 1: 25 | if visited_dir[(now, next)] == 0: 26 | cnt += 1 27 | else: 28 | visited[next] = 1 29 | 30 | visited_dir[(now, next)] = 1 31 | visited_dir[(next, now)] = 1 32 | now = next 33 | 34 | return cnt 35 | -------------------------------------------------------------------------------- /Programmers/eugene/graph/순위.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(n, results): 4 | m=len(results) 5 | graph_lower = [[] for _ in range(n+1)] 6 | graph_upper = [[] for _ in range(n+1)] 7 | for i in range(m): 8 | a,b = results[i] 9 | graph_lower[a].append(b) 10 | graph_upper[b].append(a) 11 | 12 | result=[0]*(n) 13 | for i in range(1,n+1): 14 | indegree=[False]*(n+1) 15 | indegree[i] = True #시작 노드 방문 처리 16 | cnt=0 17 | q1,q2=deque([i]),deque([i]) 18 | while q1: 19 | now=q1.popleft() 20 | for next_node in graph_lower[now]: 21 | if indegree[next_node]==False: 22 | indegree[next_node]=True 23 | cnt+=1 24 | q1.append(next_node) 25 | while q2: 26 | now=q2.popleft() 27 | for next_node in graph_upper[now]: 28 | if indegree[next_node]==False: 29 | indegree[next_node]=True 30 | cnt+=1 31 | q2.append(next_node) 32 | 33 | result[i-1]+=cnt 34 | 35 | answer=0 36 | for k in range(n): 37 | if result[k] == n-1: 38 | answer+=1 39 | return answer 40 | -------------------------------------------------------------------------------- /Programmers/eugene/greedy/조이스틱.py: -------------------------------------------------------------------------------- 1 | def solution(name): 2 | answer,i = 0,0 3 | name=list(name) 4 | len_name = len(name) 5 | 6 | while(True): 7 | left, right =1,1 8 | 9 | #알파벳 카운트 : A가 아니면 알파벳 변경을 시도 10 | if name[i] != 'A': 11 | answer+=min(ord(name[i]) - ord('A'), ord('Z')-ord(name[i])+1) 12 | 13 | #변경한 위치는 A로 변경하고, 모든 문자열이 A로 바뀌면 종료. 14 | name[i] = 'A' 15 | if ['A'] * len_name == name: 16 | break 17 | 18 | #커서 이동 카운트 19 | for k in range(1,len_name): 20 | if name[i+k]=="A": right+=1 21 | else : break 22 | 23 | if name[i-k]=="A" : left+=1 24 | else: break 25 | 26 | #left/right 중 더 가까운 방향으로 이동 27 | answer += left if left < right else right 28 | i += -left if left < right else right 29 | return answer 30 | -------------------------------------------------------------------------------- /Programmers/eugene/greedy/큰 수 만들기.py: -------------------------------------------------------------------------------- 1 | def solution(number, k): 2 | stack = [number[0]] 3 | for num in number[1:]: 4 | 5 | while stack and stack[-1]0: 6 | k -= 1 7 | stack.pop() 8 | stack.append(num) 9 | 10 | return ''.join(stack[:len(stack) - k]) 11 | -------------------------------------------------------------------------------- /Programmers/eugene/hash/베스트앨범.py: -------------------------------------------------------------------------------- 1 | def solution(genres, plays): 2 | answer = [] 3 | 4 | category = set(genres) 5 | genre_plays = dict(zip(category, [0]*len(category))) 6 | 7 | for i in range(len(genres)): 8 | genre_plays[genres[i]] += plays[i] 9 | 10 | genre_sort = sorted(genre_plays.items(), key=lambda x:x[1], reverse=True) 11 | 12 | for genre in genre_sort: 13 | temp=[] 14 | for i in range(0, len(genres)): 15 | if genres[i] == genre[0]: 16 | temp.append((i, plays[i])) 17 | 18 | song_sort = list(map(lambda x:x[0],sorted(temp, key=lambda x:x[1], reverse=True))) 19 | answer += song_sort[:2] 20 | 21 | return answer -------------------------------------------------------------------------------- /Programmers/eugene/hash/위장.py: -------------------------------------------------------------------------------- 1 | def solution(clothes): 2 | answer = 1 3 | 4 | clothes= dict(clothes) 5 | category = set(clothes.values()) 6 | 7 | dict_clothes = dict(zip(category, [0]*len(category))) 8 | 9 | for c in clothes.values(): 10 | dict_clothes[c]+=1 11 | 12 | for value in dict_clothes.values(): 13 | answer*= (value+1) 14 | 15 | return answer-1 -------------------------------------------------------------------------------- /Programmers/eugene/hash/전화번호 목록.py: -------------------------------------------------------------------------------- 1 | def solution(phone_book): 2 | #sorted로 정렬하면 phone_book에 있는 원소들은 앞자리가 작은 순서로 정렬된다. 3 | #앞 뒤로 비교하기만 하면 되는 것! 4 | 5 | #sorted를 해주지 않으면, 모든 조합에 대해 살펴봐야 하고 효율성에 적합하지 않다. 6 | phoneBook = sorted(phone_book) 7 | 8 | for pre, phone in zip(phoneBook, phoneBook[1:]): 9 | if phone.startswith(pre): 10 | return False 11 | return True 12 | -------------------------------------------------------------------------------- /Programmers/eugene/heap/더 맵게.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | def solution(scoville, K): 4 | heapq.heapify(scoville) 5 | 6 | i=0 7 | while(True): 8 | if scoville[0] >= K: 9 | return i 10 | 11 | x=heapq.heappop(scoville) 12 | y=heapq.heappop(scoville) 13 | heapq.heappush(scoville, x+y*2) 14 | i+=1 15 | 16 | if (len(scoville)==1): 17 | if scoville[0]= I_cnt): 16 | min_heap, max_heap=[],[] 17 | I_cnt, D_cnt = 0,0 18 | continue 19 | 20 | if(oper =="D 1") : 21 | heapq.heappop(max_heap) 22 | else : 23 | heapq.heappop(min_heap) 24 | 25 | if (D_cnt == I_cnt): 26 | print(min_heap, max_heap) 27 | return [0,0] 28 | else: 29 | return [max_heap[0][1], min_heap[0]] 30 | -------------------------------------------------------------------------------- /Programmers/eugene/sort/H-Index.py: -------------------------------------------------------------------------------- 1 | def solution(citations): 2 | len_ci = len(citations) 3 | citations.sort(reverse=True) 4 | 5 | for h in range(citations[0],-1,-1): 6 | if(h <= len_ci and h <= citations[h-1]): #h번 이상 인용된 논문이 h개 이상이다. 7 | return h 8 | return 0 -------------------------------------------------------------------------------- /Programmers/eugene/sort/K번째수.py: -------------------------------------------------------------------------------- 1 | def solution(array, commands): 2 | return [sorted(array[i-1 :j])[k-1] for i,j,k in commands] -------------------------------------------------------------------------------- /Programmers/eugene/sort/가장 큰 수.py: -------------------------------------------------------------------------------- 1 | def solution(numbers): 2 | 3 | numbers=list(map(str, numbers)) 4 | numbers.sort(key=lambda x:x*3, reverse=True) 5 | return str(int(''.join(numbers))) -------------------------------------------------------------------------------- /Programmers/eugene/stack_queue/주식가격.py: -------------------------------------------------------------------------------- 1 | def solution(prices): 2 | len_p=len(prices) 3 | answer = [ i for i in range (len_p - 1, -1, -1)] 4 | 5 | stack = [0] 6 | for i in range(1, len_p): 7 | while stack and prices[i] < prices[stack[-1]]: 8 | j = stack.pop() 9 | answer[j] = i - j 10 | stack.append(i) 11 | 12 | return answer 13 | -------------------------------------------------------------------------------- /Programmers/eugene/stack_queue/프린터.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(priorities, location): 4 | answer = 0 5 | 6 | queue=deque(priorities) 7 | while(queue): 8 | if location == 0 : #location이 맨 앞으로 왔을 경우 9 | if queue[0] < max(queue): #더 큰 중요도가 뒤에 있으면 10 | queue.append(queue.popleft()) 11 | location = len(queue)-1 12 | else : #loca에 있는 문서의 중요도가 가장 높으면 출력하고 순서 리턴 13 | return answer+1 14 | 15 | else : #아직 loca차례가 오지 않았을 때 16 | location -=1 17 | if queue[0] < max(queue): 18 | queue.append(queue.popleft()) 19 | 20 | else : 21 | queue.popleft() 22 | answer+=1 23 | return answer 24 | -------------------------------------------------------------------------------- /Programmers/jiwoo/2018_kakao_blind/뉴스클러스터링.py: -------------------------------------------------------------------------------- 1 | from math import floor 2 | 3 | def solution(str1, str2): 4 | str1 = str1.upper() 5 | str2 = str2.upper() 6 | 7 | str1_list = [] 8 | str2_list = [] 9 | 10 | for i in range(len(str1)-1): 11 | if str1[i:i+2].isalpha(): 12 | str1_list.append(str1[i:i+2]) 13 | 14 | for i in range(len(str2)-1): 15 | if str2[i:i+2].isalpha(): 16 | str2_list.append(str2[i:i+2]) 17 | 18 | intersection = set(str1_list) & set(str2_list) 19 | union = set(str1_list) | set(str2_list) 20 | 21 | if not union: 22 | return 65536 23 | 24 | intersection_count = sum([min(str1_list.count(e), str2_list.count(e)) for e in intersection]) 25 | union_count = sum([max(str1_list.count(e), str2_list.count(e)) for e in union]) 26 | 27 | return floor((intersection_count / union_count) * 65536) -------------------------------------------------------------------------------- /Programmers/jiwoo/2018_kakao_blind/캐시.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(cacheSize, cities): 4 | times = 0 5 | buffer = deque() 6 | 7 | if not cacheSize: 8 | return len(cities)*5 9 | for city in cities: 10 | city = city.upper() 11 | if city in buffer: 12 | times += 1 13 | buffer.remove(city) 14 | else: 15 | times += 5 16 | if len(buffer) >= cacheSize: 17 | buffer.popleft() 18 | buffer.append(city) 19 | return times -------------------------------------------------------------------------------- /Programmers/jiwoo/2018_kakao_blind/프렌즈4블록.py: -------------------------------------------------------------------------------- 1 | def solution(m, n, board): 2 | answer = 0 3 | for i in range(len(board)): 4 | board[i] = list(board[i]) 5 | while True: 6 | remove = [[0] * n for _ in range(m)] 7 | for i in range(m-1): 8 | for j in range(n-1): 9 | if board[i][j] != 0 and board[i][j] == board[i][j+1] == board[i+1][j] == board[i+1][j+1]: 10 | remove[i][j], remove[i][j+1], remove[i+1][j], remove[i+1][j+1] = 1, 1, 1, 1 11 | count = 0 12 | for i in range(m): 13 | count += sum(remove[i]) 14 | answer += count 15 | if count == 0: 16 | break 17 | for i in range(m-1, -1, -1): 18 | for j in range(n): 19 | if remove[i][j] == 1: 20 | x = i-1 21 | while x >= 0 and remove[x][j] == 1: 22 | x -= 1 23 | if x < 0: 24 | board[i][j] = 0 25 | else: 26 | board[i][j] = board[x][j] 27 | remove[x][j] = 1 28 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/2019_kakao_blind/실패율.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | def solution(N, stages): 4 | stage_dict = defaultdict(int) 5 | for stage in stages: 6 | stage_dict[stage] += 1 7 | 8 | result = {} 9 | users = len(stages) 10 | for i in range(1, N+1): 11 | users -= stage_dict[i-1] 12 | result[i] = stage_dict[i]/users if users else 0 13 | return sorted(result, key=lambda x: result[x], reverse = True) -------------------------------------------------------------------------------- /Programmers/jiwoo/2019_kakao_blind/오픈채팅방.py: -------------------------------------------------------------------------------- 1 | def solution(records): 2 | result = [] 3 | user_nick = {} 4 | 5 | for record in records: 6 | record_split = record.split() 7 | command = record_split[0] 8 | if command == "Enter" or command == "Change": 9 | user_nick[record_split[1]] = record_split[2] 10 | 11 | for record in records: 12 | record_split = record.split() 13 | command = record_split[0] 14 | if command == "Enter": 15 | result.append(user_nick[record_split[1]] + "님이 들어왔습니다.") 16 | elif command == "Leave": 17 | result.append(user_nick[record_split[1]] + "님이 나갔습니다.") 18 | return result -------------------------------------------------------------------------------- /Programmers/jiwoo/2019_kakao_blind/후보키.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | 3 | def solution(relations): 4 | row = len(relations) 5 | col = len(relations[0]) 6 | 7 | candidates = [[] for i in range(col+1)] 8 | 9 | min_key = [] 10 | for i in range(1, col+1): 11 | candidates[i] = combinations(range(col), i) 12 | for candidate in candidates[i]: 13 | not_key = 0 14 | unique = [[] for _ in range(row)] 15 | # 유효성 검사 16 | for k in candidate: 17 | for r_ in range(row): 18 | unique[r_].append(relations[r_][k]) 19 | for i in unique: 20 | if unique.count(i) >= 2: 21 | not_key = 1 22 | break 23 | # 최소성 검사 24 | if not_key == 0: 25 | if len(candidate) == 1: 26 | min_key.append(candidate) 27 | else : 28 | for r_ in min_key: 29 | if set(r_).issubset(set(candidate)): 30 | break 31 | else: 32 | min_key.append(candidate) 33 | return len(min_key) -------------------------------------------------------------------------------- /Programmers/jiwoo/2020_kakao_blind/괄호변환.py: -------------------------------------------------------------------------------- 1 | def slice_check(p): 2 | count = 0 3 | isOK = True 4 | for i in range(len(p)): 5 | if p[i] == '(': 6 | count += 1 7 | else: 8 | count -= 1 9 | if count < 0: 10 | isOK = False 11 | if not count: 12 | return p[:i+1], p[i+1:], isOK 13 | 14 | def solution(p): 15 | answer = '' 16 | if not p: return '' 17 | 18 | u, v, isOK = slice_check(p) 19 | 20 | if isOK: 21 | return u + solution(v) 22 | else: 23 | reverse = ''.join([')' if u_ == '(' else '(' for u_ in u[1:-1]]) 24 | answer += '(' + solution(v) + ')' + reverse 25 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/2020_kakao_blind/문자열압축.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | answer = len(s) 3 | zip_str = '' 4 | 5 | if answer == 1: 6 | return 1 7 | 8 | for slice_count in range(1, len(s)//2+1): 9 | zip_count = 1 10 | temp = s[:slice_count] 11 | for i in range(0, len(s), slice_count): 12 | if s[i:i+slice_count] == temp: 13 | zip_count += 1 14 | else: 15 | if zip_count == 1: 16 | zip_count = '' 17 | zip_str += str(zip_count) + temp 18 | temp = s[i:i+slice_count] 19 | zip_count = 1 20 | if zip_count == 1: 21 | zip_count = '' 22 | zip_str += str(zip_count) + temp 23 | 24 | if answer > len(zip_str): 25 | answer = len(zip_str) 26 | zip_str = '' 27 | 28 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/2020_kakao_blind/자물쇠와열쇠.py: -------------------------------------------------------------------------------- 1 | def rotate(key, M): 2 | rota_key = [[0] * M for _ in range(M)] 3 | 4 | for i in range(M): 5 | for j in range(M): 6 | rota_key[j][M-1-i] = key[i][j] 7 | return rota_key 8 | 9 | def check(key, lock, exp_size, start_x, start_y, start, end): 10 | expend_ = [[0] * exp_size for _ in range(exp_size)] 11 | 12 | # expend_에 key 추가 13 | for i in range(start+1): 14 | for j in range(start+1): 15 | expend_[start_x+i][start_y+j] += key[i][j] 16 | 17 | for i in range(start, end): 18 | for j in range(start, end): 19 | expend_[i][j] += lock[i-start][j-start] 20 | if expend_[i][j] != 1: 21 | return False 22 | return True 23 | 24 | def solution(key, lock): 25 | start = len(key) - 1 26 | end = start + len(lock) 27 | exp_size = len(lock) + start*2 28 | 29 | for _ in range(4): 30 | for i in range(end): 31 | for j in range(end): 32 | if check(key, lock, exp_size, i, j, start, end): 33 | return True 34 | key = rotate(key, start+1) 35 | 36 | return False -------------------------------------------------------------------------------- /Programmers/jiwoo/2021_kakao_blind/메뉴리뉴얼.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from itertools import combinations 3 | 4 | def solution(orders, course): 5 | result = [] 6 | 7 | for course_size in course: 8 | order_combinations = [] 9 | for order in orders: 10 | order_combinations += combinations(sorted(order), course_size) 11 | 12 | most_ordered = Counter(order_combinations).most_common() 13 | result += [menu for menu, count in most_ordered if count > 1 and count == most_ordered[0][1]] 14 | 15 | return [''.join(menu) for menu in sorted(result)] -------------------------------------------------------------------------------- /Programmers/jiwoo/2021_kakao_blind/순위검색.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from itertools import combinations 3 | 4 | def solution(infos, queries): 5 | answer = [] 6 | info_dic = defaultdict(list) 7 | for info in infos: 8 | info = info.split() 9 | info_ = info[:-1] 10 | info_score = int(info[-1]) 11 | 12 | # 가능한 info 조합 생성하여, key, score로 저장 13 | for i in range(5): 14 | for c in combinations(info_, i): 15 | temp_key = ''.join(c) 16 | info_dic[temp_key].append(info_score) 17 | 18 | # score 오름차순 정렬 19 | for key in info_dic.keys(): 20 | info_dic[key].sort() 21 | 22 | for query in queries: 23 | query = query.split() 24 | query_score = int(query[-1]) 25 | query_ = query[:-1] 26 | 27 | for i in range(3): 28 | query_.remove('and') 29 | while '-' in query_: 30 | query_.remove('-') 31 | query_ = ''.join(query_) 32 | 33 | if query_ in info_dic: 34 | scores = info_dic[query_] 35 | if len(scores) > 0: 36 | start, end = 0, len(scores) 37 | while end > start: 38 | mid = (start+end) // 2 39 | if scores[mid] >= query_score: 40 | end = mid 41 | else: 42 | start = mid+1 43 | answer.append(len(scores)-start) 44 | else: 45 | answer.append(0) 46 | 47 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/2021_kakao_blind/신규아이디추천.py: -------------------------------------------------------------------------------- 1 | def solution(new_id): 2 | #1 3 | new_id = new_id.lower() 4 | #2 5 | answer = '' 6 | for id_char in new_id: 7 | if id_char.isalnum() or id_char in '-_.': 8 | answer += id_char 9 | #3 10 | while '..' in answer: 11 | answer = answer.replace('..', '.') 12 | #4 13 | if answer[0] == '.' and len(answer) > 1: 14 | answer = answer[1:] 15 | if answer[-1] == '.': 16 | answer = answer[:-1] 17 | #5 18 | if not answer: 19 | answer = 'a' 20 | #6 21 | answer = answer[:15] 22 | if answer[-1] == '.': 23 | answer = answer[:-1] 24 | #7 25 | if len(answer) <= 2: 26 | answer += answer[-1]*(3-len(answer)) 27 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/24_week/숫자 문자열과 영단어.py: -------------------------------------------------------------------------------- 1 | def solution(string): 2 | answer = '' 3 | word = '' 4 | num_numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 5 | num_strings = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] 6 | 7 | for s in string: 8 | if s.isdigit(): 9 | answer += s 10 | elif s.isalpha(): 11 | word += s 12 | if word in num_strings: 13 | index = num_strings.index(word) 14 | answer += str(num_numbers[index]) 15 | word = '' 16 | 17 | return int(answer) -------------------------------------------------------------------------------- /Programmers/jiwoo/25_week/거리두기 확인하기.py: -------------------------------------------------------------------------------- 1 | def solution(places): 2 | answer = [] 3 | 4 | for place in places: 5 | isRight = True 6 | test_place = [] 7 | 8 | for n in place: 9 | test_place.append(list(n)) 10 | 11 | for i in range(5): 12 | for j in range(5): 13 | if test_place[i][j] == "P": 14 | if i + 1 < 5: 15 | if test_place[i + 1][j] == "P": 16 | isRight = False 17 | break 18 | if test_place[i + 1][j] == "O": 19 | if i + 2 < 5: 20 | if test_place[i + 2][j] == "P": 21 | isRight = False 22 | break 23 | if j + 1 < 5: 24 | if test_place[i][j + 1] == "P": 25 | isRight = False 26 | break 27 | if test_place[i][j + 1] == "O": 28 | if j + 2 < 5: 29 | if test_place[i][j + 2] == "P": 30 | isRight = False 31 | break 32 | if i + 1 < 5 and j + 1 < 5: 33 | if test_place[i + 1][j + 1] == "P" and (test_place[i + 1][j] == "O" or test_place[i][j + 1] == "O"): 34 | isRight = False 35 | break 36 | 37 | if i + 1 < 5 and j - 1 >= 0: 38 | if test_place[i + 1][j - 1] == "P" and (test_place[i + 1][j] == "O" or test_place[i][j - 1] == "O"): 39 | isRight = False 40 | break 41 | 42 | if isRight: 43 | answer.append(1) 44 | else: 45 | answer.append(0) 46 | 47 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/26_week/수식 최대화.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def operation(num1, num2, operator): 4 | if operator == '+': 5 | return num1 + num2 6 | if operator == '-': 7 | return num1 - num2 8 | if operator == '*': 9 | return num1 * num2 10 | 11 | def calculate(exp, operator): 12 | array = [] 13 | temp = "" 14 | for i in exp: 15 | if i.isdigit() == True: 16 | temp += i 17 | else: 18 | array.append(int(temp)) 19 | array.append(i) 20 | temp = "" 21 | array.append(int(temp)) 22 | 23 | for op in operator: 24 | stack = [] 25 | while len(array) != 0: 26 | temp = array.pop(0) 27 | if temp == op: 28 | stack.append(operation(stack.pop(), array.pop(0), op)) 29 | else: 30 | stack.append(temp) 31 | array = stack 32 | 33 | return abs(int(array[0])) 34 | 35 | def solution(expression): 36 | operators = ['+', '-', '*'] 37 | operators = list(permutations(operators, 3)) 38 | result = [] 39 | for i in operators: 40 | result.append(calculate(expression, i)) 41 | return max(result) -------------------------------------------------------------------------------- /Programmers/jiwoo/27_week/튜플.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | answer = [] 3 | s = s[2:-2] 4 | s = s.split("},{") 5 | s.sort(key = len) 6 | for i in s: 7 | i = i.split(",") 8 | for j in i: 9 | if int(j) not in answer: 10 | answer.append(int(j)) 11 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/28_week/파일명정렬.py: -------------------------------------------------------------------------------- 1 | def solution(files): 2 | answer = [] 3 | 4 | for file in files: 5 | head, number, tail = '', '', '' 6 | 7 | is_number = False 8 | for i in range(len(file)): 9 | if file[i].isdigit(): 10 | number += file[i] 11 | is_number = True 12 | elif not is_number: 13 | head += file[i] 14 | else: 15 | tail = file[i:] 16 | break 17 | answer.append((head, number, tail)) 18 | 19 | answer.sort(key=lambda x: (x[0].upper(), int(x[1]))) 20 | 21 | return [''.join(parsing) for parsing in answer] -------------------------------------------------------------------------------- /Programmers/jiwoo/29_week/n진수게임.py: -------------------------------------------------------------------------------- 1 | def tenToN(num, n): 2 | nums = "0123456789ABCDEF" 3 | 4 | a = num // n 5 | b = num % n 6 | 7 | if a == 0: 8 | return nums[b] 9 | else: 10 | return tenToN(a, n) + nums[b] 11 | 12 | def solution(n, t, m, p): 13 | answer = '' 14 | 15 | num = 0 16 | while len(answer) < m*t: 17 | answer += tenToN(num, n) 18 | num += 1 19 | return answer[p-1::m][:t] -------------------------------------------------------------------------------- /Programmers/jiwoo/30_week/주차요금계산.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def solution(fees, records): 4 | temp = [] 5 | cars_times = dict() 6 | 7 | for i in range(len(records)): 8 | record_split = records[i].split(' ') 9 | temp.append(record_split) 10 | cars_times[record_split[1]] = 0 11 | temp[i][0] = [int(record_split[0][:2]), int(record_split[0][3:5])] 12 | 13 | for i in range(len(temp)): 14 | out = True 15 | if temp[i][2] != 'x': 16 | for j in range(i+1, len(temp)): 17 | if temp[j][2] != 'x': 18 | if temp[i][1] == temp[j][1]: 19 | minute = (temp[j][0][0] - temp[i][0][0]) * 60 + (temp[j][0][1] - temp[i][0][1]) 20 | temp[j][2], temp[i][2]='x', 'x' 21 | cars_times[temp[i][1]] += minute 22 | out = False 23 | break 24 | if out: 25 | minute = (23 - temp[i][0][0]) * 60 + (59 - temp[i][0][1]) 26 | cars_times[temp[i][1]] += minute 27 | 28 | for i, k in enumerate(cars_times): 29 | if cars_times[k] < fees[0]: 30 | cars_times[k] = fees[1] 31 | else: 32 | cars_times[k] = math.ceil((cars_times[k] - fees[0]) / fees[2]) * fees[3] + fees[1] 33 | return [cars_times[i] for i in sorted(cars_times)] -------------------------------------------------------------------------------- /Programmers/jiwoo/31_week/k진수에서 소수 개수 구하기.py: -------------------------------------------------------------------------------- 1 | def solution(n, k): 2 | str_num = '' 3 | 4 | while n: 5 | str_num += str(n % k) 6 | n = n // k 7 | 8 | str_num = str_num[::-1] 9 | 10 | str_num_split = str_num.split('0') 11 | 12 | new_list = [] 13 | for num in str_num_split: 14 | if len(num) > 0: 15 | new_list.append(num) 16 | str_num_split = list(map(int, new_list)) 17 | 18 | count = 0 19 | for i in str_num_split: 20 | prime = True 21 | if i < 2: 22 | continue 23 | for j in range(2, int(i**0.5)+1): 24 | if i % j == 0: 25 | prime = False 26 | break 27 | if prime: 28 | count += 1 29 | 30 | return count -------------------------------------------------------------------------------- /Programmers/jiwoo/32_week/멀쩡한사각형.py: -------------------------------------------------------------------------------- 1 | def solution(w, h): 2 | for i in range(min(w, h), 0, -1): 3 | if w % i == 0 and h % i == 0: 4 | return w * h - (w + h - i) -------------------------------------------------------------------------------- /Programmers/jiwoo/33_week/불량사용자.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def solution(user_id_s, banned_id_s): 4 | user_cases = list(permutations(user_id_s, len(banned_id_s))) 5 | answer = [] 6 | 7 | for user_case in user_cases: 8 | if not check_banned_id(user_case, banned_id_s): 9 | continue 10 | else: 11 | user_case = set(user_case) 12 | if user_case not in answer: 13 | answer.append(user_case) 14 | 15 | return len(answer) 16 | 17 | def check_banned_id(user_case, banned_id_s): 18 | for i in range(len(banned_id_s)): 19 | if len(user_case[i]) != len(banned_id_s[i]): 20 | return False 21 | 22 | for j in range(len(user_case[i])): 23 | if banned_id_s[i][j] == "*": 24 | continue 25 | if banned_id_s[i][j] != user_case[i][j]: 26 | return False 27 | return True -------------------------------------------------------------------------------- /Programmers/jiwoo/34_week/방금그곡.py: -------------------------------------------------------------------------------- 1 | def solution(m, musicinfos): 2 | correct_music_title = '' 3 | check_melody = change_melody(m) 4 | 5 | max_time = 0 6 | for music_info in musicinfos: 7 | music_info = music_info.split(',') 8 | time = calculate_time(music_info) 9 | melody = change_melody(music_info[3]) 10 | new_melody = melody * (time // len(melody)) + melody[0:time % len(melody)] 11 | if check_melody in new_melody: 12 | if max_time < time: 13 | max_time = time 14 | correct_music_title = music_info[2] 15 | 16 | if correct_music_title == '': 17 | return "(None)" 18 | else: 19 | return correct_music_title 20 | 21 | def change_melody(melody): 22 | melody = melody.replace('C#', 'H') 23 | melody = melody.replace('D#', 'I') 24 | melody = melody.replace('F#', 'J') 25 | melody = melody.replace('G#', 'K') 26 | melody = melody.replace('A#', 'L') 27 | return melody 28 | 29 | def calculate_time(music_info): 30 | start = music_info[0] 31 | end = music_info[1] 32 | 33 | hour = int(end.split(':')[0]) - int(start.split(':')[0]) 34 | minute = int(end.split(':')[1]) - int(start.split(':')[1]) 35 | 36 | if hour == 0: 37 | return minute 38 | else: 39 | return 60 * hour + minute -------------------------------------------------------------------------------- /Programmers/jiwoo/35_week/모음사전.py: -------------------------------------------------------------------------------- 1 | def solution(word): 2 | word_list = [] 3 | 4 | word_list = make_word(0, word_list, "") 5 | 6 | return word_list.index(word) + 1 7 | 8 | def make_word(count, word_list, new_word): 9 | if count == 5: 10 | return 11 | 12 | words = "AEIOU" 13 | 14 | for i in range(len(words)): 15 | word_list.append(new_word + words[i]) 16 | make_word(count + 1, word_list, new_word + words[i]) 17 | 18 | return word_list -------------------------------------------------------------------------------- /Programmers/jiwoo/36_week/n^2배열자르기.py: -------------------------------------------------------------------------------- 1 | def solution(n, left, right): 2 | answer = [] 3 | 4 | for i in range(int(left), int(right)+1): 5 | x = i // n 6 | y = i % n 7 | if x < y: 8 | x, y = y, x 9 | answer.append(x+1) 10 | 11 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/37_week/피로도.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def solution(k, dungeons): 4 | dungeons_count = len(dungeons) 5 | answer = 0 6 | 7 | for cases in permutations(dungeons, dungeons_count): 8 | now = k 9 | count = 0 10 | for min_tired, use_tired in cases: 11 | if now >= min_tired: 12 | now -= use_tired 13 | count += 1 14 | if count > answer: 15 | answer = count 16 | 17 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/39_week/삼각달팽이.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | answer = [] 3 | triangle = [[0] * n for _ in range(n)] 4 | 5 | x, y = -1, 0 6 | number = 1 7 | 8 | for i in range(n): 9 | for j in range(i, n): 10 | if i % 3 == 0: 11 | x += 1 12 | elif i % 3 == 1: 13 | y += 1 14 | elif i % 3 == 2: 15 | x -= 1 16 | y -= 1 17 | triangle[x][y] = number 18 | number += 1 19 | 20 | for tri in triangle: 21 | for i in tri: 22 | if i != 0: 23 | answer.append(i) 24 | 25 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/README.md: -------------------------------------------------------------------------------- 1 | # 2021-Algorithm-Study-Python 2 | 3 | > 유형별 문제 풀이 4 | 5 | | 주제 | 문제명 | 6 | | --- | ------ | 7 | | 완전 탐색[0] | [소수찾기](https://jjuyaa.tistory.com/125)| 8 | | 완전 탐색[1] | [카펫](https://jjuyaa.tistory.com/127)| 9 | | 스택/큐[0] | [프린터](https://jjuyaa.tistory.com/128)| 10 | | 스택/큐[1] | [주식 가격](https://jjuyaa.tistory.com/129)| 11 | | 깊이/너비 우선 탐색[0] | [네트워크](https://jjuyaa.tistory.com/130)| 12 | | 깊이/너비 우선 탐색[1] | [타켓넘버](https://jjuyaa.tistory.com/131)| 13 | | 해시[0] | [위장](https://jjuyaa.tistory.com/132)| 14 | | 해시[1] | [전화번호목록](https://jjuyaa.tistory.com/133)| 15 | | 해시[2] | [베스트앨범]()| 16 | | 정렬[0] | [K번째수](https://jjuyaa.tistory.com/155)| 17 | | 정렬[1] | [가장큰수](https://jjuyaa.tistory.com/154)| 18 | | 정렬[2] | [H-Index](https://jjuyaa.tistory.com/156)| 19 | | 이분탐색[0] | [징검다리](https://jjuyaa.tistory.com/174)| 20 | | 이분탐색[1] |[입국심사](https://jjuyaa.tistory.com/177)| 21 | | 다이나믹 프로그래밍[0] |[등굣길](https://jjuyaa.tistory.com/178)| 22 | | 다이나믹 프로그래밍[1] |[정수삼각형](https://jjuyaa.tistory.com/179)| 23 | | 그래프[0] |[순위](https://jjuyaa.tistory.com/181)| 24 | | 그래프[1] |[방의 개수](https://jjuyaa.tistory.com/183)| 25 | | 힙 | -- | 26 | | | | 27 | 28 | > 기출 문제 풀이 29 | 30 | | 주제 | 문제명 | 31 | | --- | ---- | 32 | | 2021_카카오[0] | [메뉴리뉴얼](https://jjuyaa.tistory.com/185)| 33 | | 2021_카카오[1] | [순위검색](https://jjuyaa.tistory.com/188)| 34 | | 2020_카카오[0] | [문자열압축](https://jjuyaa.tistory.com/187)| 35 | | 2020_카카오[1] | [괄호변환](https://jjuyaa.tistory.com/189)| 36 | | 2020_카카오[2] | [자물쇠와열쇠](https://jjuyaa.tistory.com/191)| 37 | | 2019_카카오[0] | [오픈채팅방](https://jjuyaa.tistory.com/192)| 38 | | 2019_카카오[1] | [실패율](https://jjuyaa.tistory.com/193)| 39 | | 2019_카카오[2] | [후보키](https://jjuyaa.tistory.com/194)| 40 | | 2018_카카오[0] | [캐시](https://jjuyaa.tistory.com/201)| 41 | | 2018_카카오[1] | [프렌즈4블록](https://jjuyaa.tistory.com/202)| 42 | | 2018_카카오[2] | [뉴스클러스터링](https://jjuyaa.tistory.com/203)| 43 | | | | -------------------------------------------------------------------------------- /Programmers/jiwoo/binary_search/입국심사.py: -------------------------------------------------------------------------------- 1 | def solution(n, times): 2 | answer = 0 3 | 4 | left = 1 5 | right = min(times) * n 6 | 7 | while left <= right: 8 | mid = (left+right) // 2 9 | people = n 10 | 11 | for time in times: 12 | people -= mid // time 13 | if people <= 0: 14 | answer = mid 15 | right = mid - 1 16 | break 17 | if people > 0: 18 | left = mid + 1 19 | 20 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/binary_search/징검다리.py: -------------------------------------------------------------------------------- 1 | def solution(distance, rocks, n): 2 | answer = 0 3 | 4 | rocks.sort() 5 | rocks.append(distance) 6 | 7 | left, right = 0, distance 8 | 9 | while left <= right: 10 | mid = (left+right) // 2 11 | del_rock = now = 0 12 | 13 | for rock in rocks: 14 | dis = rock - now 15 | if dis < mid: 16 | del_rock += 1 17 | else: 18 | now = rock 19 | 20 | if del_rock > n: 21 | right = mid-1 22 | else: 23 | answer = mid 24 | left = mid+1 25 | 26 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/brute_force/소수찾기.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def solution(numbers): 4 | numberAll = [] 5 | for i in range(1, len(numbers)+1): 6 | a = list(permutations(numbers, i)) 7 | for j in range(len(a)): 8 | b = int(''.join(map(str, a[j]))) 9 | if isPrime(b): 10 | numberAll.append(b) 11 | numberAll = list(set(numberAll)) 12 | return len(numberAll) 13 | 14 | def isPrime(n): 15 | if n == 0 or n == 1: 16 | return False 17 | else: 18 | for i in range(2, n**0.5+1): 19 | if n % i == 0: 20 | return False 21 | return True -------------------------------------------------------------------------------- /Programmers/jiwoo/brute_force/카펫.py: -------------------------------------------------------------------------------- 1 | def solution(brown, yellow): 2 | answer = [] 3 | sum = brown+yellow 4 | 5 | for i in range(3, (sum)**0.5+1): 6 | if (sum) % i == 0: 7 | if (sum//i-2)*(i-2) == yellow: 8 | return [sum//i, i] -------------------------------------------------------------------------------- /Programmers/jiwoo/dfs_bfs/네트워크.py: -------------------------------------------------------------------------------- 1 | def bfs(k, graph, visited): 2 | visited[k] = 1 3 | for i in range(len(graph[k])): 4 | if visited[i] == 0 and graph[k][i] == 1: 5 | bfs(i, graph, visited) 6 | 7 | def solution(n, computers): 8 | network = 0 9 | visited = [0] * n 10 | 11 | while 0 in visited: 12 | i = visited.index(0) 13 | if visited[i] == 0: 14 | bfs(i, computers, visited) 15 | network += 1 16 | 17 | return network -------------------------------------------------------------------------------- /Programmers/jiwoo/dfs_bfs/단어변환.py: -------------------------------------------------------------------------------- 1 | def solution(begin, target, words): 2 | answer = 0 3 | queue = [begin] 4 | while True: 5 | temp = [] 6 | for word in queue: 7 | if word == target: 8 | return answer 9 | for index in range(len(words)-1, -1, -1): 10 | word2 = words[index] 11 | difference = sum([x != y for x, y in zip(word, word2)]) 12 | if difference == 1: 13 | temp.append(words.pop(index)) 14 | if not temp: 15 | return 0 16 | queue = temp 17 | answer += 1 -------------------------------------------------------------------------------- /Programmers/jiwoo/dfs_bfs/타켓넘버.py: -------------------------------------------------------------------------------- 1 | def solution(numbers, target): 2 | root = [0] 3 | 4 | for num in numbers: 5 | subTree = [] 6 | for i in root: 7 | subTree.append(i+num) 8 | subTree.append(i-num) 9 | root = subTree 10 | 11 | return root.count(target) -------------------------------------------------------------------------------- /Programmers/jiwoo/dynamic_programming/N으로표현.py: -------------------------------------------------------------------------------- 1 | def solution(N, number): 2 | if N == number: 3 | return 1 4 | 5 | S = [{}, {N}] 6 | 7 | for i in range(2, 9): 8 | temp = {int(str(N) * i)} 9 | for j in range(1, i//2 + 1): 10 | for a in S[j]: 11 | for b in S[i-j]: 12 | temp.add(a+b) 13 | temp.add(a-b) 14 | temp.add(b-a) 15 | temp.add(a*b) 16 | if b: 17 | temp.add(a//b) 18 | if a: 19 | temp.add(b//a) 20 | if number in temp: 21 | return i 22 | S.append(temp) 23 | 24 | return -1 -------------------------------------------------------------------------------- /Programmers/jiwoo/dynamic_programming/등굣길.py: -------------------------------------------------------------------------------- 1 | def solution(m, n, puddles): 2 | memo = [[0]*(n+1) for i in range(m+1)] 3 | 4 | if puddles: 5 | for a, b in puddles: 6 | memo[a][b] = -1 7 | 8 | memo[1][1] = 1 9 | 10 | for j in range(1, m+1): 11 | for k in range(1, n+1): 12 | if j == k == 1: 13 | continue 14 | if memo[j][k] == -1: 15 | memo[j][k] = 0 16 | continue 17 | memo[j][k] = (memo[j][k-1] + memo[j-1][k]) % 1000000007 18 | 19 | return memo[-1][-1] -------------------------------------------------------------------------------- /Programmers/jiwoo/dynamic_programming/정수삼각형.py: -------------------------------------------------------------------------------- 1 | def solution(triangle): 2 | for i in range(1, len(triangle)): 3 | for j in range(i+1): 4 | if j == 0: 5 | triangle[i][j] += triangle[i-1][0] 6 | elif j == i: 7 | triangle[i][j] += triangle[i-1][-1] 8 | else: 9 | a = triangle[i][j] + triangle[i-1][j-1] 10 | b = triangle[i][j] + triangle[i-1][j] 11 | triangle[i][j] = max(a, b) 12 | 13 | return max(triangle[i]) -------------------------------------------------------------------------------- /Programmers/jiwoo/graph/가장먼노드.py: -------------------------------------------------------------------------------- 1 | def solution(n, edges): 2 | graph = [[] for _ in range(n+1)] 3 | distance = [0]*(n+1) 4 | visited = [0]*(n+1) 5 | queue = [1] 6 | visited[1] = 1 7 | for (a,b) in edges: 8 | graph[a].append(b) 9 | graph[b].append(a) 10 | while queue: 11 | i = queue.pop(0) 12 | for j in graph[i]: 13 | if visited[j] == 0: 14 | visited[j] = 1 15 | queue.append(j) 16 | distance[j] = distance[i] + 1 17 | return distance.count(max(distance)) -------------------------------------------------------------------------------- /Programmers/jiwoo/graph/방의개수.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict, deque 2 | 3 | def solution(arrows): 4 | location = [(0, 1), (1, 1), (1, 0), (1, -1), 5 | (0, -1), (-1, -1), (-1, 0), (-1, 1)] 6 | now = (0, 0) 7 | 8 | #visited: 노드 방문여부, visited_direction: 노드 방문경로여부 확인 9 | visited = defaultdict(int) 10 | visited_direction = defaultdict(int) 11 | 12 | #예외처리 위해 두칸씩 이동 13 | queue = deque([now]) 14 | for arrow in arrows: 15 | for _ in range(2): 16 | next = (now[0] + location[arrow][0], now[1] + location[arrow][1]) 17 | queue.append(next) 18 | now = next 19 | 20 | room_count = 0 21 | now = queue.popleft() 22 | visited[now] = 1 23 | 24 | while queue: 25 | next = queue.popleft() 26 | if visited[next] == 1: 27 | if visited_direction[(now, next)] == 0: 28 | room_count += 1 29 | else: 30 | visited[next] = 1 31 | #양쪽 간선 방문 체크 32 | visited_direction[(now, next)] = 1 33 | visited_direction[(next, now)] = 1 34 | now = next 35 | 36 | return room_count -------------------------------------------------------------------------------- /Programmers/jiwoo/graph/순위.py: -------------------------------------------------------------------------------- 1 | def solution(n, results): 2 | count = 0 3 | winners, losers = {}, {} 4 | 5 | for i in range(1, n+1): 6 | winners[i], losers[i] = set(), set() 7 | 8 | for i in range(1, n+1): 9 | for result in results: 10 | if result[0] == i: 11 | winners[i].add(result[1]) 12 | if result[1] == i: 13 | losers[i].add(result[0]) 14 | 15 | for winner in losers[i]: 16 | winners[winner].update(winners[i]) 17 | for loser in winners[i]: 18 | losers[loser].update(losers[i]) 19 | 20 | for i in range(1, n+1): 21 | if len(winners[i]) + len(losers[i]) == n-1: 22 | count += 1 23 | return count -------------------------------------------------------------------------------- /Programmers/jiwoo/hash/베스트앨범.py: -------------------------------------------------------------------------------- 1 | def solution(genres, plays): 2 | answer = [] 3 | 4 | genre_count = {} 5 | for genre, play in zip(genres, plays): 6 | if genre in genre_count.keys(): 7 | genre_count[genre] += play 8 | else: 9 | genre_count[genre] = play 10 | 11 | song_play_count = {} 12 | for i in range(len(genres)): 13 | genre = genres[i] 14 | play = plays[i] 15 | 16 | counts = genre_count[genre] 17 | if genre in song_play_count.keys(): 18 | if len(song_play_count[genre]) >= 2: 19 | song_play_count[genre].append([counts, play, i]) 20 | song_play_count[genre] = sorted(song_play_count[genre], key = lambda x: -x[1])[:2] 21 | else: 22 | song_play_count[genre].append([counts, play, i]) 23 | else: 24 | song_play_count[genre] = [[counts, play, i]] 25 | 26 | song_play_values = sum(song_play_count.values(), []) 27 | song_play_sort = sorted(song_play_values, key=lambda x: (-x[0], -x[1], x[2])) 28 | 29 | return [i[2] for i in song_play_sort] -------------------------------------------------------------------------------- /Programmers/jiwoo/hash/위장.py: -------------------------------------------------------------------------------- 1 | def solution(clothes): 2 | answer = {} 3 | 4 | for i in clothes: 5 | if i[1] in answer: 6 | answer[i[1]] += 1 7 | else: 8 | answer[i[1]] = 2 9 | 10 | count = 1 11 | for i in answer.values(): 12 | count *= i 13 | 14 | return count-1 -------------------------------------------------------------------------------- /Programmers/jiwoo/hash/전화번호목록.py: -------------------------------------------------------------------------------- 1 | def solution(phone_book): 2 | phone_book.sort() 3 | 4 | for i in range(len(phone_book)-1): 5 | if phone_book[i] == phone_book[i+1][:len(phone_book[i])]: 6 | return False 7 | 8 | return True -------------------------------------------------------------------------------- /Programmers/jiwoo/heap/더맵게.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | def solution(scoville, K): 4 | count = 0 5 | 6 | heapq.heapify(scoville) 7 | 8 | while scoville[0] < K: 9 | try: 10 | count += 1 11 | heapq.heappush(scoville, heapq.heappop(scoville) + heapq.heappop(scoville)*2) 12 | except IndexError: 13 | return -1 14 | return count -------------------------------------------------------------------------------- /Programmers/jiwoo/heap/디스크컨트롤러.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | def solution(jobs): 4 | heap = [] 5 | start, time, now, i = -1, 0, 0, 0 6 | 7 | while i < len(jobs): 8 | for j in jobs: 9 | if start < j[0] <= now: 10 | heapq.heappush(heap, [j[1], j[0]]) 11 | if heap: 12 | disk_1, disk_2 = heapq.heappop(heap) 13 | start = now 14 | now += disk_1 15 | time += (now-disk_2) 16 | i += 1 17 | else: 18 | now += 1 19 | 20 | return time//len(jobs) -------------------------------------------------------------------------------- /Programmers/jiwoo/heap/이중우선순위큐.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | def solution(operations): 4 | min_heap = [] 5 | max_heap = [] 6 | 7 | for o in operations: 8 | operation = o.split() 9 | if operation[0] == "I": 10 | num = int(operation[1]) 11 | heapq.heappush(min_heap, num) 12 | heapq.heappush(max_heap, (-num, num)) 13 | else: 14 | if not min_heap: 15 | pass 16 | elif operation[1] == '1': 17 | max_num = heapq.heappop(max_heap)[1] 18 | min_heap.remove(max_num) 19 | elif operation[1] == '-1': 20 | min_num = heapq.heappop(min_heap) 21 | max_heap.remove((-min_num, min_num)) 22 | 23 | return [heapq.heappop(max_heap)[1], heapq.heappop(min_heap)] if min_heap else [0,0] -------------------------------------------------------------------------------- /Programmers/jiwoo/sort/HIndex.py: -------------------------------------------------------------------------------- 1 | def solution(citations): 2 | citations.sort(reverse=True) 3 | h = len(citations) 4 | 5 | while True: 6 | count = 0 7 | for c in citations: 8 | if c >= h: 9 | count += 1 10 | if count >= h: 11 | return h 12 | h -= 1 -------------------------------------------------------------------------------- /Programmers/jiwoo/sort/K번째수.py: -------------------------------------------------------------------------------- 1 | def solution(array, commands): 2 | return [sorted(array[i-1:j]))[k-1] for i, j, k in commands] -------------------------------------------------------------------------------- /Programmers/jiwoo/sort/가장큰수.py: -------------------------------------------------------------------------------- 1 | def solution(numbers): 2 | numbers = list(map(str, numbers)) 3 | numbers.sort(key = lambda x: x*3, reverse=True) 4 | return str(int(''.join(numbers))) -------------------------------------------------------------------------------- /Programmers/jiwoo/stack_queue/주식가격.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(prices): 4 | answer = [] 5 | 6 | prices_deq = deque(prices) 7 | 8 | while prices_deq: 9 | price = prices_deq.popleft() 10 | count = 0 11 | for i in prices_deq: 12 | count += 1 13 | if i < price: 14 | break 15 | answer.append(count) 16 | 17 | return answer -------------------------------------------------------------------------------- /Programmers/jiwoo/stack_queue/프린터.py: -------------------------------------------------------------------------------- 1 | def solution(priorities, location): 2 | answer = 0 3 | while priorities: 4 | max_pri = max(priorities) 5 | n = priorities.pop(0) 6 | if max_pri == n: 7 | answer += 1 8 | if location == 0: 9 | return answer 10 | else: 11 | location -= 1 12 | else: 13 | priorities.append(n) 14 | location = len(priorities)-1 if location == 0 else location-1 -------------------------------------------------------------------------------- /Programmers/suyeon/2018_kakao_blind/뉴스 클러스터링.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | NUM = 65536 4 | 5 | def get_set(_str): 6 | _list = [] 7 | for i in range(0, len(_str) - 1): 8 | e = _str[i:i + 2].lower() 9 | if 'a' <= e[0] <= 'z' and 'a' <= e[1] <= 'z': 10 | _list.append(e) 11 | return _list 12 | 13 | def solution(str1, str2): 14 | str1, str2 = get_set(str1), get_set(str2) 15 | 16 | set_intersection = set(str1) & set(str2) 17 | set_union = set(str1) | set(str2) 18 | 19 | if not set_union: 20 | return NUM 21 | 22 | intersection = sum([min(str1.count(e), str2.count(e)) for e in set_intersection]) 23 | union = sum([max(str1.count(e), str2.count(e)) for e in set_union]) 24 | 25 | return math.floor(intersection * NUM / union) -------------------------------------------------------------------------------- /Programmers/suyeon/2018_kakao_blind/캐시.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(cacheSize, cities): 4 | if not cacheSize: 5 | return len(cities) * 5 6 | 7 | answer = 0 8 | cache = deque(maxlen = cacheSize) 9 | for city in cities: 10 | city = city.lower() 11 | if city in cache: 12 | cache.remove(city) 13 | cache.append(city) 14 | answer += 1 15 | else: 16 | cache.append(city) 17 | answer += 5 18 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/2018_kakao_blind/프렌즈4블록.py: -------------------------------------------------------------------------------- 1 | def get_pop(m, n, board): 2 | set_pop = set() 3 | for i in range(1, n): 4 | for j in range(1, m): 5 | if board[i][j] == board[i - 1][j - 1] == board[i - 1][j] == board[i][j - 1]: 6 | if board[i][j] != '': 7 | set_pop.update([(i, j), (i - 1, j - 1), (i - 1, j), (i, j - 1)]) 8 | 9 | for i, j in set_pop: 10 | board[i][j] = '' 11 | 12 | for i in range(n): 13 | temp1 = [b for b in board[i] if b != ''] 14 | temp2 = [''] * (m - len(temp1)) 15 | board[i] = temp2 + temp1 16 | 17 | return len(set_pop) 18 | 19 | def solution(m, n, board): 20 | board = list(map(list, zip(*board))) # row, col rotation 21 | 22 | answer = 0 23 | while True: 24 | pop = get_pop(m, n, board) 25 | if not pop: return answer 26 | answer += pop -------------------------------------------------------------------------------- /Programmers/suyeon/2019_kakao_blind/실패율.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | def solution(N, stages): 4 | stage_dict = defaultdict(int) 5 | for stage in stages: 6 | stage_dict[stage] += 1 7 | 8 | answer = {} 9 | user = len(stages) 10 | for i in range(1, N + 1): 11 | user -= stage_dict[i - 1] 12 | answer[i] = stage_dict[i]/user if user else 0 13 | 14 | return sorted(answer, key=lambda x: answer[x], reverse=True) -------------------------------------------------------------------------------- /Programmers/suyeon/2019_kakao_blind/오픈채팅방.py: -------------------------------------------------------------------------------- 1 | def solution(record): 2 | nickname_dict = {} 3 | 4 | for rec in record: 5 | rec = rec.split() 6 | if rec[0] == 'Enter' or rec[0] == 'Change': 7 | nickname_dict[rec[1]] = rec[2] 8 | 9 | answer = [] 10 | for rec in record: 11 | rec = rec.split() 12 | nickname = nickname_dict[rec[1]] 13 | if rec[0] == 'Enter': 14 | answer.append(nickname + '님이 들어왔습니다.') 15 | elif rec[0] == 'Leave': 16 | answer.append(nickname + '님이 나갔습니다.') 17 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/2019_kakao_blind/후보키.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from itertools import combinations 3 | 4 | def solution(relation): 5 | len_relation = len(relation) 6 | columns = [i for i in range(len(relation[0]))] 7 | 8 | uniqueness = defaultdict(set) 9 | for len_candidate in range(1, len(relation[0])): 10 | candidates = list(combinations(columns, len_candidate)) 11 | for candidate in candidates: 12 | candidate_set = set() 13 | for row in range(len_relation): 14 | temp = tuple() 15 | for col in candidate: 16 | temp += (relation[row][col], ) 17 | candidate_set.add(temp) 18 | if len(candidate_set) == len_relation: 19 | uniqueness[len_candidate].add(candidate) 20 | 21 | minimality = set() 22 | for key in uniqueness: 23 | for value in uniqueness[key]: 24 | flag_1 = False 25 | for m in minimality: 26 | flag_2 = True 27 | for _m in m: 28 | if _m not in value: 29 | flag_2 = False 30 | if flag_2: 31 | flag_1 = True 32 | if not flag_1: 33 | minimality.add(value) 34 | return len(minimality) if len(minimality) else 1 -------------------------------------------------------------------------------- /Programmers/suyeon/2020_kakao_blind/괄호 변환.py: -------------------------------------------------------------------------------- 1 | def solution(p): 2 | if not p: return p 3 | 4 | count = 0 5 | is_correct = True 6 | for i, pp in enumerate(p): 7 | count += 1 if pp == '(' else -1 8 | 9 | if count < 0: 10 | is_correct = False 11 | elif count == 0: 12 | u, v = p[:i+1], p[i+1:] 13 | 14 | if is_correct: 15 | return u + solution(v) 16 | else: 17 | u = ''.join([')' if uu == '(' else '(' for uu in u[1:-1]]) 18 | return '(' + solution(v) + ')' + u -------------------------------------------------------------------------------- /Programmers/suyeon/2020_kakao_blind/문자열 압축.py: -------------------------------------------------------------------------------- 1 | def get_rotation(keys, m): # 90 rotation 2 | matrix = [[0] * m for _ in range(m)] 3 | for i in range(m): 4 | for j in range(m): 5 | matrix[i][j] = keys[m - 1 - j][i] 6 | return matrix 7 | 8 | def solution(keys, locks): 9 | m, n = len(keys), len(locks) 10 | for angle in range(0, 360, 90): 11 | for x in range(m + n): 12 | for y in range(m + n): 13 | matrix = [[0] * (n + 2 * m) for _ in range(n + 2 * m)] 14 | for i in range(m): 15 | for j in range(m): 16 | matrix[x + i][y + j] = keys[i][j] 17 | 18 | answer = True 19 | for i in range(n): 20 | for j in range(n): 21 | if matrix[m + i][m + j] ^ locks[i][j] == 0: 22 | answer = False 23 | break 24 | if answer: return True 25 | 26 | keys = get_rotation(keys, m) 27 | return False -------------------------------------------------------------------------------- /Programmers/suyeon/2020_kakao_blind/자물쇠와 열쇠.py: -------------------------------------------------------------------------------- 1 | def get_rotation(keys, m): # 90 rotation 2 | matrix = [[0] * m for _ in range(m)] 3 | for i in range(m): 4 | for j in range(m): 5 | matrix[i][j] = keys[m - 1 - j][i] 6 | return matrix 7 | 8 | def solution(keys, locks): 9 | m, n = len(keys), len(locks) 10 | for angle in range(0, 360, 90): 11 | if angle != 0: 12 | keys = get_rotation(keys, m) 13 | 14 | for x in range(m + n): 15 | for y in range(m + n): 16 | matrix = [[0] * (n + 2 * m) for _ in range(n + 2 * m)] 17 | for i in range(m): 18 | for j in range(m): 19 | matrix[x + i][y + j] = keys[i][j] 20 | 21 | answer = True 22 | for i in range(n): 23 | for j in range(n): 24 | if matrix[m + i][m + j] ^ locks[i][j] == 0: 25 | answer = False 26 | break 27 | if answer: return True 28 | return False -------------------------------------------------------------------------------- /Programmers/suyeon/2021_kakao_blind/메뉴 리뉴얼.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from itertools import combinations 3 | 4 | def solution(orders, course): 5 | course_dict = {} 6 | for c in course: 7 | course_dict[c] = defaultdict(int) 8 | 9 | for order in orders: 10 | menu_list = list(order) 11 | for c in course: 12 | temp = list(combinations(menu_list, c)) 13 | for t in temp: 14 | t = list(t) 15 | t.sort() 16 | course_dict[c][''.join(t)] += 1 17 | 18 | answer = [] 19 | for key, value in course_dict.items(): 20 | max_value = 0 21 | for k, v in value.items(): 22 | if v > max_value: 23 | max_value = v 24 | for k, v in value.items(): 25 | if v >= 2 and v == max_value: 26 | answer.append(''.join(k)) 27 | 28 | answer.sort() 29 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/2021_kakao_blind/순위 검색.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | def solution(info, query): 4 | group_info = defaultdict(list) 5 | for i, user_info in enumerate(info): 6 | lang, task, exp, food, score = user_info.split() 7 | score = int(score) 8 | 9 | case_list = [] 10 | for a in ["-", lang]: 11 | for b in ["-", task]: 12 | for c in ["-", exp]: 13 | for d in ["-", food]: 14 | group_info[(a, b, c, d)].append(score) 15 | 16 | for key in group_info: 17 | group_info[key].sort() 18 | 19 | answer = [] 20 | for q in query: 21 | lang, _, task, _, exp, _, food, score = q.split() 22 | score = int(score) 23 | 24 | temp = group_info[(lang, task, exp, food)] 25 | 26 | start, end = 0, len(temp) - 1 27 | while start <= end: 28 | mid = (start + end) // 2 29 | 30 | if temp[mid] < score: 31 | start = mid + 1 32 | else: 33 | end = mid - 1 34 | 35 | answer.append(len(temp) - start) 36 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/2021_kakao_blind/신규 아이디 추천.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def solution(new_id): 4 | new_id = new_id.lower() # 1단계 5 | new_id = re.sub("[^a-z0-9-_.]", "", new_id) # 2단계 6 | new_id = re.sub("[.]+", ".",new_id) # 3단계 7 | new_id = re.sub("^[.]|[.]$", "", new_id) # 4단계 8 | if not new_id: new_id = "a" # 5단계 9 | new_id = re.sub("[.]$", "", new_id[:15]) # 6단계 10 | if len(new_id) <= 2: new_id = new_id.ljust(3, new_id[-1]) # 7단계 11 | 12 | return new_id -------------------------------------------------------------------------------- /Programmers/suyeon/24_week/숫자 문자열과 영단어.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | word_dict = { 4 | 'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 5 | 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9' 6 | } 7 | 8 | def solution(s): 9 | s = deque(s) 10 | answer, word = '', '' 11 | 12 | while(s): 13 | digit = s.popleft() 14 | 15 | if digit.isdigit(): 16 | answer += digit 17 | continue 18 | 19 | word += digit 20 | 21 | if word in word_dict: 22 | answer += word_dict[word] 23 | word = '' 24 | 25 | return int(answer) -------------------------------------------------------------------------------- /Programmers/suyeon/25_week/거리두기 확인하기.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | 3 | SPACE_SIZE = 5 4 | 5 | def get_people(place): 6 | people = [] 7 | for i in range(SPACE_SIZE): 8 | for j in range(SPACE_SIZE): 9 | if place[i][j] == 'P': 10 | people.append((i, j)) 11 | return people 12 | 13 | def is_succesful_distancing(place): 14 | for (r1, c1), (r2, c2) in combinations(get_people(place), 2): 15 | manhattan = abs(r1 - r2) + abs(c1 - c2) 16 | 17 | if manhattan > 2: 18 | continue 19 | elif manhattan == 1: 20 | return False 21 | 22 | if r1 == r2: 23 | if place[r1][min(c1, c2) + 1] == 'X': 24 | continue 25 | elif c1 == c2: 26 | if place[min(r1, r2) + 1][c1] == 'X': 27 | continue 28 | else: 29 | r, c = min(r1, r2), min(c1, c2) 30 | if (r1 - r2) * (c1 - c2) > 0: 31 | if place[r][c + 1] == 'X' and place[r + 1][c] == 'X': 32 | continue 33 | else: 34 | if place[r][c] == 'X' and place[r + 1][c + 1] == 'X': 35 | continue 36 | 37 | return False 38 | 39 | return True 40 | 41 | def solution(places): 42 | return [ 1 if is_succesful_distancing(place) else 0 for place in places] -------------------------------------------------------------------------------- /Programmers/suyeon/26_week/수식 최대화.py: -------------------------------------------------------------------------------- 1 | import re 2 | from functools import reduce 3 | from itertools import permutations 4 | 5 | PLUS, MINUS, MULTIPLY = '+', '-', '*' 6 | 7 | def calculate(operator, numbers): 8 | if operator == PLUS: 9 | return reduce(lambda x, y: x + y, numbers) 10 | elif operator == MINUS: 11 | return reduce(lambda x, y: x - y, numbers) 12 | else: 13 | return reduce(lambda x, y: x * y, numbers) 14 | 15 | 16 | def divide_and_conquer(operators, idx, expression): 17 | if expression.isdigit(): 18 | return int(expression) 19 | 20 | temp = [] 21 | for sub_expression in expression.split(operators[idx]): 22 | temp.append(divide_and_conquer(operators, idx + 1, sub_expression)) 23 | 24 | return calculate(operators[idx], temp) 25 | 26 | 27 | def solution(expression): 28 | answer = 0 29 | 30 | for operators in permutations(set(re.sub(r'[0-9]', '',expression))): 31 | answer = max(answer, abs(divide_and_conquer(operators, 0, expression))) 32 | 33 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/27_week/튜플.py: -------------------------------------------------------------------------------- 1 | def parse_s(s): 2 | return [list(map(int, sub_s.split(','))) for sub_s in s[2:-2].split('},{')] 3 | 4 | 5 | def solution(s): 6 | answer = {} 7 | 8 | for sub_list in sorted(parse_s(s), key=len): 9 | for digit in sub_list: 10 | if digit not in answer: 11 | answer[digit] = 0 12 | 13 | return list(answer) -------------------------------------------------------------------------------- /Programmers/suyeon/28_week/파일명 정렬.py: -------------------------------------------------------------------------------- 1 | def file_split(file): 2 | head, number = '', 0 3 | 4 | for idx, token in enumerate(file): 5 | if token.isdigit(): 6 | head = file[:idx] 7 | file = file[idx:] 8 | break 9 | 10 | number_flag = False 11 | for idx, token in enumerate(file): 12 | if not token.isdigit(): 13 | number = file[:idx] 14 | number_flag = True 15 | break 16 | 17 | if not number_flag: 18 | number = file 19 | 20 | return (head.lower(), int(number)) 21 | 22 | 23 | def solution(files): 24 | file_dict = {file: file_split(file) for file in files} 25 | 26 | sorted_dict = dict(sorted(file_dict.items(), key=lambda x : (x[1][0], x[1][1]))) 27 | 28 | return list(sorted_dict.keys()) 29 | -------------------------------------------------------------------------------- /Programmers/suyeon/29_week/n진수 게임.py: -------------------------------------------------------------------------------- 1 | HEX_DICT = { 10 : 'A', 11 : 'B', 12 : 'C', 13 : 'D', 14 : 'E', 15 : 'F' } 2 | 3 | def convert(number, n): 4 | if number <= 1: 5 | return '1' if number == 1 else '' 6 | 7 | q, r = divmod(number, n) 8 | temp = HEX_DICT[r] if r in HEX_DICT else str(r) 9 | 10 | return convert(q, n) + temp 11 | 12 | def solution(n, t, m, p): 13 | answer = '' 14 | number = 0 15 | 16 | while len(answer) < t * m: 17 | temp = convert(number, n) 18 | if temp == '': 19 | temp = '0' 20 | answer += temp 21 | number += 1 22 | 23 | return answer[p - 1::m][:t] -------------------------------------------------------------------------------- /Programmers/suyeon/30_week/주차 요금 계산.py: -------------------------------------------------------------------------------- 1 | from math import ceil 2 | from collections import defaultdict 3 | 4 | LAST = 23 * 60 + 59 5 | 6 | 7 | def time_converter(time): 8 | hour, minute = map(int ,time.split(':')) 9 | return hour * 60 + minute 10 | 11 | 12 | def calculate_fee(fees, minute): 13 | base_minute, base_time, unit_time, unit_fee = fees 14 | 15 | if minute <= base_minute: 16 | return base_time 17 | 18 | return base_time + ceil((minute - base_minute) / unit_time) * unit_fee 19 | 20 | 21 | def solution(fees, records): 22 | car_dict = defaultdict(list) 23 | 24 | for record in records: 25 | time, car, io = record.split(' ') 26 | car_dict[car].append(time_converter(time)) 27 | 28 | answer = [] 29 | for car, record in car_dict.items(): 30 | sum_time, record_length = 0, len(record) 31 | 32 | for idx in range(1, len(record), 2): 33 | sum_time += record[idx] - record[idx - 1] 34 | 35 | if record_length % 2 == 1: 36 | sum_time += LAST - record[-1] 37 | 38 | print(car, sum_time) 39 | answer.append((car, calculate_fee(fees, sum_time))) 40 | 41 | return list(zip(*sorted(answer)))[1] -------------------------------------------------------------------------------- /Programmers/suyeon/31_week/k 진수에서 소수 개수 구하기.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | def is_prime(n): 4 | if n == 2: 5 | return True 6 | 7 | if n % 2 == 0 or n == 1: 8 | return False 9 | 10 | for i in range(3, int(sqrt(n)) + 1, 2): 11 | if n % i == 0: 12 | return False 13 | 14 | return True 15 | 16 | 17 | def convert(q, k): 18 | temp = '' 19 | 20 | while True: 21 | q, r = divmod(q, k) 22 | temp = str(r) + temp 23 | 24 | if q <= 1: 25 | temp = str(q) + temp 26 | break 27 | 28 | return temp 29 | 30 | 31 | def solution(n, k): 32 | answer = 0 33 | 34 | for num in convert(n, k).split('0'): 35 | if num != '' and is_prime(int(num)): 36 | answer += 1 37 | 38 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/32_week/멀쩡한 사각형.py: -------------------------------------------------------------------------------- 1 | def gcd(x, y): 2 | while(y): 3 | x, y = y, x % y 4 | 5 | return x 6 | 7 | def solution(w,h): 8 | return w * h - (w + h - gcd(w, h)) -------------------------------------------------------------------------------- /Programmers/suyeon/33_week/불량 사용자.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | answer = [] 4 | 5 | def dfs(banned_list, idx, temp): 6 | if idx == len(banned_list): 7 | temp = set(temp) 8 | 9 | if temp not in answer: 10 | answer.append(temp) 11 | 12 | return 13 | 14 | for u_id in banned_list[idx]: 15 | if u_id not in temp: 16 | temp.add(u_id) 17 | dfs(banned_list, idx + 1, temp) 18 | temp.remove(u_id) 19 | 20 | 21 | def is_mapping(u_id, b_id): 22 | if len(u_id) != len(b_id): 23 | return False 24 | 25 | for u, b in zip(u_id, b_id): 26 | if b == '*': 27 | continue 28 | 29 | if u != b: 30 | return False 31 | 32 | return True 33 | 34 | 35 | def solution(user_id, banned_id): 36 | banned_list = [] 37 | 38 | for b_id in banned_id: 39 | banned_list.append([u_id for u_id in user_id if is_mapping(u_id, b_id)]) 40 | 41 | dfs(banned_list, 0, set()) 42 | 43 | return len(answer) -------------------------------------------------------------------------------- /Programmers/suyeon/34_week/방금그곡.py: -------------------------------------------------------------------------------- 1 | def convert_time(start, end): 2 | start_h, start_m = start.split(':') 3 | end_h, end_m = end.split(':') 4 | 5 | return (int(end_h) * 60 + int(end_m)) - (int(start_h) * 60 + int(start_m)) 6 | 7 | def convert_score(score): 8 | return score.replace('C#', 'c').replace('D#', 'd').replace('F#', 'f').replace('G#', 'g').replace('A#', 'a') 9 | 10 | def solution(m, musicinfos): 11 | answer = [] 12 | m = convert_score(m) 13 | 14 | for info in musicinfos: 15 | start_time, end_time, title, score = info.split(',') 16 | 17 | play_time = convert_time(start_time, end_time) 18 | score = convert_score(score) 19 | 20 | score = score * (play_time // len(score) + 1) 21 | score = score[:play_time] 22 | 23 | for i in range(len(score)): 24 | if m == score[i:i + len(m)]: 25 | answer.append((play_time, title)) 26 | break 27 | 28 | return '(None)' if not answer else sorted(answer, key=lambda x:-x[0])[0][1] -------------------------------------------------------------------------------- /Programmers/suyeon/35_week/모음 사전.py: -------------------------------------------------------------------------------- 1 | from itertools import product 2 | 3 | def solution(word): 4 | vowels = ['A', 'E', 'I', 'O', 'U'] 5 | 6 | words = [] 7 | for i in range(len(vowels)): 8 | words.extend(map(''.join, list(product(vowels, repeat = i + 1)))) 9 | 10 | return sorted(words).index(word) + 1 -------------------------------------------------------------------------------- /Programmers/suyeon/36_week/n^2 배열 자르기.py: -------------------------------------------------------------------------------- 1 | def solution(n, left, right): 2 | return [max(divmod(i, n)) + 1 for i in range(int(left), int(right) + 1)] -------------------------------------------------------------------------------- /Programmers/suyeon/37_week/피로도.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def solution(k, dungeons): 4 | answer = -1 5 | 6 | for perm_dungeons in permutations(dungeons, len(dungeons)): 7 | count, min_k = 0, k 8 | for min_hp, hp in perm_dungeons: 9 | if min_k >= min_hp: 10 | count += 1 11 | min_k -= hp 12 | 13 | if count > answer: 14 | answer = count 15 | 16 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/38_week/교점에 별 만들기.py: -------------------------------------------------------------------------------- 1 | def make_star(points, x_points, y_points): 2 | x_min, x_max = min(x_points), max(x_points) 3 | y_min, y_max = min(y_points), max(y_points) 4 | 5 | matrix = [['.'] * (x_max - x_min + 1) for _ in range(y_max - y_min + 1)] 6 | 7 | for x, y in points: 8 | matrix[y_max - y][x - x_min] = '*' 9 | 10 | return [''.join(m) for m in matrix] 11 | 12 | def solution(line): 13 | points = set() 14 | 15 | for i in range(0, len(line)): 16 | a, b, e = line[i] 17 | 18 | for j in range(i + 1, len(line)): 19 | c, d, f = line[j] 20 | 21 | denominator = a * d - b * c 22 | 23 | if denominator: 24 | x = (b * f - e * d) / denominator 25 | y = (e * c - a * f) / denominator 26 | 27 | if int(x) == x and int(y) == y: 28 | points.add((int(x), int(y))) 29 | 30 | return make_star(points, list(zip(*points))[0], list(zip(*points))[1]) -------------------------------------------------------------------------------- /Programmers/suyeon/39_week/삼각 달팽이.py: -------------------------------------------------------------------------------- 1 | # 아래, 오른쪽, 위 2 | dx = [1, 0, -1] 3 | dy = [0, 1, -1] 4 | 5 | def solution(n): 6 | matrix = [[0] * i for i in range(1, n + 1)] 7 | 8 | x, y = -1, 0 9 | num, idx = 0, -1 10 | 11 | for count in range(n, 0, -1): 12 | idx = (idx + 1) % 3 13 | for _ in range(count): 14 | num += 1 15 | x += dx[idx] 16 | y += dy[idx] 17 | matrix[x][y] = num 18 | 19 | return [col for row in matrix for col in row] -------------------------------------------------------------------------------- /Programmers/suyeon/40_week/빛의 경로 사이클.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | # 시계 방향 (좌, 하, 우, 상) 4 | dx = [0, 1, 0, -1] 5 | dy = [-1, 0, 1, 0] 6 | 7 | def get_cycle_length(grid, visited, x, y, d): 8 | row, col = len(grid), len(grid[0]) 9 | 10 | count = 0 11 | 12 | while not visited[x][y][d]: 13 | count += 1 14 | visited[x][y][d] = True 15 | 16 | if(grid[x][y] == 'L'): 17 | d = (d + 1) % 4 18 | elif(grid[x][y] == 'R'): 19 | d = (d - 1) % 4 20 | 21 | x = (x + dx[d]) % row 22 | y = (y + dy[d]) % col 23 | 24 | return count 25 | 26 | def solution(grid): 27 | row, col = len(grid), len(grid[0]) 28 | 29 | answer = [] 30 | visited = [[[False] * 4 for _ in range(col)] for _ in range(row)] 31 | 32 | for x in range(row): 33 | for y in range(col): 34 | for d in range(4): 35 | if not visited[x][y][d]: 36 | answer.append(get_cycle_length(grid, visited, x, y, d)) 37 | 38 | return sorted(answer) -------------------------------------------------------------------------------- /Programmers/suyeon/42_week/점프와 순간 이동.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | ans = 0 3 | 4 | while n: 5 | ans += n % 2 6 | n //= 2 7 | 8 | return ans -------------------------------------------------------------------------------- /Programmers/suyeon/43_week/스킬트리.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def solution(skill, skill_trees): 4 | answer = 0 5 | 6 | for skill_tree in skill_trees: 7 | temp = re.findall('['+skill+']', skill_tree) 8 | 9 | if ''.join(temp) == skill[:len(temp)]: 10 | answer += 1 11 | 12 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/44_week/양과 늑대.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | SHEEP, WOLF = 0, 1 4 | 5 | def bfs(graph, info, start): 6 | # 현재 노드, 양의 수, 늑대의 수, 이동 가능 노드 7 | max_sheep = 0 8 | queue = deque([[start, 1, 0, set()]]) 9 | 10 | while queue: 11 | node, sheep_count, wolf_count, nexts = queue.popleft() 12 | 13 | max_sheep = max(max_sheep, sheep_count) 14 | nexts.update(graph[node]) 15 | 16 | for next_node in nexts: 17 | if info[next_node] == SHEEP: 18 | queue.append([next_node, sheep_count + 1, wolf_count, nexts - {next_node}]) 19 | elif sheep_count > wolf_count + 1: 20 | queue.append([next_node, sheep_count, wolf_count + 1, nexts - {next_node}]) 21 | 22 | return max_sheep 23 | 24 | 25 | def solution(info, edges): 26 | graph = [[] for _ in range(len(info))] 27 | 28 | for parent, child in edges: 29 | graph[parent].append(child) 30 | 31 | return bfs(graph, info, 0) -------------------------------------------------------------------------------- /Programmers/suyeon/46_week/2개 이하로 다른 비트.py: -------------------------------------------------------------------------------- 1 | def solution(numbers): 2 | answer = [] 3 | 4 | for number in numbers: 5 | if number % 2 == 0: 6 | answer.append(number + 1) 7 | continue 8 | 9 | bin_number = list('0' + bin(number)[2:]) 10 | idx = ''.join(bin_number).rfind('0') 11 | 12 | bin_number[idx] = '1' 13 | bin_number[idx+1] = '0' 14 | 15 | answer.append(int(''.join(bin_number), 2)) 16 | 17 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/47_week/110 옮기기.py: -------------------------------------------------------------------------------- 1 | ooz = '110' 2 | 3 | 4 | def split_ooz(x): 5 | count, stack = 0, [] 6 | 7 | for token in x: 8 | if token != '0' or stack[-2:] != ['1', '1']: 9 | stack.append(token) 10 | continue 11 | 12 | stack.pop() 13 | stack.pop() 14 | count += 1 15 | 16 | return (count, ''.join(stack)) 17 | 18 | 19 | def get_min_order(x): 20 | count, x = split_ooz(x) 21 | 22 | idx_oo = x.find('11') 23 | 24 | if idx_oo != -1: 25 | return x[:idx_oo] + ooz * count + x[idx_oo:] 26 | 27 | idx_last_z = x.rfind('0') 28 | 29 | if idx_last_z != -1: 30 | return x[:idx_last_z + 1] + ooz * count + x[idx_last_z + 1:] 31 | 32 | return ooz * count + x 33 | 34 | 35 | def solution(s): 36 | return [get_min_order(x) for x in s] -------------------------------------------------------------------------------- /Programmers/suyeon/48_week/배달.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | 3 | INF = int(1e9) 4 | 5 | 6 | def dijkstra(start, n, graph): 7 | distance = [INF] * (n + 1) 8 | distance[start] = 0 9 | 10 | queue = [] 11 | heappush(queue, (0, start)) 12 | 13 | while queue: 14 | dist, now = heappop(queue) 15 | 16 | if distance[now] < dist: 17 | continue 18 | 19 | for c, node in graph[now]: 20 | cost = dist + c 21 | 22 | if cost < distance[node]: 23 | distance[node] = cost 24 | heappush(queue, (cost, node)) 25 | 26 | return distance 27 | 28 | 29 | def solution(N, road, K): 30 | graph = [[] for _ in range(N + 1)] 31 | 32 | for a, b, c in road: 33 | graph[a].append((c, b)) 34 | graph[b].append((c, a)) 35 | 36 | return len([dist for dist in dijkstra(1, N, graph) if dist <= K]) -------------------------------------------------------------------------------- /Programmers/suyeon/50_week/기능 개발.py: -------------------------------------------------------------------------------- 1 | 2 | from collections import deque 3 | 4 | def solution(progresses, speeds): 5 | progresses = deque(progresses) 6 | speeds = deque(speeds) 7 | 8 | answer = [] 9 | 10 | while progresses: 11 | for idx, speed in enumerate(speeds): 12 | progresses[idx] += speed 13 | 14 | count = 0 15 | 16 | while progresses and progresses[0] >= 100: 17 | progresses.popleft() 18 | speeds.popleft() 19 | count += 1 20 | 21 | if count: 22 | answer.append(count) 23 | 24 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/51_week/두 큐 합 같게 만들기.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(queue1, queue2): 4 | sum1, sum2 = sum(queue1), sum(queue2) 5 | queue1, queue2 = deque(queue1), deque(queue2) 6 | 7 | answer = 0 8 | max_count = len(queue1) * 2 + 1 9 | 10 | while True: 11 | if sum1 == sum2: 12 | break 13 | 14 | if answer > max_count: 15 | answer = -1 16 | break 17 | 18 | answer += 1 19 | 20 | if sum1 > sum2: 21 | sum1 -= queue1[0] 22 | sum2 += queue1[0] 23 | queue2.append(queue1.popleft()) 24 | else: 25 | sum2 -= queue2[0] 26 | sum1 += queue2[0] 27 | queue1.append(queue2.popleft()) 28 | 29 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/52_week/전력망을 둘로 나누기.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict, deque 2 | 3 | 4 | def bfs(v1, v2, graph): 5 | count = 1 6 | queue = deque([v1]) 7 | 8 | visited = [False] * (len(graph) + 1) 9 | visited[v1] = True 10 | visited[v2] = True 11 | 12 | while queue: 13 | node = queue.popleft() 14 | 15 | for n in graph[node]: 16 | if not visited[n]: 17 | visited[n] = True 18 | queue.append(n) 19 | count += 1 20 | 21 | return count 22 | 23 | 24 | def solution(n, wires): 25 | answer = n 26 | graph = defaultdict(set) 27 | 28 | for v1, v2 in wires: 29 | graph[v1].add(v2) 30 | graph[v2].add(v1) 31 | 32 | for v1, v2 in wires: 33 | answer = min(answer, abs(n - 2 * bfs(v1, v2, graph))) 34 | 35 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/53_week/JadenCase 문자열 만들기.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | s = [' '] + list(s.lower()) 3 | 4 | for i in range(len(s) - 1): 5 | if s[i] == ' ' and not s[i + 1].isdigit(): 6 | s[i + 1] = s[i + 1].upper() 7 | 8 | return ''.join(s[1:]) -------------------------------------------------------------------------------- /Programmers/suyeon/54_week/124 나라의 숫자.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | answer = '' 3 | 4 | while n: 5 | if n % 3: 6 | answer += str(n % 3) 7 | n //= 3 8 | else: 9 | answer += '4' 10 | n = n//3 - 1 11 | 12 | return answer[::-1] -------------------------------------------------------------------------------- /Programmers/suyeon/55_week/양궁대회.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations_with_replacement 2 | 3 | def solution(n, apeach_info): 4 | answer = [] 5 | diff = 0 6 | 7 | for case in combinations_with_replacement(range(11), n): 8 | lion_info = [0] * 11 9 | 10 | for i in case: 11 | lion_info[10 - i] += 1 12 | 13 | apeach_score, lion_score = 0, 0 14 | 15 | for i, (apeach, lion) in enumerate(zip(apeach_info, lion_info)): 16 | if not apeach and not lion: 17 | continue 18 | 19 | if apeach >= lion: 20 | apeach_score += 10 - i 21 | else: 22 | lion_score += 10 - i 23 | 24 | if lion_score - apeach_score > diff: 25 | diff = lion_score - apeach_score 26 | answer = lion_info 27 | 28 | return answer or [-1] -------------------------------------------------------------------------------- /Programmers/suyeon/binary_search/입국심사.py: -------------------------------------------------------------------------------- 1 | def solution(n, times): 2 | start = min(times) * n // len(times) 3 | end = max(times) * n // len(times) 4 | 5 | while start <= end: 6 | mid = (start + end) //2 7 | 8 | cnt = 0 # 심사 가능한 최대 인원 9 | for time in times: 10 | cnt += mid // time 11 | 12 | if cnt < n: 13 | start = mid + 1 14 | else: 15 | end = mid - 1 16 | 17 | return start -------------------------------------------------------------------------------- /Programmers/suyeon/binary_search/징검다리.py: -------------------------------------------------------------------------------- 1 | def solution(distance, rocks, n): 2 | rocks.sort() 3 | rocks.append(distance) 4 | 5 | answer = 0 6 | start, end = 1, distance # answer은 1 ~ distance 사이에 있음 7 | while start <= end: 8 | mid = (start + end) // 2 9 | 10 | # 부서진 바위의 수 세기 11 | cnt_rock, prev_rock = 0, 0 12 | for rock in rocks: 13 | if rock - prev_rock < mid: 14 | cnt_rock += 1 15 | else: 16 | prev_rock = rock 17 | 18 | if cnt_rock > n: # 더 많이 파괴되었을 경우 19 | end = mid - 1 20 | else: # 같거나 더 작게 파괴되었을 경우 21 | answer = mid 22 | start = mid + 1 23 | 24 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/brute_force/소수 찾기.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | # 에라토스테네스의 체 4 | def prime_list(n): 5 | prime = [True] * (n + 1) 6 | prime[0] = prime[1] = False 7 | 8 | for i in range(2, int(n ** 0.5) + 1): 9 | if prime[i]: 10 | for j in range(i*i, len(prime), i): 11 | prime[j] = False 12 | return prime 13 | 14 | def solution(numbers): 15 | numbers = list(numbers) 16 | number_set = set() 17 | 18 | # 가능한 모든 경우의 수 (순열) => set 사용해서 중복 제거 19 | for i in range(len(numbers)): 20 | number_set |= set(map(int, map(''.join, permutations(numbers, i + 1)))) 21 | 22 | # 에라토스테네스의 체로 소수 판별 리스트 생성 23 | prime = prime_list(max(number_set)) 24 | 25 | # 소수 판별 26 | answer = 0 27 | for number in number_set: 28 | if prime[number]: 29 | answer += 1 30 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/brute_force/카펫.py: -------------------------------------------------------------------------------- 1 | def solution(brown, yellow): 2 | total = brown + yellow 3 | # x(세로) <= total//x(가로) 이고, 4 | # x는 최소 3 이상이기 때문에 total//3 범위까지 반복함 5 | for x in range (3, total // 3 + 1): 6 | if total % x == 0 and brown == 2 * (x + total // x - 2): 7 | return [total // x, x] -------------------------------------------------------------------------------- /Programmers/suyeon/dfs_bfs/네트워크.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def bfs(graph, start, visited): 4 | queue = deque([start]) 5 | visited[start] = True 6 | 7 | while queue: 8 | v = queue.popleft() 9 | for i, connection in enumerate(graph[v]): 10 | if not visited[i] and connection == 1: 11 | queue.append(i) 12 | visited[i] = True 13 | 14 | def solution(n, computers): 15 | answer = 0 16 | visited = [False] * n 17 | 18 | for i in range(n): 19 | if not visited[i]: 20 | answer += 1 21 | if sum(computers[i]) > 1: 22 | bfs(computers, i,visited) 23 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/dfs_bfs/단어 변환.py: -------------------------------------------------------------------------------- 1 | def solution(begin, target, words): 2 | answer = 0 3 | stack = [begin] 4 | 5 | while True: 6 | temp = [] 7 | for word in stack: 8 | if word == target: return answer 9 | 10 | for i in range(len(words)-1, -1, -1): # Index Error 방지 11 | if sum([x!=y for x, y in zip(word, words[i])]) == 1: 12 | temp.append(words.pop(i)) 13 | # print(temp) 14 | if not temp: return 0 15 | stack = temp 16 | answer += 1 -------------------------------------------------------------------------------- /Programmers/suyeon/dfs_bfs/타겟 넘버.py: -------------------------------------------------------------------------------- 1 | def solution(numbers, target): 2 | answers = [numbers[0], -numbers[0]] 3 | for number in numbers[1:]: 4 | temp = [] 5 | for answer in answers: 6 | temp.append(answer + number) 7 | temp.append(answer - number) 8 | answers = temp 9 | 10 | return answers.count(target) -------------------------------------------------------------------------------- /Programmers/suyeon/dynamic_programming/N으로 표현.py: -------------------------------------------------------------------------------- 1 | def solution(N, number): 2 | if N == number: return 1 3 | 4 | DP = [{}, { N }] 5 | for i in range(2, 9): 6 | temp = { int(str(N) * i) } 7 | 8 | for j in range(1, i // 2 + 1): 9 | for num_1 in DP[j]: 10 | for num_2 in DP[i - j]: 11 | temp.add(num_1 + num_2) 12 | temp.add(num_1 - num_2) 13 | temp.add(num_2 - num_1) 14 | temp.add(num_1 * num_2) 15 | if num_2: temp.add(num_1 // num_2) 16 | if num_1: temp.add(num_2 // num_1) 17 | 18 | if number in temp: return i 19 | 20 | DP.append(temp) 21 | return -1 -------------------------------------------------------------------------------- /Programmers/suyeon/dynamic_programming/등굣길.py: -------------------------------------------------------------------------------- 1 | def solution(m, n, puddles): 2 | DP = [[0] * (m + 1) for _ in range(n + 1)] 3 | for x, y in puddles: DP[y][x] = -1 4 | 5 | DP[1][1] = 1 6 | for i in range(1, n + 1): 7 | for j in range(1, m + 1): 8 | if i == 1 and j == 1: 9 | continue 10 | elif DP[i][j] == -1: 11 | DP[i][j] = 0 12 | else: 13 | DP[i][j] = (DP[i - 1][j] + DP[i][j - 1]) % 1000000007 14 | return DP[-1][-1] -------------------------------------------------------------------------------- /Programmers/suyeon/dynamic_programming/정수 삼각형.py: -------------------------------------------------------------------------------- 1 | def solution(triangle): 2 | for i in range(1, len(triangle)): 3 | for j in range(i + 1): 4 | if j == 0: 5 | triangle[i][j] += triangle[i - 1][0] 6 | elif j == i: 7 | triangle[i][j] += triangle[i - 1][-1] 8 | else: 9 | triangle[i][j] += max(triangle[i - 1][j - 1], triangle[i - 1][j]) 10 | return max(triangle[-1]) -------------------------------------------------------------------------------- /Programmers/suyeon/graph/가장 먼 노드.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | INF = int(1e9) 4 | 5 | def solution(n, edge): 6 | graph = [[] for _ in range(n + 1)] 7 | distance = [INF] * (n + 1) 8 | 9 | for node1, node2 in edge: 10 | graph[node1].append(node2) 11 | graph[node2].append(node1) 12 | 13 | queue = deque([]) 14 | queue.append((0, 1)) # 1번 노드부터 시작 (dist, node) 15 | distance[1] = 0 16 | while queue: 17 | dist, now = queue.popleft() 18 | if distance[now] < dist: 19 | continue 20 | for node in graph[now]: 21 | cost = dist + 1 22 | 23 | if cost < distance[node]: 24 | distance[node] = cost 25 | queue.append((cost, node)) 26 | return distance.count(max(distance[1:])) -------------------------------------------------------------------------------- /Programmers/suyeon/graph/방의 개수.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict, deque 2 | 3 | def solution(arrows): 4 | move = [(-1, 0), (-1, 1), (0, 1), (1, 1), 5 | (1, 0), (1, -1), (0, -1), (-1, -1)] 6 | now = (0, 0) # x(열), y(행) 7 | 8 | visited = defaultdict(int) 9 | visited_dir = defaultdict(int) # (A, B)는 A -> B 10 | 11 | queue = deque([now]) 12 | for arrow in arrows: 13 | for _ in range(2): # 모래 시계 예외 처리를 위함 14 | next = (now[0] + move[arrow][0], now[1] + move[arrow][1]) 15 | queue.append(next) 16 | now = next 17 | 18 | answer = 0 19 | now = queue.popleft() 20 | visited[now] = 1 21 | 22 | while queue: 23 | next = queue.popleft() 24 | 25 | if visited[next] == 1: 26 | if visited_dir[(now, next)] == 0: 27 | answer += 1 28 | else: 29 | visited[next] = 1 30 | 31 | visited_dir[(now, next)] = 1 32 | visited_dir[(next, now)] = 1 33 | now = next 34 | 35 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/graph/순위.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | def solution(n, results): 4 | win_results, loses_results = defaultdict(set), defaultdict(set) 5 | 6 | for a, b in results: 7 | win_results[a].add(b) 8 | loses_results[b].add(a) 9 | 10 | for i in range(1, n + 1): 11 | for loser in win_results[i]: 12 | loses_results[loser].update(loses_results[i]) 13 | for winner in loses_results[i]: 14 | win_results[winner].update(win_results[i]) 15 | 16 | answer = 0 17 | for i in range(1, n + 1): 18 | if len(win_results[i]) + len(loses_results[i]) == n -1: 19 | answer += 1 20 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/greedy/조이스틱.py: -------------------------------------------------------------------------------- 1 | def solution(name): 2 | # 상하 이동 3 | up_down = [min(ord(n) - ord('A'), ord('Z') - ord(n) + 1) for n in name] 4 | 5 | idx, answer = 0, 0 6 | # 좌우 이동 7 | while True: 8 | answer += up_down[idx] 9 | up_down[idx] = 0 10 | if sum(up_down) == 0: 11 | return answer 12 | 13 | left, right = 1, 1 14 | while up_down[idx - left] == 0: 15 | left += 1 16 | while up_down[idx + right] == 0: 17 | right += 1 18 | answer += left if left < right else right 19 | idx += -left if left < right else right -------------------------------------------------------------------------------- /Programmers/suyeon/greedy/큰 수 만들기.py: -------------------------------------------------------------------------------- 1 | def solution(number, k): 2 | answer = [] # Stack 3 | 4 | for num in number: 5 | while k > 0 and answer and answer[-1] < num: 6 | answer.pop() 7 | k -= 1 8 | answer.append(num) 9 | 10 | return ''.join(answer[:len(answer) - k]) -------------------------------------------------------------------------------- /Programmers/suyeon/hash/베스트앨범.py: -------------------------------------------------------------------------------- 1 | def solution(genres, plays): 2 | genre_dict = {} 3 | play_dict = {} 4 | for i, genre_play in enumerate(zip(genres, plays)): 5 | genre, play = genre_play[0], genre_play[1] 6 | genre_dict[genre] = genre_dict.get(genre, 0) + play 7 | play_dict[genre] = play_dict.get(genre, []) + [(play, i)] 8 | 9 | genre_dict = dict(sorted(genre_dict.items(), key=lambda x: -x[1])) 10 | 11 | answer = [] 12 | for genre in genre_dict: 13 | _, idx = zip(*sorted(play_dict.get(genre), key=lambda x: -x[0])) 14 | answer += idx[:2] 15 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/hash/위장.py: -------------------------------------------------------------------------------- 1 | # Counter, reduce를 사용한 풀이도 가능 2 | # get 대신 defauldict 사용 가능 3 | 4 | def solution(clothes): 5 | dictionary = dict() 6 | for name, kind in clothes: 7 | dictionary[kind] = dictionary.get(kind, 1) + 1 8 | 9 | answer = 1 10 | for value in dictionary.values(): 11 | answer *= value 12 | return answer - 1 -------------------------------------------------------------------------------- /Programmers/suyeon/hash/전화번호 목록.py: -------------------------------------------------------------------------------- 1 | def solution(phone_book): 2 | phone_book.sort() 3 | 4 | for i, phone in enumerate(phone_book[:-1]): 5 | if phone == phone_book[i+1][:len(phone)]: 6 | return False 7 | return True -------------------------------------------------------------------------------- /Programmers/suyeon/heap/더 맵게.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | def solution(scoville, K): 4 | heapq.heapify(scoville) 5 | 6 | answer = 0 7 | while True: 8 | first = heapq.heappop(scoville) 9 | if not scoville: 10 | return -1 if first < K else answer 11 | elif first < K: 12 | second = heapq.heappop(scoville) 13 | heapq.heappush(scoville, first + second * 2) 14 | answer += 1 15 | else: 16 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/heap/디스크 컨트롤러.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | from heapq import heapify, heappop, heappush 3 | 4 | def solution(jobs): 5 | queue = deque(sorted(jobs)) 6 | 7 | heap = [] 8 | answer, count, now = 0, 0, 0 9 | while count < len(jobs): 10 | while queue and queue[0][0] <= now: 11 | call, time = queue.popleft() 12 | heappush(heap, (time, call)) 13 | 14 | if not heap: 15 | now = queue[0][0] 16 | else: 17 | time, call = heappop(heap) 18 | answer += time + (now - call) 19 | now += time 20 | count += 1 21 | return answer // count -------------------------------------------------------------------------------- /Programmers/suyeon/heap/이중우선순위큐.py: -------------------------------------------------------------------------------- 1 | from heapq import heapify, heappop, heappush 2 | 3 | def solution(operations): 4 | min_heap, max_heap = [], [] 5 | 6 | for op in operations: 7 | if op == "D 1": #최댓값 삭제 8 | if not max_heap: continue 9 | max_num = heappop(max_heap)[1] 10 | min_heap.remove(max_num) 11 | elif op == "D -1": #최솟값 삭제 12 | if not min_heap: continue 13 | min_num = heappop(min_heap) 14 | max_heap.remove((-min_num, min_num)) 15 | else: 16 | num = int(op[2:]) 17 | heappush(min_heap, num) 18 | heappush(max_heap, (-num, num)) 19 | 20 | return [max_heap[0][1], min_heap[0]] if max_heap and min_heap else [0, 0] -------------------------------------------------------------------------------- /Programmers/suyeon/sort/H-Index.py: -------------------------------------------------------------------------------- 1 | def solution(citations): 2 | citations.sort() 3 | 4 | n = len(citations) 5 | for i, citation in enumerate(citations): 6 | if citation >= n - i: 7 | return n - i 8 | return 0 -------------------------------------------------------------------------------- /Programmers/suyeon/sort/K번째수.py: -------------------------------------------------------------------------------- 1 | def solution(array, commands): 2 | return [sorted(array[i-1:j])[k-1] for i, j, k in commands] -------------------------------------------------------------------------------- /Programmers/suyeon/sort/가장 큰 수.py: -------------------------------------------------------------------------------- 1 | from functools import cmp_to_key 2 | 3 | def solution(numbers): 4 | numbers = [str(number) for number in numbers] 5 | # 음수, 양수, 0 6 | numbers.sort(key=cmp_to_key(lambda x, y: int(y+x)-int(x+y))) 7 | return ''.join(numbers) if numbers[0] != '0' else '0' -------------------------------------------------------------------------------- /Programmers/suyeon/stack_queue/주식가격.py: -------------------------------------------------------------------------------- 1 | # prices = {1, 2, 3, 2, 3, 1} return {5, 4, 1, 2, 1, 0} 2 | def solution(prices): 3 | length = len(prices) 4 | answer = [ i for i in range (length - 1, -1, -1)] 5 | 6 | stack = [0] 7 | for i in range (1, length, 1): 8 | # print(i, stack) 9 | while stack and prices[stack[-1]] > prices[i]: 10 | j = stack.pop() 11 | answer[j] = i - j 12 | # print(i, j, stack) 13 | stack.append(i) 14 | return answer -------------------------------------------------------------------------------- /Programmers/suyeon/stack_queue/프린터.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(priorities, location): 4 | queue = deque(priorities) 5 | 6 | answer = 0 7 | while location >= 0: 8 | left = queue.popleft() 9 | location -= 1 10 | 11 | check = False 12 | for q in queue: 13 | if(q > left): 14 | check = True 15 | break 16 | 17 | if check: 18 | queue.append(left) 19 | if location == -1: 20 | location = len(queue) - 1 21 | else: 22 | answer += 1 23 | return answer --------------------------------------------------------------------------------