├── .gitignore ├── LICENSE ├── README.md ├── cote-filelists.txt ├── notes ├── .DS_Store ├── Codingtest_Binarysearch.ipynb ├── Codingtest_DFS_BFS.ipynb ├── Codingtest_DynamicProgramming.ipynb ├── Codingtest_SamsungSW.ipynb ├── Codingtest_Sort.ipynb ├── Codingtest_shortest_path.ipynb ├── SWEA_핀볼 게임.py ├── baekjoon_nxm보드 완주하기_1회.py ├── baekjoon_감소하는 수.py ├── baekjoon_백트래킹_색종이 붙이기_풀이.py ├── baekjoon_파티_1회.py ├── baekjoon_팰린드롬2.py ├── baekjoon_합이 0인 네 정수.py ├── codility_구현_1.py ├── codingtest_greedy.ipynb ├── codingtest_implementation.ipynb ├── dp_연습.py ├── kakao_menu_combination.py ├── permutation_combination_implementation.ipynb ├── practice_per_com.py ├── programmers_스킬체크.py ├── programmers_스킬체크_3.py ├── programmers_스킬체크_3_2.py ├── samsung_DFS, 구현_프로세서 연결하기_수정풀이.py ├── samsung_낚시왕.py ├── samsung_미세먼지 안녕_1회.py ├── samsung_인구 이동.py ├── 그래프_위상정렬.py ├── 그래프_크루스칼_코드.py ├── 네이버_퍼즐조각채우기_미완.py ├── 다시풀기_baekjoon_파티.py ├── 모노미노도미노 2.py ├── 블로그풀이_삼성_실전_청소년상어.py ├── 어른 상어.py ├── 예제_개선된_다익스트라.py ├── 예제_개선된_다익스트라_실습.py ├── 예제_다익스트라.py ├── 예제_플로이드_워셜.py ├── 예제_플로이드_워셜_실습.py ├── 온풍기 안녕_2회.py ├── 이분탐색.py ├── 주사위 윷놀이.py ├── 주사위 윷놀이_풀이.py ├── 취코테_dfsbfs_16_연구소_책풀이.py ├── 취코테_greedy_6_무지의_먹방_라이브_힙풀이.py ├── 취코테_implementation_11_자물쇠와_열쇠_답안.py ├── 풀이_삼성_실전_청소년상어.py └── 프로그래머스_N으로표현_다시풀기.py ├── solution_codes ├── programmers_DP_여행_1회답.py ├── .DS_Store ├── .cph │ ├── .baekjoon_그래프_택배 배송_1회.py_093adbaa5e516587dd865784dc1d17d1.prob │ ├── .baekjoon_그래프_한 줄로 서기_1회.py_711d368afff42db7738278707241d7fe.prob │ ├── .baekjoon_도토리 숨기기.py_9a56cdd50204360fb5b72e9412fc266f.prob │ ├── .baekjoon_새로운 게임 2.py_afd3352f7cd570c0476f0be2319cefc9.prob │ ├── .baekjoon_소문난 칠공주.py_a8a019b4fa1325bee74fc2c72401df23.prob │ ├── .baekjoon_파티.py_ebb333dac39f09977e30581d746b2a4d.prob │ ├── .baekjoon_파티_1회.py_a41b0b419bf2e37251d365895082cb22.prob │ ├── .programmers_코딩테스트 연습.py_6787030bb9ab00932dcb167dd6d1e38b.prob │ ├── .samsung_BFS, 백트래킹_연구소 3_1회답.py_29755a22cef82696523091cbaf0583be.prob │ ├── .samsung_게리맨더링 2.py_75c49ec84b2a4c795b4ae48e721ce6ae.prob │ ├── .samsung_마법사 상어와 파이어스톰_1회.py_fa1a7bae419e81aba8f414df7af33770.prob │ ├── .samsung_시뮬레이션_큐빙_1회.py_170b6cfbe6aee8e07e107d0579499c4b.prob │ ├── .samsung_연구소 3_1회.py_1bfe2eae5840980e938e4809edc17378.prob │ └── .samsung_원판 돌리기_1회.py_4a5329be370bf33305f9394a6f864d76.prob ├── SWEA_DFS, 구현_프로세서 연결하기_1회답.py ├── SWEA_백트래킹, 구현_등산로 조성_1회.py ├── SWEA_시뮬레이션_핀볼 게임_1회.py ├── baekjoon_BFS_단지번호붙이기_1회.py ├── baekjoon_BFS_상범 빌딩_1회.py ├── baekjoon_BFS_스타트링크_1회답.py ├── baekjoon_DFS, BFS_바이러스_1회.py ├── baekjoon_DFS, BFS_벽 부수고 이동하기 4_1회답.py ├── baekjoon_DFS, BFS_회사문화1_1회답.py ├── baekjoon_DFS_색종이 만들기_1회.py ├── baekjoon_DP, 배낭문제_호텔_1회답.py ├── baekjoon_DP_RGB거리 2_1회답.py ├── baekjoon_DP_방 번호_1회답.py ├── baekjoon_DP_병사 배치하기_1회답.py ├── baekjoon_DP_색상환_1회답.py ├── baekjoon_DP_신나는 함수 실행_1회.py ├── baekjoon_DP_연속합_1회답.py ├── baekjoon_DP_정수 삼각형_1회.py ├── baekjoon_DP_팰린드롬?_1회답.py ├── baekjoon_DP_피보나치 수_1회.py ├── baekjoon_구현, 백트래킹_사다리 조작_1회답.py ├── baekjoon_구현_시험감독_1회답.py ├── baekjoon_구현_시험감독_2회.py ├── baekjoon_그래프_최단경로_1회답.py ├── baekjoon_그래프_택배 배송_1회.py ├── baekjoon_그래프_한 줄로 서기_1회.py ├── baekjoon_그리디_보석 도둑_1회답.py ├── baekjoon_백트래킹_색종이 붙이기_1회답.py ├── baekjoon_백트래킹_소문난 칠공주_1회답.py ├── baekjoon_브루트포스_하늘에서 별똥별이 빗발친다_1회.py ├── baekjoon_소수_소수 구하기_1회답.py ├── baekjoon_순열조합_암호 만들기_1회.py ├── baekjoon_시뮬레이션_미친 아두이노_1회.py ├── baekjoon_시뮬레이션_새로운 게임 2_1회.py ├── baekjoon_시뮬레이션_킹_1회.py ├── baekjoon_이분탐색_도토리 숨기기_1회답.py ├── baekjoon_이분탐색_흩날리는 시험지 속에서 내 평점이 느껴진거야_1회답.py ├── baekjoon_정규식_FBI_1회.py ├── baekjoon_정규식_javavsc_1회.py ├── baekjoon_정규식_모음의개수_1회.py ├── baekjoon_정규식_문서 검색_1회.py ├── baekjoon_정규식_창영이의일기장_1회.py ├── baekjoon_정규식_출력형식이잘못되었습니다_1회.py ├── baekjoon_최단거리_파티_1회.py ├── baekjoon_최단거리_파티_2회.py ├── baekjoon_투포인터_두 수의 합2_1회.py ├── baekjoon_투포인터_두 수의 합_1회.py ├── baekjoon_투포인터_두 용액_1회.py ├── baekjoon_투포인터_두 용액_2회.py ├── bookcodingtest_BFS_블록 이동하기_1회답.py ├── bookcodingtest_DP_금광_1회.py ├── bookcodingtest_DP_못생긴 수_1회.py ├── bookcodingtest_DP_편집 거리_1회답.py ├── bookcodingtest_dfsbfs_DFS와BFS_1회.py ├── bookcodingtest_dfsbfs_경쟁적전염_1회.py ├── bookcodingtest_dfsbfs_괄호변환_1회.py ├── bookcodingtest_dfsbfs_맥주마시면서걸어가기_1회.py ├── bookcodingtest_dfsbfs_미로탐색_1회.py ├── bookcodingtest_dfsbfs_빙산_1회.py ├── bookcodingtest_dfsbfs_연구소_1회.py ├── bookcodingtest_dfsbfs_연산자끼워넣기_1회.py ├── bookcodingtest_dfsbfs_특정거리의도시찾기_1회.py ├── bookcodingtest_구현_기둥과보설치_1회.py ├── bookcodingtest_구현_럭키스트레이트_1회.py ├── bookcodingtest_구현_문자열압축_1회.py ├── bookcodingtest_구현_문자열압축_2회.py ├── bookcodingtest_구현_문자열재정렬_1회.py ├── bookcodingtest_구현_뱀_1회.py ├── bookcodingtest_구현_외벽_점검_1회.py ├── bookcodingtest_구현_자물쇠와열쇠_1회.py ├── bookcodingtest_구현_치킨배달_1회.py ├── bookcodingtest_그래프_도시분할계획_1회.py ├── bookcodingtest_그래프_어두운길_1회.py ├── bookcodingtest_그래프_여행계획_1회.py ├── bookcodingtest_그래프_최종순위_1회답.py ├── bookcodingtest_그래프_커리큘럼_1회.py ├── bookcodingtest_그래프_탑승구_1회.py ├── bookcodingtest_그래프_팀결성_1회.py ├── bookcodingtest_그래프_행성터널_1회.py ├── bookcodingtest_그리디_곱하기혹은더하기_1회.py ├── bookcodingtest_그리디_만들수없는금액_1회.py ├── bookcodingtest_그리디_모험가 길드_1회답.py ├── bookcodingtest_그리디_무지의먹방라이브_1회.py ├── bookcodingtest_그리디_문자열뒤집기_1회.py ├── bookcodingtest_그리디_볼링공고르기_1회.py ├── bookcodingtest_이진탐색_가사검색_1회답.py ├── bookcodingtest_이진탐색_고정점찾기_1회.py ├── bookcodingtest_이진탐색_공유기설치_1회.py ├── bookcodingtest_이진탐색_특정수개수_1회.py ├── bookcodingtest_정렬_국영수_1회.py ├── bookcodingtest_정렬_실패율_1회.py ├── bookcodingtest_정렬_안테나_1회.py ├── bookcodingtest_정렬_카드정렬하기_1회.py ├── bookcodingtest_최단거리_플로이드_1회.py ├── bookcodingtest_최단경로_미래도시_1회.py ├── bookcodingtest_최단경로_숨바꼭질_1회.py ├── bookcodingtest_최단경로_전보_1회.py ├── bookcodingtest_최단경로_정확한순위_1회.py ├── bookcodingtest_최단경로_화성탐사_1회답.py ├── codility_정규식_LongestPassword_1회.py ├── coding-test-readme-generator.py ├── cote-filelists.txt ├── programmers_BFS_게임 맵 최단거리_1회답.py ├── programmers_BFS_내리막길_1회답.py ├── programmers_BFS_리코쳇 로봇_1회답.py ├── programmers_DFS,BFS_타겟 넘버_1회.py ├── programmers_DP_N으로 표현_1회답.py ├── programmers_DP_등굣길_1회.py ├── programmers_DP_빛의 경로 사이클_1회.py ├── programmers_DP_코딩테스트 연습_1회답.py ├── programmers_구현, 수학_교점에 별 만들기_1회.py ├── programmers_구현_스타 수열_1회답.py ├── programmers_그래프, dfs_네트워크_1회.py ├── programmers_그래프, dfs_네트워크_2회.py ├── programmers_그래프, 다익스트라_가장 먼 노드_1회답.py ├── programmers_그래프, 다익스트라_가장 먼 노드_2회.py ├── programmers_그래프_게임 개발_1회답.py ├── programmers_그래프_등산코스 정하기_1회.py ├── programmers_그래프_순위_1회답.py ├── programmers_그래프_합승 택시 요금_1회.py ├── programmers_그리디, 투포인터_두 큐 합 같게 만들기_1회답.py ├── programmers_그리디, 투포인터_두 큐 합 같게 만들기_2회답.py ├── programmers_그리디_체육복_1회.py ├── programmers_수학_124 나라의 숫자_1회.py ├── programmers_스택, 큐_같은 숫자는 싫어_1회.py ├── programmers_스택, 큐_기능개발_1회.py ├── programmers_스택, 큐_올바른 괄호_1회.py ├── programmers_스택, 큐_주식 가격_1회.py ├── programmers_스택, 큐_짝지어 제거하기_1회.py ├── programmers_스택, 큐_프린터_1회.py ├── programmers_시뮬레이션_주차 요금 계산_1회.py ├── programmers_완전탐색_모의고사_1회.py ├── programmers_완전탐색_소수 찾기_1회.py ├── programmers_완전탐색_최소직사각형_1회.py ├── programmers_완전탐색_카펫_1회.py ├── programmers_완전탐색_피로도_1회.py ├── programmers_이분탐색_입국심사_1회.py ├── programmers_이분탐색_입국심사_2회.py ├── programmers_카운터_시소 짝꿍_1회답.py ├── programmers_큐, 구현_행렬 테두리 회전하기_1회.py ├── programmers_투포인터_좋다_1회답.py ├── programmers_해시_오픈채팅방_1회.py ├── programmers_힙_더 맵게_1회.py ├── programmers_힙_디스크 컨트롤러_1회답.py ├── programmers_힙_이중우선순위큐_1회답.py ├── samsung_BFS, 백트래킹_연구소 3_1회답.py ├── samsung_BFSDFS, 구현_마법사상어와복제_1회답.py ├── samsung_BFS_구슬탈출2_1회답.py ├── samsung_DFSBFS, 구현_2048_1회답.py ├── samsung_DFSBFS, 구현_마법사상어와블리자드_1회.py ├── samsung_DFSBFS, 구현_마법사상어와블리자드_2회.py ├── samsung_DFSBFS, 구현_상어중학교_1회.py ├── samsung_DFSBFS, 구현_아기상어_1회.py ├── samsung_DFSBFS, 구현_온풍기 안녕_1회.py ├── samsung_DFSBFS, 구현_온풍기 안녕_2회답.py ├── samsung_DFSBFS, 구현_주사위굴리기2_1회.py ├── samsung_DFSBFS, 구현_주사위굴리기_1회.py ├── samsung_DFSBFS, 구현_청소년상어_1회.py ├── samsung_DFSBFS, 구현_테트로미노_1회.py ├── samsung_DFSBFS, 구현_테트로미노_2회.py ├── samsung_DFSBFS, 구현_퇴사_1회.py ├── samsung_DFSBFS, 구현_퇴사_2회.py ├── samsung_dfs, 백트래킹_스타트와 링크_1회답.py ├── samsung_구현, DFS_감시_1회답.py ├── samsung_구현_경사로_1회.py ├── samsung_구현_나무박멸_1회.py ├── samsung_구현_어항 정리_1회.py ├── samsung_구현_톱니바퀴_1회.py ├── samsung_시뮬레이션_나무 재테크_1회.py ├── samsung_시뮬레이션_낚시왕_1회.py ├── samsung_시뮬레이션_놀이기구 탑승_1회.py ├── samsung_시뮬레이션_돌아가는 팔각의자_1회.py ├── samsung_시뮬레이션_드래곤 커브_1회.py ├── samsung_시뮬레이션_로봇 청소기_1회답.py ├── samsung_시뮬레이션_마법사 상어와 파이어스톰_1회.py ├── samsung_시뮬레이션_모노미노도미노 2_1회.py ├── samsung_시뮬레이션_미세먼지 안녕_1회.py ├── samsung_시뮬레이션_스타트 택시_1회답.py ├── samsung_시뮬레이션_아기 상어_1회.py ├── samsung_시뮬레이션_어른 상어_1회.py ├── samsung_시뮬레이션_원판 돌리기_1회.py ├── samsung_시뮬레이션_이차원 배열과 연산_1회.py ├── samsung_시뮬레이션_자율주행 자동차_1회.py ├── samsung_시뮬레이션_주사위 윷놀이_1회답.py ├── samsung_시뮬레이션_캐슬 디펜스_1회답.py ├── samsung_시뮬레이션_컨베이어 벨트 위의 로봇_1회.py ├── samsung_시뮬레이션_큐빙_1회.py ├── samsung_완전탐색_게리맨더링 2_1회.py ├── sql_GROUP BY_동명 동물 수 찾기_1회.sql ├── sql_GROUP BY_저자 별 카테고리 별 매출액 집계하기_1회.sql ├── sql_GROUP BY_즐겨찾기가 가장 많은 식당 정보 출력하기_1회.sql ├── sql_JOIN_없어진 기록 찾기_1회.sql ├── sql_JOIN_특정 기간동안 대여 가능한 자동차들의 대여비용 구하기_1회.sql ├── sql_SELECT, UNION_오프라인 온라인 판매 데이터 통합하기_1회답.sql ├── sql_STRING_조건에 맞는 사용자 정보 조회하기_1회답.sql └── sql_STRING_조회수가 가장 많은 중고거래 게시판의 첨부파일 조회하기_1회답.sql └── temp ├── baekjoon_녹색 옷 입은 애가 젤다지.py ├── baekjoon_숨바꼭질 3.py └── baekjoon_좋다.py /.gitignore: -------------------------------------------------------------------------------- 1 | temp/ 2 | 3 | .DS_Store 4 | .idea 5 | .ipynb_checkpoints 6 | .vscode -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2022 Wooseok Park 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /cote-filelists.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hoeen/coding_test_training/b0ffdd467259e3b043d699a13636a87a8089a681/cote-filelists.txt -------------------------------------------------------------------------------- /notes/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hoeen/coding_test_training/b0ffdd467259e3b043d699a13636a87a8089a681/notes/.DS_Store -------------------------------------------------------------------------------- /notes/baekjoon_감소하는 수.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | # import time 3 | 4 | ans_list = [0] 5 | len = 1 6 | while len < 11: 7 | 8 | for i in range(1, 10): 9 | if len > i+1: continue 10 | for aft_num in combinations(list(range(i-1, -1, -1)),len-1): # 자릿수 - 1 만큼 경우의수 11 | num = str(i) 12 | for an in aft_num: 13 | num += str(an) 14 | ans_list.append(int(num)) 15 | 16 | len += 1 17 | 18 | ans_list.sort() 19 | 20 | try: 21 | print(ans_list[int(input())]) 22 | except: 23 | print(-1) 24 | -------------------------------------------------------------------------------- /notes/baekjoon_백트래킹_색종이 붙이기_풀이.py: -------------------------------------------------------------------------------- 1 | # board = [list(map(int, input().split())) for _ in range(10)] 2 | import time 3 | 4 | papers = [0, 5, 5, 5, 5, 5] 5 | result = set() # 자동 중복 방지 6 | 7 | board = [ 8 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 9 | [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], 10 | [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], 11 | [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], 12 | [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], 13 | [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], 14 | [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], 15 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 17 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 18 | ] 19 | 20 | 21 | def find_length(y, x): 22 | length = 1 23 | for l in range(2, min(10 - y, 10 - x, 5) + 1): 24 | for i in range(y, y+l): 25 | for j in range(x, x+l): 26 | if board[i][j] == 0: 27 | return length # 1이 아니면 최대 범위로 설정 28 | length += 1 29 | return length 30 | 31 | def cover(y, x, length): 32 | for i in range(y, y + length): 33 | for j in range(x, x + length): 34 | board[i][j] = 0 35 | 36 | def uncover(y, x, length): 37 | for i in range(y, y + length): 38 | for j in range(x, x + length): 39 | board[i][j] = 1 40 | 41 | def dfs(cnt): 42 | 43 | for i in range(0, 10): 44 | for j in range(0, 10): 45 | if board[i][j] == 1: 46 | length = find_length(i, j) 47 | for l in range(length, 0, -1): 48 | if papers[l]: 49 | cover(i, j, l) 50 | papers[l] -= 1 51 | 52 | time.sleep(0.5) 53 | print('check') 54 | for b in board: 55 | print(b) 56 | print(papers) 57 | 58 | 59 | 60 | result.add(dfs(cnt + 1)) 61 | uncover(i, j, l) 62 | papers[l] += 1 63 | if result: 64 | return min(result) 65 | else: 66 | return -1 67 | return cnt 68 | 69 | result.add(dfs(0)) 70 | if -1 in result: 71 | result.remove(-1) 72 | print(min(result) if result else -1) -------------------------------------------------------------------------------- /notes/baekjoon_파티_1회.py: -------------------------------------------------------------------------------- 1 | # ~4:40 2 | # 그래프 문제? 3 | import heapq 4 | 5 | n, m, x = map(int, input().split()) 6 | #start, end, cost 7 | inp_list = [list(map(int, input().split())) for _ in range(m)] 8 | graph = [[] for _ in range(n+1)] 9 | for start, end, cost in inp_list: 10 | graph[start].append((end, cost)) 11 | 12 | # 다익스트라 - i번째 마을에서 X번 마을로 갔다가, 다시 i로 돌아오는 최단거리 13 | INF = int(1e9) 14 | 15 | # for start, end, cost in graph: 16 | def dijkstra(start): 17 | # heap 에 스타트 삽입 18 | q = [] 19 | dist = [INF]*(n+1) 20 | dist[start] = 0 21 | heapq.heappush(q, (0, start)) 22 | 23 | while q: 24 | dist_now, node_now = heapq.heappop(q) 25 | if dist[node_now] < dist_now: 26 | continue 27 | for node_next, dist_next in graph[node_now]: 28 | cost = dist_next + dist[node_now] 29 | if dist[node_next] > cost: 30 | dist[node_next] = cost 31 | heapq.heappush(q, (cost, node_next)) 32 | 33 | return dist 34 | 35 | total_dist = [0]*(n+1) 36 | for i in range(1, n+1): 37 | total_dist[i] += dijkstra(i) 38 | # print('godist:', godist) 39 | total_dist[i] += dijkstra(x)[i] 40 | backdist = dijkstra(x, backdist) 41 | # print('backdist:', backdist) 42 | total_dist[i] += backdist[i] 43 | 44 | print(total_dist) 45 | print(max(total_dist)) -------------------------------------------------------------------------------- /notes/baekjoon_팰린드롬2.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | seq = list(map(int, input().split())) 3 | m = int(input()) 4 | 5 | dp_tab = [[False]*(n) for _ in range(n)] 6 | 7 | for _ in range(m): 8 | s, e = map(int, input().split()) 9 | s, e = s-1, e-1 10 | 11 | ns, ne = s, e 12 | exited = False 13 | while ne - ns >= 1: 14 | if dp_tab[ns][ne]: 15 | dp_tab[s][e] = dp_tab[ns][ne] 16 | print(dp_tab[ns][ne]) 17 | exited = True 18 | break 19 | else: 20 | if seq[ns] == seq[ne]: 21 | ns += 1 22 | ne -= 1 23 | else: 24 | exited = True 25 | dp_tab[s][e] = 0 26 | print(0) 27 | break 28 | if not exited: 29 | print(1) 30 | dp_tab[s][e] = 1 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /notes/baekjoon_합이 0인 네 정수.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | 3 | A, B, C, D = list(), list(), list(), list() 4 | 5 | # print(list(map(int, input().split()))) 6 | 7 | for _ in range(n): 8 | a, b, c, d = map(int, input().split()) 9 | A.append(a) 10 | B.append(b) 11 | C.append(c) 12 | D.append(d) 13 | 14 | A.sort() 15 | B.sort() 16 | C.sort() 17 | D.sort() 18 | 19 | count = 0 20 | for a in A: 21 | for b in B: 22 | for c in C: 23 | if a+b+c+max(D) < 0: 24 | # print('impossible') 25 | continue 26 | else: 27 | for d in D: 28 | # print(a,b,c,d) 29 | if a+b+c+d == 0: 30 | # print('count+1') 31 | count += 1 32 | elif a+b+c+d > 0: 33 | # print('morethan0') 34 | break # 다음 a,b,c에서 시작 35 | 36 | print(count) -------------------------------------------------------------------------------- /notes/codility_구현_1.py: -------------------------------------------------------------------------------- 1 | A = [1,3,2,1,2,1,5,3,3,4,2] 2 | 3 | # max_cand = [] 4 | # def binary_search(array, value, start, end): 5 | # if start > end: 6 | # return None 7 | # else: 8 | # mid = (start + end) // 2 9 | # # 왼쪽 최댓값 10 | # max_left = max(array[start:mid]) 11 | # # 오른쪽 최댓값 12 | # max_right = max(array[mid+1:end]) 13 | 14 | for rock in A: 15 | 16 | -------------------------------------------------------------------------------- /notes/dp_연습.py: -------------------------------------------------------------------------------- 1 | def fibo(x, memo={}): # x번째 수 피보나치 - 탑다운, 메모이제이션 2 | if x in memo: 3 | return memo[x] 4 | else: 5 | if x <= 0: 6 | return False 7 | elif x == 1 or x == 2: 8 | ans = 1 9 | memo[x] = ans 10 | return ans 11 | else: 12 | # f(k+1) = f(k) + f(k-1) 13 | ans = fibo(x-2,memo) + fibo(x-1,memo) 14 | memo[x] = ans 15 | return ans 16 | 17 | def fibo_tab(x): # x번째 수 반환 18 | tab = [0]*x 19 | tab[0] = 1 20 | tab[1] = 1 21 | for i in range(x-2): # 0~x-1 22 | tab[i+2] = tab[i] + tab[i+1] 23 | return tab[x-1] 24 | 25 | import time 26 | t0 = time.time() 27 | print(fibo(1500)) 28 | print(time.time() - t0) 29 | t0 = time.time() 30 | print(fibo_tab(1500)) 31 | print(time.time() - t0) 32 | 33 | 34 | 35 | 36 | 37 | # 1 1 2 3 5 8 13 21 34 55 89 144 -------------------------------------------------------------------------------- /notes/kakao_menu_combination.py: -------------------------------------------------------------------------------- 1 | def solution(orders, course): 2 | import itertools 3 | 4 | def match_char(a,b,n): 5 | match = ''.join([i for i in a if i in b]) 6 | result = list(itertools.combinations(list(match),n)) # 조합으로 개수에 맞는 쌍 생성 7 | 8 | if len(result)>=1: 9 | return [''.join(sorted(list(result[i]))) for i in range(len(result))] 10 | else: 11 | return '' 12 | # 개수 정해진 경우 : 값을 개수에 맞게 조합으로 나눈다. 13 | 14 | ex1 = orders 15 | tot_menu_list = [] 16 | for i in range(len(ex1)-1): 17 | 18 | for num in course: 19 | course_num_list = [] 20 | for j in range(1,len(ex1)-i): 21 | course_num_list+=match_char(ex1[i],ex1[i+j],num) 22 | tot_menu_list+=course_num_list 23 | 24 | 25 | value_count = {} 26 | for n in set(tot_menu_list): 27 | value_count[n] = tot_menu_list.count(n) 28 | #course 수마다 뽑아서 제일 큰 값을 갖는걸 찾는다. 딕셔너리 이용? 29 | 30 | 31 | # 개수별로 뽑아서 제일 큰값 갖는걸 찾기 32 | final = [] 33 | for num in course: 34 | max_num = 0 35 | for cs in list(value_count.keys()): 36 | if len(cs) == num: 37 | if tot_menu_list.count(cs) > max_num: 38 | max_num = tot_menu_list.count(cs) 39 | 40 | final+=[i for i in list(value_count.keys()) if (len(i) == num) & (tot_menu_list.count(i) == max_num)] 41 | 42 | answer = sorted(final) 43 | return answer 44 | -------------------------------------------------------------------------------- /notes/practice_per_com.py: -------------------------------------------------------------------------------- 1 | def perm(input_list, n): 2 | result = [] 3 | if len(input_list) < n: 4 | return result 5 | elif n == 1: 6 | for i in input_list: 7 | result.append([i]) 8 | elif n > 1: 9 | for j in range(len(input_list)): 10 | temp = [k for k in input_list] 11 | temp.remove(input_list[j]) 12 | for p in perm(temp, n-1): 13 | result.append([input_list[j]] + p) 14 | return result 15 | 16 | 17 | 18 | print(perm([1,2,3,4], 3)) -------------------------------------------------------------------------------- /notes/programmers_스킬체크.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | def solution(scoville, K): 4 | answer = 0 5 | scoville.sort() 6 | while scoville[0] < K: 7 | if len(scoville) == 2 and min(scoville) + 2*max(scoville) < K: 8 | return -1 9 | s1 = heapq.heappop(scoville) 10 | s2 = heapq.heappop(scoville) 11 | s_new = s1 + (s2*2) 12 | heapq.heappush(scoville, s_new) 13 | answer += 1 14 | return answer 15 | 16 | 17 | # def solution(scoville, K): 18 | # answer = 0 19 | # scoville.sort() 20 | # while scoville[0] < K: 21 | # if len(scoville) == 2 and scoville[0] + 2*scoville[1] < K: 22 | # return -1 23 | # s1 = scoville.pop(0) 24 | # s2 = scoville.pop(0) 25 | # s_new = s1 + (s2*2) 26 | # scoville.insert(0,s_new) 27 | # scoville.sort() 28 | # answer += 1 29 | # return answer -------------------------------------------------------------------------------- /notes/programmers_스킬체크_3.py: -------------------------------------------------------------------------------- 1 | def find_parent(parent, x): 2 | if parent[x] != x: 3 | parent[x] = find_parent(parent, parent[x]) 4 | return parent[x] 5 | 6 | def union_parent(a, b, parent): 7 | 8 | a = find_parent(parent, a) 9 | b = find_parent(parent, b) 10 | if a < b: 11 | parent[b] = a 12 | else: 13 | parent[a] = b 14 | 15 | def solution(n, costs): 16 | answer = 0 17 | parent = list(range(0, n)) 18 | 19 | costs.sort(key=lambda x: x[2]) #맨 뒤 cost가 짧은것부터 정렬 20 | 21 | for a, b, cost in costs: 22 | if find_parent(parent, a) != find_parent(parent, b): 23 | union_parent(a, b, parent) 24 | answer += cost 25 | 26 | return answer 27 | 28 | print(solution(4, [[0,1,1],[0,2,2],[1,2,5],[1,3,1],[2,3,8]])) 29 | 30 | 31 | 32 | n행 m열의 격자가 있습니다. 격자의 각 행은 0, 1, ..., n-1번의 번호, 그리고 각 열은 0, 1, ..., m-1번의 번호가 순서대로 매겨져 있습니다. 당신은 이 격자에 공을 하나 두고, 그 공에 다음과 같은 쿼리들을 날리고자 합니다. 33 | 열 번호가 감소하는 방향으로 dx칸 이동하는 쿼리 (query(0, dx)) 34 | 열 번호가 증가하는 방향으로 dx칸 이동하는 쿼리 (query(1, dx)) 35 | 행 번호가 감소하는 방향으로 dx칸 이동하는 쿼리 (query(2, dx)) 36 | 행 번호가 증가하는 방향으로 dx칸 이동하는 쿼리 (query(3, dx)) 37 | 단, 공은 격자 바깥으로 이동할 수 없으며, 목적지가 격자 바깥인 경우 공은 이동하다가 더 이상 이동할 수 없을 때 멈추게 됩니다. 예를 들어, 5행 × 4열 크기의 격자 내의 공이 3행 2열에 있을 때 query(3, 10) 쿼리를 받은 경우 공은 4행 2열에서 멈추게 됩니다. (격자의 크기가 5행 × 4열이므로, 0~4번 행과 0~3번 열로 격자가 구성되기 때문입니다.) 38 | 격자의 행의 개수 n, 열의 개수 m, 정수 x와 y, 그리고 쿼리들의 목록을 나타내는 2차원 정수 배열 queries가 매개변수로 주어집니다. n × m개의 가능한 시작점에 대해서 해당 시작점에 공을 두고 queries 내의 쿼리들을 순서대로 시뮬레이션했을 때, x행 y열에 도착하는 시작점의 개수를 return 하도록 solution 함수를 완성해주세요. 39 | 제한사항 40 | 1 ≤ n ≤ 109 41 | 1 ≤ m ≤ 109 42 | 0 ≤ x < n 43 | 0 ≤ y < m 44 | 1 ≤ queries의 행의 개수 ≤ 200,000 45 | queries의 각 행은 [command,dx] 두 정수로 이루어져 있습니다. 46 | 0 ≤ command ≤ 3 47 | 1 ≤ dx ≤ 109 48 | 이는 query(command, dx)를 의미합니다. 49 | 입출력 예 50 | n m x y queries result 51 | 2 2 0 0 [[2,1],[0,1],[1,1],[0,1],[2,1]] 4 52 | 2 5 0 1 [[3,1],[2,2],[1,1],[2,3],[0,1],[2,1]] 2 53 | 입출력 예 설명 54 | 입출력 예 #1 55 | 다음 애니메이션은 4개의 가능한 시작점에 대한 모든 시뮬레이션을 나타낸 것입니다. 56 | ex1 57 | 어떤 곳에서 출발하더라도 항상 0행 0열에 도착하기 때문에, 4를 return 해야 합니다. 58 | 입출력 예 #2 59 | 다음 애니메이션은 10개의 가능한 시작점에 대한 모든 시뮬레이션을 나타낸 것입니다. -------------------------------------------------------------------------------- /notes/programmers_스킬체크_3_2.py: -------------------------------------------------------------------------------- 1 | def solution(n, m, x, y, queries): 2 | dx = (0, 0, -1, 1) 3 | dy = (-1, 1, 0, 0) 4 | x0, y0 = x, y 5 | # board = [[1]*m for _ in range(n)] 6 | board = [[0]*m for _ in range(n)] 7 | for x in range(n): 8 | for y in range(m): 9 | for way, dist in queries: 10 | nx, ny = x + dx[way]*dist, y + dy[way]*dist 11 | if nx < 0: 12 | nx = 0 13 | if ny < 0: 14 | ny = 0 15 | if nx > n-1: 16 | nx = n-1 17 | if ny > m-1: 18 | ny = m-1 19 | board[nx][ny] += 1 20 | 21 | answer = board[x0][y0] 22 | 23 | for b in board: 24 | print(b) 25 | 26 | 27 | 28 | return answer 29 | 30 | solution(2, 2, 0, 0, [[2, 1], [0, 1], [1, 1], [0, 1], [2, 1]]) -------------------------------------------------------------------------------- /notes/그래프_위상정렬.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | # 노드, 간선 입력받기 4 | v, e = map(int, input().split()) 5 | # 모든 노드 진입차수 0으로 초기화 6 | indegree = [0] * (v+1) 7 | # 각 노드 연결 리스트 초기화 8 | graph = [[] for _ in range(v+1)] 9 | 10 | # 모든 간선 정보 입력받기 11 | for _ in range(e): 12 | a, b = map(int, input().split()) 13 | graph[a].append(b) 14 | # 진입차수를 1 증가 15 | indegree[b] += 1 16 | 17 | # 위상 정렬 함수 18 | def topology_sort(): 19 | result = [] 20 | q = deque() 21 | 22 | # 처음 시작할 때는 차수 0인 노드 큐 삽입 23 | for i in range(1, v+1): 24 | if indegree[i] == 0: 25 | q.append(i) 26 | 27 | # 큐가 빌 때까지 반복 28 | while q: 29 | now = q.popleft() 30 | result.append(now) # 큐에 들어간 노드 순서대로 출력하면됨 31 | # 해당 원소와 연결된 노드 진입차수에서 1 빼기 32 | for i in graph[now]: 33 | indegree[i] -= 1 34 | # 새롭게 진입차수 0이 되는 노드를 큐에 삽입 35 | if indegree[i] == 0: 36 | q.append(i) 37 | 38 | for i in result: 39 | print(i, end=' ') 40 | 41 | topology_sort() -------------------------------------------------------------------------------- /notes/그래프_크루스칼_코드.py: -------------------------------------------------------------------------------- 1 | # 신장 트리 - 크루스칼 알고리즘 2 | def find_parent(parent, x): 3 | if parent[x] != x: 4 | parent[x] = find_parent(parent, parent[x]) 5 | return parent[x] 6 | 7 | def union_parent(parent, a, b): 8 | a = find_parent(parent, a) 9 | b = find_parent(parent, b) 10 | if a < b: 11 | parent[b] = a 12 | else: 13 | parent[a] = b 14 | 15 | # 노드와 간선의 개수 16 | v, e = map(int, input().split()) 17 | parent = [0] * (v+1) 18 | 19 | # 모든 간선을 담을 리스트와 최종 비용을 담을 변수 20 | edges = [] 21 | result = 0 22 | 23 | # 부모 테이블 상에서 부모를 자기 자신으로 초기화 24 | for i in range(1, v+1): 25 | parent[i] = i 26 | 27 | # 모든 간선에 대한 정보 28 | for _ in range(e): 29 | a, b, cost = map(int, input().split()) 30 | # 비용순으로 정렬위해서 첫번째 원소를 비용으로 설정 31 | edges.append((cost, a, b)) 32 | 33 | # 간선을 비용순으로 정렬 34 | edges.sort() 35 | 36 | for edge in edges: 37 | cost, a, b = edge 38 | # 사이클이 발생하지 않는 경우에만 집합에 포함 39 | if find_parent(parent, a) != find_parent(parent, b): 40 | union_parent(parent, a, b) 41 | result += cost 42 | 43 | print(result) 44 | -------------------------------------------------------------------------------- /notes/다시풀기_baekjoon_파티.py: -------------------------------------------------------------------------------- 1 | # 플로이드 워셜 2 | 3 | n, m, x = map(int, input().split()) 4 | 5 | INF = int(1e9) 6 | graph = [[INF]*(n+1) for _ in range(n+1)] 7 | 8 | 9 | for i in range(m): 10 | start, end, cost = map(int, input().split()) 11 | graph[start][end] = cost 12 | 13 | for i in range(n+1): 14 | for j in range(n+1): 15 | if i==j: 16 | graph[i][j] = 0 17 | 18 | for k in range(1, n+1): 19 | for start in range(1, n+1): 20 | for end in range(1, n+1): 21 | graph[start][end] = min(graph[start][end], graph[start][k]+graph[k][end]) 22 | 23 | 24 | max_dist = 0 25 | for i in range(1, n+1): 26 | go_back = graph[i][x] + graph[x][i] 27 | if go_back > max_dist: 28 | max_dist = go_back 29 | 30 | print(max_dist) 31 | 32 | -------------------------------------------------------------------------------- /notes/블로그풀이_삼성_실전_청소년상어.py: -------------------------------------------------------------------------------- 1 | # 청소년 상어 - BOJ 19236 2 | # DFS+구현 3 | import copy 4 | 5 | board = [[] for _ in range(4)] 6 | 7 | dx = [-1, -1, 0, 1, 1, 1, 0, -1] 8 | dy = [0, -1, -1, -1, 0, 1, 1, 1] 9 | 10 | for i in range(4): 11 | data = list(map(int, input().split())) 12 | fish = [] 13 | for j in range(4): 14 | # 물고기 번호, 방향 15 | fish.append([data[2*j], data[2*j+1]-1]) 16 | board[i] = fish 17 | 18 | 19 | max_score = 0 20 | 21 | 22 | def dfs(sx, sy, score, board): 23 | global max_score 24 | score += board[sx][sy][0] 25 | max_score = max(max_score, score) 26 | board[sx][sy][0] = 0 27 | 28 | # 물고기 움직임 29 | for f in range(1, 17): 30 | f_x, f_y = -1, -1 31 | for x in range(4): 32 | for y in range(4): 33 | if board[x][y][0] == f: 34 | f_x, f_y = x, y 35 | break 36 | if f_x == -1 and f_y == -1: 37 | continue 38 | f_d = board[f_x][f_y][1] 39 | 40 | for i in range(8): 41 | nd = (f_d+i) % 8 42 | nx = f_x + dx[nd] 43 | ny = f_y + dy[nd] 44 | if not (0 <= nx < 4 and 0 <= ny < 4) or (nx == sx and ny == sy): 45 | continue 46 | board[f_x][f_y][1] = nd 47 | board[f_x][f_y], board[nx][ny] = board[nx][ny], board[f_x][f_y] 48 | break 49 | 50 | # 상어 먹음 51 | s_d = board[sx][sy][1] 52 | for i in range(1, 5): 53 | nx = sx + dx[s_d]*i 54 | ny = sy + dy[s_d]*i 55 | if (0<= nx < 4 and 0<= ny < 4) and board[nx][ny][0] > 0: 56 | dfs(nx, ny, score, copy.deepcopy(board)) 57 | 58 | dfs(0, 0, 0, board) 59 | print(max_score) -------------------------------------------------------------------------------- /notes/예제_개선된_다익스트라.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 직관적 다익스트라는 시간복잡도가 O(V^2)이다. 3 | 개선된 다익스트라는 시간복잡도가 O(ElogV)이다. E는 간선, V는 노드 4 | 최단거리가 가장 짧은 노드를 찾기 위해서 매번 최단 거리 테이블을 선형적으로 탐색하는 기존방법에 비해, 5 | heapq(우선순위 큐)를 이용하여 더 빨리 탐색이 가능하다. - 우선순위 큐는 우선순위가 제일 높은 데이터를 먼저 꺼냄. 6 | BFS 의 원리와 비슷하게 동작한다. 7 | ''' 8 | 9 | import heapq 10 | 11 | INF = int(1e9) 12 | 13 | n, m = map(int, input().split()) 14 | start = int(input()) 15 | 16 | graph = [[] for i in range(n+1)] 17 | distance = [INF] * (n+1) 18 | 19 | for _ in range(m): 20 | a, b, c = map(int, input().split()) 21 | graph[a].append((b,c)) 22 | 23 | def dijkstra(start): 24 | q = [] 25 | # 시작 노드 최단 경로는 0으로 설정. 큐에 삽입 26 | heapq.heappush(q, (0,start)) 27 | distance[start] = 0 28 | while q: 29 | # 가장 최단 거리 짧은 노드 정보 꺼내기. 여기에서 get_smallest_node()를 따로 작성할필요가 없음. 30 | dist, now = heapq.heappop(q) 31 | # 현재 노드가 처리된 적이 있는 노드면 무시 32 | if distance[now] < dist: 33 | continue 34 | # 현재와 인접한 다른 노드를 확인 35 | for i in graph[now]: 36 | cost = dist + i[1] 37 | # 현재 노드 거치는게 더 짧은 경우 38 | if cost < distance[i[0]]: 39 | distance[i[0]] = cost 40 | heapq.heappush(q, (cost, i[0])) 41 | 42 | dijkstra(start) 43 | 44 | # 모든 노드로 가기 위한 최단거리 출력 45 | for i in range(1, n+1): 46 | if distance[i] == INF: 47 | print('INFINITY') 48 | else: 49 | print(distance[i]) 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /notes/예제_개선된_다익스트라_실습.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | # 6 11 4 | # 1 5 | n, k = map(int, input().split()) 6 | start = int(input()) 7 | INF = int(1e9) 8 | dist = [INF]*(n+1) 9 | 10 | 11 | graph = [[] for _ in range(n+1)] 12 | for _ in range(k): 13 | a, b, c = map(int, input().split()) 14 | graph[a].append((b,c)) 15 | 16 | def dijkstra(start): 17 | q = [] 18 | dist[start] = 0 19 | heapq.heappush(q, (0, start)) 20 | while q: 21 | distance, now = heapq.heappop(q) 22 | if dist[now] < distance: 23 | continue 24 | for b, c in graph[now]: # now로부터 다음, 거리 25 | cost = distance + c 26 | if cost < dist[b]: 27 | dist[b] = cost 28 | heapq.heappush(q, (cost, b)) 29 | 30 | dijkstra(start) 31 | 32 | for d in dist[1:]: 33 | print(d) 34 | 35 | 36 | -------------------------------------------------------------------------------- /notes/예제_다익스트라.py: -------------------------------------------------------------------------------- 1 | import sys 2 | # input = sys.stdin.readline() 3 | INF = int(1e9) 4 | 5 | n, m = map(int, input().split()) 6 | start = int(input()) 7 | 8 | graph = [[] for _ in range(n+1)] 9 | visited = [False]*(n+1) 10 | distance = [INF] * (n+1) 11 | 12 | # 간선 정보 입력받기 13 | for _ in range(m): 14 | a, b, c = map(int, input().split()) 15 | graph[a].append((b,c)) 16 | 17 | # 방문하지 않은 노드 중에서 가장 최단거리가 짧은 노드의 번호를 반환 18 | def get_smallest_node(): 19 | min_value = INF 20 | index = 0 21 | for i in range(1, n+1): 22 | if distance[i] < min_value and not visited[i]: 23 | min_value = distance[i] 24 | index = i 25 | return index 26 | 27 | def dijkstra(start): 28 | distance[start] = 0 29 | visited[start] = True 30 | for j in graph[start]: # j = (목적지, 거리) 31 | distance[j[0]] = j[1] 32 | # 시작 노드를 제외한 전체 n-1개 노드에 대해 반복 33 | for i in range(n-1): 34 | # 현재 최단거리 가장 짧은 노드 꺼내서 방문처리 35 | now = get_smallest_node() 36 | visited[now] = True 37 | # 현재 노드와 연결된 다른 노드를 확인 38 | for j in graph[now]: # j = (목적지, 거리) 39 | cost = distance[now] + j[1] # 거리를 더함 40 | # 현재 노드를 거쳐가는게 더 짧은 경우 41 | if cost < distance[j[0]]: 42 | distance[j[0]] = cost 43 | 44 | dijkstra(start) 45 | 46 | for i in range(1, n+1): 47 | # 도달 못하는 경우 무한 출력 48 | if distance[i] == INF: 49 | print('INFINITY') 50 | else: 51 | print(distance[i]) 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /notes/예제_플로이드_워셜.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 플로이드 워셜 - 모든 지점에서 다른 모든 지점까지의 최단 경로를 모두 구해야 할 경우에 이용하는 알고리즘 3 | 다익스트라와 다르게, 2차원 배열에 거리정보를 저장한다. 다이나믹 프로그래밍으로 구현. 4 | ''' 5 | 6 | INF = int(1e9) 7 | 8 | n = int(input()) 9 | m = int(input()) 10 | 11 | graph = [[INF] * (n+1) for _ in range(n+1)] 12 | 13 | for a in range(1, n+1): 14 | for b in range(1, n+1): 15 | if a == b: 16 | graph[a][b] = 0 17 | 18 | for _ in range(m): 19 | a, b, c = map(int, input().split()) 20 | graph[a][b] = c 21 | 22 | # 점화식에 따라 플로이드 워셜 알고리즘을 수행 23 | for k in range(1, n+1): 24 | for a in range(1, n+1): 25 | for b in range(1, n+1): 26 | graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b]) 27 | 28 | # 수행된 결과를 출력 29 | for a in range(1, n+1): 30 | for b in range(1, n+1): 31 | if graph[a][b] == INF: 32 | print('INFINITY', end=' ') 33 | else: 34 | print(graph[a][b], end=' ') 35 | print() -------------------------------------------------------------------------------- /notes/예제_플로이드_워셜_실습.py: -------------------------------------------------------------------------------- 1 | # 점화식 2 | n = int(input()) 3 | k = int(input()) 4 | 5 | INF = int(1e9) 6 | graph = [[INF]*(n+1) for _ in range(n+1)] 7 | for _ in range(k): 8 | a, b, c = map(int, input().split()) 9 | graph[a][b] = c 10 | for x in range(n+1): 11 | for y in range(n+1): 12 | if x == y: 13 | graph[x][y] = 0 14 | 15 | # 점화식 -> fab = min(fab, fak+fkb) 16 | for k in range(1,n+1): 17 | for x in range(1, n+1): 18 | for y in range(1, n+1): 19 | graph[x][y] = min(graph[x][y], graph[x][k]+graph[k][y]) 20 | 21 | for g in graph[1:]: 22 | print(g[1:]) 23 | -------------------------------------------------------------------------------- /notes/이분탐색.py: -------------------------------------------------------------------------------- 1 | # 13:00 시작 2 | n, m, l = map(int, input().split()) 3 | 4 | loc = list(map(int ,input().split())) 5 | 6 | start = 0 7 | end = l 8 | 9 | # 남아 있는 휴게소 중 10 | 11 | 12 | 13 | 14 | # m개 휴게소 짓고 나서 휴게소 없는 구간 최댓값이 최소가 되도록. 이를 출력 15 | loc.sort() 16 | # 처음과 끝점 추가 17 | loc.insert(0,0) 18 | loc.append(l) 19 | rests = m 20 | 21 | 22 | 23 | # 최대간격을 d로 했을 때 몇개까지 지어지나 보기. 24 | # m개보다 더 지을 수 있으면 - > d 를키움 25 | # m개보다 적으면 -> d를 줄임 26 | # d 초기값: 간격중 최댓값 27 | # max_dist = 0 28 | # for i in range(len(loc)-1): 29 | # # 맨처음과 휴게소 거리 30 | # dist = loc[i+1] - loc[i] 31 | # if max_dist < dist: 32 | # max_dist = dist 33 | max_dist = l 34 | 35 | def binary_search(array, value, start, end): 36 | if start > end: 37 | return 38 | else: 39 | mid = (start + end) // 2 40 | # mid 를 최대 길이로 가질 때 몇 개까지 지을 수 있나? 41 | 42 | 43 | binary_search(array, m, 0, max_dist) 44 | 45 | 46 | 47 | # 48 | # while rests > 0: 49 | # dists = [] 50 | # max_dist = 0 51 | # max_loc = None 52 | # 53 | # # 전체 간격 측정하고 최대 간격을 찾음 54 | # for i in range(len(loc)-1): 55 | # # 맨처음과 휴게소 거리 56 | # dist = loc[i+1] - loc[i] 57 | # if max_dist < dist: 58 | # max_dist = dist 59 | # max_loc = i # i ~ i+1 이 간격 최대임 60 | # dists.append(dist) 61 | # print('measured dists:', dists) 62 | # 63 | # # 최대 간격 중간에 하나 지어서 1/2로 만듬. 중간이 없으면 왼쪽에 짓기 64 | # mid = (loc[max_loc] + loc[max_loc+1]) // 2 65 | # loc.append(mid) 66 | # loc.sort() 67 | # print('new loc:', mid) 68 | # print('updated loc:', loc) 69 | # # 지을 휴게소 수 하나 빼기 70 | # rests -= 1 71 | # 72 | # total_max_dist = None 73 | # for i in range(len(loc)-1): 74 | # dist = loc[i+1] - loc[i] 75 | # if total_max_dist is None: 76 | # total_max_dist = dist 77 | # if total_max_dist < dist: 78 | # total_max_dist = dist 79 | # 80 | # print(total_max_dist) 81 | 82 | -------------------------------------------------------------------------------- /notes/주사위 윷놀이_풀이.py: -------------------------------------------------------------------------------- 1 | # 링크 : https://2hs-rti.tistory.com/entry/백준-17852번-주사위-윷놀이-파이썬 2 | 3 | move = list(map(int, input().split())) 4 | horse = [[0, 0] for _ in range(4)] 5 | road = [[i for i in range(0, 41, 2)], 6 | [i for i in range(0, 11, 2)]+[13, 16, 19], 7 | [i for i in range(0, 25, 2)], 8 | [i for i in range(0, 31, 2)]+[28, 27, 26], 9 | [25, 30, 35, 40] 10 | ] 11 | 12 | def back_tracking(x, result, horse): 13 | global answer 14 | if x == 10: 15 | answer = max(answer, result) 16 | return 17 | for k in range(4): 18 | if horse[k][1] == -1: # 도착한 경우 19 | continue 20 | new_horse = [h[:] for h in horse] 21 | new_horse[k][1] += move[x] 22 | change_road(k, new_horse) 23 | # 도착 미도착 설정 24 | if new_horse[k][1] >= len(road[new_horse[k][0]]): 25 | new_horse[k][1] = -1 26 | back_tracking(x+1, result, new_horse) 27 | else: 28 | # 말이 있는지 없는지 29 | if [new_horse[k][0], new_horse[k][1]] in horse: 30 | continue 31 | back_tracking(x+1, result + road[new_horse[k][0]][new_horse[k][1]], new_horse) 32 | 33 | def change_road(k, horse): 34 | if horse[k][0] == 0: 35 | if horse[k][1] == 5: 36 | horse[k][0] = 1 37 | elif horse[k][1] == 10: 38 | horse[k][0] = 2 39 | elif horse[k][1] == 15: 40 | horse[k][0] = 3 41 | elif horse[k][1] == len(road[horse[k][0]]) - 1: 42 | horse[k][0] = 4 43 | horse[k][1] = len(road[horse[k][0]]) - 1 44 | elif horse[k][0] != 4: 45 | if horse[k][1] >= len(road[horse[k][0]]): 46 | horse[k][1] = horse[k][1] - len(road[horse[k][0]]) 47 | horse[k][0] = 4 48 | 49 | 50 | 51 | 52 | 53 | answer = 0 54 | back_tracking(0, 0, horse) 55 | print(answer) 56 | -------------------------------------------------------------------------------- /notes/취코테_dfsbfs_16_연구소_책풀이.py: -------------------------------------------------------------------------------- 1 | n, m = map(int, input().split()) 2 | data = [] # 초기 맵 리스트 3 | temp = [[0] * m for _ in range(n)] # 벽을 설치한 뒤의 맵 리스트 4 | 5 | for _ in range(n): 6 | data.append(list(map(int, input().split()))) 7 | 8 | 9 | # 4가지 이동방향 10 | dx = [-1,0,1,0] 11 | dy = [0,-1,0,1] 12 | 13 | result = 0 14 | 15 | # 깊이 우선 탐색(DFS)를 이용해 각 바이러스가 사방으로 퍼지도록 하기 16 | def virus(x, y): 17 | for i in range(4): 18 | nx = x + dx[i] 19 | ny = x + dy[i] 20 | # 상하좌우 중에서 바이러스가 퍼질 수 있는 경우 21 | if nx >= 0 and nx < n and ny >= 0 and ny < m: 22 | if temp[nx][ny] == 0: 23 | # 해당 위치에 바이러스 배치, 다시 재귀적으로 수행 24 | temp[nx][ny] = 2 25 | virus(nx,ny) 26 | # 재귀때는, input값을 같게 하자. 27 | 28 | # 현재 맵에서 안전 영역의 크기 계산하는 메서드 29 | def get_score(): 30 | score = 0 31 | for i in range(n): 32 | for j in range(m): 33 | if temp[i][j] == 0: 34 | score += 1 35 | return score 36 | 37 | # 깊이 우선 탐색(DFS)를 이용하여 울타리를 설치하면서, 매번 안전 영역의 크기 계산 38 | def dfs(count): 39 | global result 40 | if count == 3: 41 | for i in range(n): 42 | for j in range(m): 43 | temp[i][j] = data[i][j] 44 | 45 | # 각 바이러스의 위치에서 전파 진행 46 | for i in range(n): 47 | for j in range(m): 48 | if temp[i][j] == 2: 49 | virus(i, j) 50 | 51 | # 안전영역의 최댓값 계산 52 | result = max(result, get_score()) 53 | return 54 | 55 | # 빈 공간에 울타리 설치 56 | for i in range(n): 57 | for j in range(m): 58 | if data[i][j] == 0: 59 | data[i][j] = 1 60 | count += 1 61 | dfs(count) 62 | data[i][j] = 0 # dfs 이후에 울타리 뺌 63 | count -= 1 64 | 65 | dfs(0) 66 | print(result) 67 | -------------------------------------------------------------------------------- /notes/취코테_greedy_6_무지의_먹방_라이브_힙풀이.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | food_times = [3,1,2,4,5,7,8,6] 4 | k = 15 5 | 6 | # 남은시간, 음식번호 로 heap에 추가 7 | 8 | # greedy 방법 9 | # 가장 작은 시간 가진것부터 불러서, k - len(food_times)*남은시간 함 10 | # 만약 k가 더 작을경우: 남은것들 다시 나열해서 불러오면됨 11 | # 스킵하는 방법을 인덱싱할 필요가 없다. 겁나 간단하네.. 12 | if sum(food_times) <= k: 13 | print(-1) 14 | 15 | heap = [] 16 | for i in range(len(food_times)): 17 | heapq.heappush(heap,(food_times[i],i+1)) # 남은시간, 음식번호 18 | 19 | 20 | elapsed = 0 # 돈 바퀴 (먹은수) 21 | while heap: 22 | food_len = len(heap) 23 | time, number = heapq.heappop(heap) 24 | # 뽑아낸 time에서 현재 돈 바퀴만큼을 뺀다 25 | time -= elapsed 26 | # 남은음식수 * 빼고남은 time이 k보다 작으면 다먹는거고 27 | if food_len*time < k: 28 | k -= food_len*time 29 | elapsed += time 30 | 31 | 32 | # k보다 크면 셈을 한다 33 | else: 34 | # 뺀거 다시 집어넣음 35 | heapq.heappush(heap,(time,number)) 36 | # 정렬 리스트 37 | heap = sorted(heap,key=lambda x: x[1]) 38 | 39 | goal = heap[k%food_len] 40 | # 목표의 숫자를 출력 41 | print(goal[1]) 42 | break 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /notes/취코테_implementation_11_자물쇠와_열쇠_답안.py: -------------------------------------------------------------------------------- 1 | # 풀이방법을 보고 비효율적인 부분을 찾아보기. 2 | 3 | def rotate_a_matrix_by_90_degree(a): 4 | n = len(a) 5 | m = len(a[0]) 6 | result = [[0]*n for _ in range(m)] 7 | for i in range(n): 8 | for j in range(m): 9 | result[j][n - i - 1] = a[i][j] 10 | return result 11 | 12 | def check(new_lock): 13 | lock_length = len(new_lock) // 3 14 | for i in range(lock_length, lock_length * 2): 15 | for j in range(lock_length, lock_length * 2): 16 | if new_lock[i][j] != 1: 17 | return False 18 | return True 19 | 20 | def solution(key, lock): 21 | n = len(lock) 22 | m = len(key) 23 | new_lock = [[0] * (n*3) for _ in range(n*3)] 24 | for i in range(n): 25 | for j in range(n): 26 | new_lock[i + n][j + n] = lock[i][j] 27 | 28 | # 4가지 방향에 대해서 확인 29 | for rotation in range(4): 30 | key = rotate_a_matrix_by_90_degree(key) 31 | for x in range(n * 2): 32 | for y in range(n * 2): 33 | # 자물쇠에 열쇠를 끼워 넣기 34 | for i in range(m): 35 | for j in range(m): 36 | new_lock[x + i][y + j] += key[i][j] 37 | 38 | # 새로운 자물쇠에 열쇠가 정확히 들어맞는지 검사 39 | if check(new_lock) == True: 40 | return True 41 | # 자물쇠에서 열쇠를 다시 빼기 42 | for i in range(m): 43 | for j in range(m): 44 | new_lock[x + i][y + j] -= key[i][j] 45 | 46 | return False -------------------------------------------------------------------------------- /notes/풀이_삼성_실전_청소년상어.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | board = [[] for _ in range(4)] 4 | 5 | dx = [-1,-1,0,1,1,1,0,-1] 6 | dy = [0,-1,-1,-1,0,1,1,1] 7 | 8 | for i in range(4): 9 | data = list(map(int, input().split())) 10 | fish =[] 11 | for j in range(4): 12 | fish.append([data[2*j], data[2*j+1]-1]) 13 | board[i] = fish 14 | 15 | max_score = 0 16 | 17 | def dfs(sx, sy, score, board): 18 | global max_score 19 | score += board[sx][sy][0] 20 | max_score = max(max_score, score) 21 | board[sx][sy][0] = 0 22 | 23 | # 물고기 움직임 24 | for f in range(1,17): 25 | f_x, f_y = -1, -1 26 | for x in range(4): 27 | for y in range(4): 28 | if board[x][y][0] == f: 29 | f_x, f_y = x, y 30 | break 31 | if f_x == -1 and f_y == -1: 32 | continue 33 | f_d = board[f_x][f_y][1] 34 | 35 | for i in range(8): 36 | nd = (f_d+i) % 8 37 | nx = f_x + dx[nd] 38 | ny = f_y + dy[nd] 39 | if not (0 <= nx < 4 and 0 <= ny < 4) or (nx == sx and ny == sy): 40 | continue 41 | board[f_x][f_y][1] = nd 42 | board[f_x][f_y], board[nx][ny] = board[nx][ny], board[f_x][f_y] 43 | break 44 | 45 | # 상어 먹음 46 | s_d = board[sx][sy][1] 47 | for i in range(1, 5): 48 | nx = sx + dx[s_d]*i 49 | ny = sy + dy[s_d]*i 50 | if (0 <= nx < 4 and 0 <= ny < 4) and board[nx][ny][0] > 0: 51 | dfs(nx, ny, score, copy.deepcopy(board)) 52 | 53 | dfs(0,0,0,board) 54 | print(max_score) 55 | -------------------------------------------------------------------------------- /notes/프로그래머스_N으로표현_다시풀기.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(N, number): 4 | tab = [0]*N*int(1e6) 5 | # N, NN, NNN 등 먼저 집어넣기 6 | multi = N 7 | count = 1 8 | while multi < len(tab): 9 | tab[multi] = count 10 | multi = 10*multi + N 11 | count += 1 12 | 13 | stack = deque([]) 14 | stack.append(N) 15 | while stack: 16 | breakpoint() 17 | num = stack.pop() 18 | cand_cal = [num+5, num-5, num*5, num//5] 19 | new_cal = [] 20 | for c in cand_cal: 21 | if 1 <= c < len(tab): 22 | new_cal.append(c) 23 | print(num) 24 | print(new_cal) 25 | for c in new_cal: 26 | if tab[c] > tab[num] + 1: 27 | tab[c] = tab[num] + 1 28 | elif tab[c] == 0: 29 | tab[c] = tab[num] + 1 30 | stack.append(c) 31 | else: 32 | continue 33 | 34 | answer = tab[number] 35 | return answer 36 | 37 | print(solution(5, 12)) -------------------------------------------------------------------------------- /solution_codes/programmers_DP_여행_1회답.py: -------------------------------------------------------------------------------- 1 | n,m,k = map(int, input().split()) 2 | 3 | # n번도시, m개이하의 도시 지나야, k는 노선 개수 4 | 5 | graph = [list(map(int, input().split())) for _ in range(k)] 6 | # a, b, 기내식 c 7 | 8 | # dp 9 | # i+1번도시 : max(i+1로 오는 경로가 있는 x의 값들) 10 | dp = [[0]*(n+1) for _ in range(n+1)] # 0~n x 0~n 11 | dp_sum = [[0]*(n+1) for _ in range(m+1)] # 0~m X 0~n 12 | 13 | for a, b, c in graph: 14 | if a < b: #[도착][출발] 15 | dp[b][a] = max(dp[b][a], c) 16 | if a == 1: 17 | dp_sum[1][b] = max(dp_sum[1][b], c) 18 | 19 | for x in range(1, n+1): 20 | for i in range(1, x): 21 | # print('x,i:', x,i) 22 | cost = dp[x][i] 23 | if cost: 24 | for k in range(1, m-1): 25 | if dp_sum[k][i]: 26 | dp_sum[k+1][x] = max(dp_sum[k+1][x], dp_sum[k][i] + cost) 27 | 28 | print(max(d[n] for d in dp_sum)) -------------------------------------------------------------------------------- /solution_codes/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hoeen/coding_test_training/b0ffdd467259e3b043d699a13636a87a8089a681/solution_codes/.DS_Store -------------------------------------------------------------------------------- /solution_codes/.cph/.baekjoon_그래프_택배 배송_1회.py_093adbaa5e516587dd865784dc1d17d1.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: baekjoon_그래프_택배 배송_1회","url":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_그래프_택배 배송_1회.py","tests":[{"id":1669903252201,"input":"6 8\n4 5 3\n2 4 0\n4 1 4\n2 1 1\n5 6 1\n3 6 2\n3 2 6\n3 4 4","output":"5"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_그래프_택배 배송_1회.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.baekjoon_그래프_한 줄로 서기_1회.py_711d368afff42db7738278707241d7fe.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: baekjoon_그래프_한 줄로 서기_1회","url":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_그래프_한 줄로 서기_1회.py","tests":[{"id":1669905208974,"input":"4\n2 1 1 0","output":"4 2 1 3"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_그래프_한 줄로 서기_1회.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.baekjoon_도토리 숨기기.py_9a56cdd50204360fb5b72e9412fc266f.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: baekjoon_도토리 숨기기","url":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_도토리 숨기기.py","tests":[{"id":1668145557756,"input":"200 2 5\n100 150 10\n110 150 15","output":"125"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_도토리 숨기기.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.baekjoon_새로운 게임 2.py_afd3352f7cd570c0476f0be2319cefc9.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: baekjoon_새로운 게임 2","url":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_새로운 게임 2.py","tests":[{"id":1664980402109,"input":"4 4\n0 0 2 0\n0 0 1 0\n0 0 1 2\n0 2 0 0\n2 1 1\n3 2 3\n2 2 1\n4 1 2","output":"-1"},{"id":1664985659505,"input":"4 4\n0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0\n1 1 1\n1 2 1\n1 3 1\n1 4 1","output":"1"},{"id":1664985698246,"input":"4 4\n0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0\n1 1 1\n1 2 1\n1 3 1\n2 4 3","output":"1"},{"id":1664985706198,"input":"4 4\n0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0\n1 1 1\n1 2 1\n1 3 1\n3 3 3","output":"2"},{"id":1664985716596,"input":"6 10\n0 1 2 0 1 1\n1 2 0 1 1 0\n2 1 0 1 1 0\n1 0 1 1 0 2\n2 0 1 2 0 1\n0 2 1 0 2 1\n1 1 1\n2 2 2\n3 3 4\n4 4 1\n5 5 3\n6 6 2\n1 6 3\n6 1 2\n2 4 3\n4 2 1","output":"7"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_새로운 게임 2.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.baekjoon_소문난 칠공주.py_a8a019b4fa1325bee74fc2c72401df23.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: baekjoon_소문난 칠공주","url":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_소문난 칠공주.py","tests":[{"id":1666938777628,"input":"YYYYY\nSYSYS\nYYYYY\nYSYYS\nYYYYY","output":"2"},{"id":1666943022930,"input":"YYYYY\nSYSYS\nYYYYY\nSSSSY\nYYSYY","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_소문난 칠공주.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.baekjoon_파티.py_ebb333dac39f09977e30581d746b2a4d.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: baekjoon_파티","url":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_파티.py","tests":[{"id":1669333360762,"input":"4 8 2\n1 2 4\n1 3 2\n1 4 7\n2 1 1\n2 3 5\n3 1 2\n3 4 4\n4 2 3","output":"10"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_파티.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.baekjoon_파티_1회.py_a41b0b419bf2e37251d365895082cb22.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: baekjoon_파티_1회","url":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_파티_1회.py","tests":[{"id":1673251311027,"input":"4 8 2\n1 2 4\n1 3 2\n1 4 7\n2 1 1\n2 3 5\n3 1 2\n3 4 4\n4 2 3","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/baekjoon_파티_1회.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.programmers_코딩테스트 연습.py_6787030bb9ab00932dcb167dd6d1e38b.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: programmers_코딩테스트 연습","url":"/Users/wooseokpark/github/coding_test/solution_codes/programmers_코딩테스트 연습.py","tests":[{"id":1671350988314,"input":"","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/programmers_코딩테스트 연습.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.samsung_BFS, 백트래킹_연구소 3_1회답.py_29755a22cef82696523091cbaf0583be.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: samsung_BFS, 백트래킹_연구소 3_1회답","url":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_BFS, 백트래킹_연구소 3_1회답.py","tests":[{"id":1664934369014,"input":"7 3\n2 0 0 0 1 1 0\n0 0 1 0 1 2 0\n0 1 1 0 1 0 0\n0 1 0 0 0 0 0\n0 0 0 2 0 1 1\n0 1 0 0 0 0 0\n2 1 0 0 0 0 2","output":"4"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_BFS, 백트래킹_연구소 3_1회답.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.samsung_게리맨더링 2.py_75c49ec84b2a4c795b4ae48e721ce6ae.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: samsung_게리맨더링 2","url":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_게리맨더링 2.py","tests":[{"id":1665217537952,"input":"6\n1 2 3 4 1 6\n7 8 9 1 4 2\n2 3 4 1 1 3\n6 6 6 6 9 4\n9 1 9 1 9 5\n1 1 1 1 9 9","output":"18"},{"id":1665220634419,"input":"6\n5 5 5 5 5 5\n5 5 5 5 5 5\n5 5 5 5 5 5\n5 5 5 5 5 5\n5 5 5 5 5 5\n5 5 5 5 5 5","output":"20"},{"id":1665220645204,"input":"8\n1 2 3 4 5 6 7 8\n2 3 4 5 6 7 8 9\n3 4 5 6 7 8 9 1\n4 5 6 7 8 9 1 2\n5 6 7 8 9 1 2 3\n6 7 8 9 1 2 3 4\n7 8 9 1 2 3 4 5\n8 9 1 2 3 4 5 6","output":"23"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_게리맨더링 2.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.samsung_마법사 상어와 파이어스톰_1회.py_fa1a7bae419e81aba8f414df7af33770.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: samsung_마법사 상어와 파이어스톰_1회","url":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_마법사 상어와 파이어스톰_1회.py","tests":[{"id":1665065724654,"input":"3 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1","output":"284\n64"},{"id":1665065770557,"input":"3 2\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2","output":"280\n64"},{"id":1665065869469,"input":"3 5\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 0 3 2","output":"268\n64"},{"id":1665065881042,"input":"3 10\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 0 3 2 1 2 3 2 3","output":"248\n62"},{"id":1665066727760,"input":"3 10\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8\n8 7 6 5 4 3 2 1\n1 2 3 1 2 3 1 2 3 1","output":"246\n60"},{"id":1665066737869,"input":"3 10\n1 0 3 4 5 6 7 0\n8 0 6 5 4 3 2 1\n1 2 0 4 5 6 7 0\n8 7 6 5 4 3 2 1\n1 2 3 4 0 6 7 0\n8 7 0 5 4 3 2 1\n1 2 3 4 5 6 7 0\n0 7 0 5 4 3 2 1\n1 2 3 1 2 3 1 2 3 1","output":"37\n9"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_마법사 상어와 파이어스톰_1회.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.samsung_시뮬레이션_큐빙_1회.py_170b6cfbe6aee8e07e107d0579499c4b.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: samsung_시뮬레이션_큐빙_1회","url":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_시뮬레이션_큐빙_1회.py","tests":[{"id":1664895167042,"input":"4\n1\nL-\n2\nF+ B+\n4\nU- D- L+ R+\n10\nL- U- L+ U- L- U- U- L+ U+ U+","output":"rww\nrww\nrww\nbbb\nwww\nggg\ngwg\nowr\nbwb\ngwo\nwww\nrww"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_시뮬레이션_큐빙_1회.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.samsung_연구소 3_1회.py_1bfe2eae5840980e938e4809edc17378.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: samsung_연구소 3_1회","url":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_연구소 3_1회.py","tests":[{"id":1664895077366,"input":"7 3\n2 0 0 0 1 1 0\n0 0 1 0 1 2 0\n0 1 1 0 1 0 0\n0 1 0 0 0 0 0\n0 0 0 2 0 1 1\n0 1 0 0 0 0 0\n2 1 0 0 0 0 2","output":"4"},{"id":1664933741669,"input":"7 3\n2 0 2 0 1 1 0\n0 0 1 0 1 2 0\n0 1 1 2 1 0 0\n2 1 0 0 0 0 2\n0 0 0 2 0 1 1\n0 1 0 0 0 0 0\n2 1 0 0 2 0 2","output":"4"},{"id":1664933754969,"input":"7 4\n2 0 2 0 1 1 0\n0 0 1 0 1 2 0\n0 1 1 2 1 0 0\n2 1 0 0 0 0 2\n0 0 0 2 0 1 1\n0 1 0 0 0 0 0\n2 1 0 0 2 0 2","output":"4"},{"id":1664933764188,"input":"7 5\n2 0 2 0 1 1 0\n0 0 1 0 1 2 0\n0 1 1 2 1 0 0\n2 1 0 0 0 0 2\n0 0 0 2 0 1 1\n0 1 0 0 0 0 0\n2 1 0 0 2 0 2","output":"3"},{"id":1664933768740,"input":"7 3\n2 0 2 0 1 1 0\n0 0 1 0 1 0 0\n0 1 1 1 1 0 0\n2 1 0 0 0 0 2\n1 0 0 0 0 1 1\n0 1 0 0 0 0 0\n2 1 0 0 2 0 2","output":"7"},{"id":1664933782662,"input":"7 2\n2 0 2 0 1 1 0\n0 0 1 0 1 0 0\n0 1 1 1 1 0 0\n2 1 0 0 0 0 2\n1 0 0 0 0 1 1\n0 1 0 0 0 0 0\n2 1 0 0 2 0 2","output":"-1"},{"id":1664933786756,"input":"5 1\n2 2 2 1 1\n2 1 1 1 1\n2 1 1 1 1\n2 1 1 1 1\n2 2 2 1 1","output":"0"},{"id":1664933798052,"input":"","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_연구소 3_1회.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/.cph/.samsung_원판 돌리기_1회.py_4a5329be370bf33305f9394a6f864d76.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: samsung_원판 돌리기_1회","url":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_원판 돌리기_1회.py","tests":[{"id":1665235193030,"input":"4 4 1\n1 1 2 3\n5 2 4 2\n3 1 3 5\n2 1 3 2\n2 0 1","output":"30"},{"id":1665236260951,"input":"4 4 2\n1 1 2 3\n5 2 4 2\n3 1 3 5\n2 1 3 2\n2 0 1\n3 1 3","output":"22"},{"id":1665236322138,"input":"4 4 3\n1 1 2 3\n5 2 4 2\n3 1 3 5\n2 1 3 2\n2 0 1\n3 1 3\n2 0 2","output":"22"},{"id":1665236971243,"input":"4 4 4\n1 1 2 3\n5 2 4 2\n3 1 3 5\n2 1 3 2\n2 0 1\n3 1 3\n2 0 2\n3 1 1","output":"0"},{"id":1665237082279,"input":"4 6 3\n1 2 3 4 5 6\n2 3 4 5 6 7\n3 4 5 6 7 8\n4 5 6 7 8 9\n2 1 4\n3 0 1\n2 1 2","output":"26"}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/Users/wooseokpark/github/coding_test/solution_codes/samsung_원판 돌리기_1회.py","group":"local","local":true} -------------------------------------------------------------------------------- /solution_codes/baekjoon_BFS_단지번호붙이기_1회.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | n = int(input()) 3 | board = [list(map(int, input())) for _ in range(n)] 4 | 5 | count = [] 6 | visited = [[False]*n for _ in range(n)] 7 | dx = (-1, 1, 0, 0) # 상하좌우 8 | dy = (0, 0, -1, 1) 9 | 10 | def bfs(x, y): 11 | count = [] 12 | q = deque([(x,y)]) 13 | visited[x][y] = True 14 | while q: 15 | qx, qy = q.popleft() 16 | count.append((qx, qy)) 17 | for i in range(4): 18 | nx = qx + dx[i] 19 | ny = qy + dy[i] 20 | if 0 <= nx < n and 0 <= ny < n: 21 | if not visited[nx][ny] and board[nx][ny] == 1: 22 | # print('nx, ny to put:', nx, ny) 23 | visited[nx][ny] = True 24 | q.append((nx,ny)) 25 | # print('bfs count:', len(set(count))) 26 | return len(set(count)) 27 | 28 | for x in range(n): 29 | for y in range(n): 30 | if board[x][y] == 1 and not visited[x][y]: # 방문 안한 1이면 31 | count.append(bfs(x, y)) 32 | 33 | print(len(count)) 34 | count.sort() 35 | for c in count: 36 | print(c) 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_BFS_상범 빌딩_1회.py: -------------------------------------------------------------------------------- 1 | # 최단시간 - bfs 2 | from collections import deque 3 | 4 | def solution(l, r, c): 5 | # 층수, 행 열 수 6 | board = [] 7 | for li in range(l): 8 | board.append( 9 | [list(input()) for _ in range(r)] 10 | ) 11 | _ = input() 12 | 13 | # 동서 남북 상하 14 | dx = (-1, 1, 0, 0, 0, 0) 15 | dy = (0, 0, -1, 1, 0, 0) 16 | dz = (0, 0, 0, 0, -1, 1) 17 | 18 | q = deque([]) 19 | 20 | def find_start_end(l, r, c): 21 | for z in range(l): 22 | for x in range(r): 23 | for y in range(c): 24 | if board[z][x][y] == 'S': 25 | start = (x, y, z) 26 | elif board[z][x][y] == 'E': 27 | exit = (x, y, z) 28 | return start, exit 29 | 30 | visited = [[[-1]*c for _ in range(r)] for _ in range(l)] 31 | (sx, sy, sz), (ex, ey ,ez) = find_start_end(l, r, c) 32 | visited[sz][sx][sy] = 0 33 | q.append((sx, sy, sz)) 34 | while q: 35 | qx, qy, qz = q.popleft() 36 | for i in range(6): 37 | nx, ny, nz = qx + dx[i], qy + dy[i], qz + dz[i] 38 | if 0 <= nx < r and 0 <= ny < c and 0 <= nz < l: 39 | if visited[nz][nx][ny] < 0 and board[nz][nx][ny] != '#': 40 | visited[nz][nx][ny] = visited[qz][qx][qy] + 1 41 | q.append((nx, ny, nz)) 42 | 43 | if visited[ez][ex][ey] > 0: 44 | print('Escaped in {} minute(s).'.format(visited[ez][ex][ey])) 45 | elif visited[ez][ex][ey] == -1: 46 | print('Trapped!') 47 | 48 | while True: 49 | l, r, c = map(int, input().split()) 50 | # print('l, r, c:', l, r, c) 51 | if (l, r, c) == (0, 0, 0): 52 | break 53 | solution(l, r, c) -------------------------------------------------------------------------------- /solution_codes/baekjoon_BFS_스타트링크_1회답.py: -------------------------------------------------------------------------------- 1 | # BFS로 접근 2 | from collections import deque 3 | 4 | f,s,g,u,d = map(int, input().split()) 5 | 6 | # 각 층에 방문했을때 visit 처리 7 | q = deque([]) 8 | visited = [None]*(f+1) 9 | # 시작층 큐에 삽입 10 | q.append((s,0)) # (층, 버튼횟수) 11 | while q: 12 | now, pressed = q.popleft() 13 | # print(now, pressed) 14 | # print(visited) 15 | 16 | if visited[now] is None: 17 | visited[now] = pressed # 꺼낸 층에 방문처리 18 | # 층 도달하면 반환 19 | if now == g: 20 | break 21 | up = now + u 22 | down = now - d 23 | if 0 < up <= f: 24 | q.append((up, pressed+1)) 25 | if 0 < down <= f: 26 | q.append((down, pressed+1)) 27 | # print('q status:', q) 28 | 29 | # print('visit changed:', visited) 30 | if visited[g] is not None: 31 | print(visited[g]) 32 | else: 33 | print('use the stairs') 34 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DFS, BFS_바이러스_1회.py: -------------------------------------------------------------------------------- 1 | # ~11:10 2 | n = int(input()) 3 | m = int(input()) 4 | 5 | graph = [list(map(int, input().split())) for _ in range(m)] 6 | 7 | # bfs 8 | # 1번 먼저 연결 확인 9 | def bfs(): 10 | infected = 0 11 | q = [] 12 | visited = [False]*(n+1) 13 | visited[1] = True # 방문처리 14 | q.append(1) 15 | while q: 16 | num = q.pop(0) 17 | for g in graph: 18 | if num in g: 19 | b = list(set(g)-set([num]))[0] 20 | if not visited[b]: 21 | q.append(b) 22 | visited[b] = True 23 | infected += 1 24 | # print('num:', num) 25 | # print('q:', q) 26 | # print('visited:', visited) 27 | return infected 28 | print(bfs()) -------------------------------------------------------------------------------- /solution_codes/baekjoon_DFS, BFS_벽 부수고 이동하기 4_1회답.py: -------------------------------------------------------------------------------- 1 | from collections import deque, defaultdict 2 | import sys 3 | input = sys.stdin.readline 4 | n, m = map(int, input().split()) 5 | board = [list(map(int, list(input().strip()))) for _ in range(n)] 6 | 7 | 8 | dx = (-1, 1, 0, 0) 9 | dy = (0, 0, 1, -1) 10 | 11 | visited = [[False]*m for _ in range(n)] 12 | total_visited = [[0]*m for _ in range(n)] # 참조할 칸. [그룹숫자] 13 | group_ref = defaultdict(int) 14 | 15 | 16 | def bfs(x, y, gnum): 17 | # global total_visited 18 | # global group_ref 19 | 20 | ''' 21 | 뚫려있는 칸 개수만큼 찾은 방향의 visited 칸을 모두 업데이트 22 | ''' 23 | count = 1 # 이동할수있는 빈칸 24 | # found = deque([]) # 찾은칸 25 | q = deque([]) 26 | q.append((x, y)) 27 | visited[x][y] = True 28 | total_visited[x][y] = gnum 29 | while q: 30 | qx, qy = q.popleft() 31 | for i in range(4): 32 | nx, ny = qx + dx[i], qy + dy[i] 33 | if 0 <= nx < n and 0 <= ny < m: 34 | if board[nx][ny] == 0 and not visited[nx][ny] and total_visited[nx][ny] == 0: 35 | visited[nx][ny] = True 36 | total_visited[nx][ny] = gnum 37 | count += 1 38 | q.append((nx, ny)) 39 | 40 | # 기억할 부분 넣어야함 - 찾은 빈칸개수로 채우기 41 | group_ref[gnum] = count 42 | return 43 | 44 | current = 1 # 현재 체크할 그룹 넘버 45 | for x in range(n): 46 | for y in range(m): 47 | # 빈칸을 탐색 48 | if board[x][y] == 0 and not visited[x][y]: 49 | bfs(x, y, current) 50 | current += 1 51 | 52 | 53 | for x in range(n): 54 | for y in range(m): 55 | if board[x][y] == 1: 56 | gset = set() 57 | for i in range(4): 58 | nx = x + dx[i] 59 | ny = y + dy[i] 60 | if 0 <= nx < n and 0 <= ny < m: 61 | gset.add(total_visited[nx][ny]) 62 | board[x][y] = (board[x][y] + sum(group_ref[num] for num in gset)) % 10 63 | 64 | 65 | for b in board: 66 | print(''.join(list(map(str,b)))) -------------------------------------------------------------------------------- /solution_codes/baekjoon_DFS, BFS_회사문화1_1회답.py: -------------------------------------------------------------------------------- 1 | from collections import deque, defaultdict 2 | import sys 3 | 4 | 5 | input = sys.stdin.readline 6 | n, m = map(int, input().split()) 7 | graph_list = [0] + list(map(int, input().split())) 8 | 9 | # 직속 부하로 바꿈 10 | graph = defaultdict(list) #[[] for _ in range(n+1)] 11 | for i, g in enumerate(graph_list): 12 | if i > 1: 13 | graph[g].append(i) 14 | 15 | result = defaultdict(int) 16 | for _ in range(m): 17 | num, grat = map(int, input().split()) 18 | result[num] += grat 19 | 20 | 21 | def bfs(start): 22 | global result 23 | q = deque([]) 24 | q.append(start) 25 | while q: 26 | x = q.popleft() 27 | w = result[x] 28 | for pawn in graph[x]: 29 | result[pawn] += w 30 | q.append(pawn) 31 | 32 | bfs(1) 33 | 34 | answer = [0]*(n+1) 35 | for k, i in result.items(): 36 | answer[k] = i 37 | 38 | print(*answer[1:]) 39 | 40 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DFS_색종이 만들기_1회.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | board = [list(map(int, input().split())) for _ in range(n)] 3 | 4 | # board = [ 5 | # [1, 1, 0, 0, 0, 0, 1, 1], 6 | # [1, 1, 0, 0, 0, 0, 1, 1], 7 | # [0, 0, 0, 0, 1, 1, 0, 0], 8 | # [0, 0, 0, 0, 1, 1, 0, 0], 9 | # [1, 0, 0, 0, 1, 1, 1, 1], 10 | # [0, 1, 0, 0, 1, 1, 1, 1], 11 | # [0, 0, 1, 1, 1, 1, 1, 1], 12 | # [0, 0, 1, 1, 1, 1, 1, 1], 13 | # ] 14 | 15 | white = 0 16 | blue = 0 17 | 18 | def sum_pap(pa): 19 | res = 0 20 | for x in range(len(pa)): 21 | res += sum(pa[x]) 22 | # print(res) 23 | if res == 0: return 0 24 | elif res == len(pa)**2: return 1 25 | else: return -1 26 | 27 | def func(pa): 28 | global white, blue 29 | # print('print pa') 30 | # for p in pa: 31 | # print(p) 32 | if sum_pap(pa) == 0: 33 | white += 1 34 | return 35 | elif sum_pap(pa) == 1: 36 | blue += 1 37 | return 38 | else: 39 | N = len(pa) 40 | if N == 1: return 41 | # print(N, sum_pap(pa)) 42 | # print([p[0:(N//2)] for p in pa[:N//2]]) 43 | func([p[0:(N//2)] for p in pa[:N//2]]) 44 | func([p[(N//2):] for p in pa[:N//2]]) 45 | func([p[0:(N//2)] for p in pa[N//2:]]) 46 | func([p[(N//2):] for p in pa[N//2:]]) 47 | 48 | func(board) 49 | print(white) 50 | print(blue) 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP, 배낭문제_호텔_1회답.py: -------------------------------------------------------------------------------- 1 | c, n = map(int, input().split()) 2 | inv = [list(map(int, input().split())) for _ in range(n)] 3 | 4 | ''' 5 | 배낭 문제 6 | inv : cost, ppl 7 | k명 확보했을때 최소 비용 8 | f(k+ppl) = min(f(k+ppl), f(k) + cost)) 9 | ''' 10 | 11 | dp_tab = [float('inf')]*(c+101) # 0~c+100명 12 | for cost, ppl in inv: 13 | dp_tab[ppl] = min(dp_tab[ppl], cost) 14 | 15 | for k in range(c+1): 16 | for cost, ppl in inv: 17 | dp_tab[k+ppl] = min(dp_tab[k+ppl], dp_tab[k] + cost) 18 | 19 | print(min(dp_tab[c:])) 20 | 21 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP_RGB거리 2_1회답.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.setrecursionlimit(int(1e5)) 3 | 4 | n = int(input()) 5 | costs = [list(map(int, input().split())) for _ in range(n)] 6 | board = [[[float('inf')] * 3 for _ in range(3)] for _ in range(n)] 7 | 8 | # top-down dp 9 | def recur(idx, color, first_color): 10 | if idx == n: # 맨끝 - 0으로 리턴 11 | return 0 12 | if board[idx][color] < float('inf'): 13 | return board[idx][color] 14 | for next_col in range(3): 15 | if idx == n-2 and next_col in [first_color, color]: 16 | continue 17 | elif next_col != color: 18 | board[idx][color] = min(board[idx][color], 19 | costs[idx][color] + recur(idx+1, next_col, first_color) 20 | ) 21 | return board[idx][color] 22 | 23 | min_cost = float('inf') 24 | for i in range(3): 25 | # first_color의 경우마다 dp table를 새로 만들어줘서 재귀 결과를 최솟값과 비교 갱신 26 | board = [[float('inf')] * 3 for _ in range(n)] 27 | min_cost = min(min_cost, 28 | recur(0, i, i) 29 | ) 30 | print(min_cost) 31 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP_방 번호_1회답.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | costs = list(map(int, input().split())) 3 | m = int(input()) 4 | 5 | dp = [-1]*(m+1) #0 ~ m 6 | for i in range(n-1, -1, -1): #0~n-1 7 | x = costs[i] # 번호 하나 뽑 - 현재 숫자 가격 8 | for j in range(x, m+1): # 가격 x부터 m까지 9 | dp[j] = max(i, dp[j], dp[j-x]*10 + i) 10 | # 현재 숫자, 직전 번호, j-x 한 값에 해당하는 숫자가 있으면 한자리 올림 11 | print(dp[m]) 12 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP_병사 배치하기_1회답.py: -------------------------------------------------------------------------------- 1 | # 내림차순으로 배치되며 최대한 적게 열외시키자. 2 | 3 | n = int(input()) 4 | solds = list(map(int, input().split())) 5 | 6 | # f(k) = max(f(k), f(i)+1) for i in range(1~k) if f(i) < f(k) 7 | 8 | tab = [1]*n 9 | solds.reverse() 10 | 11 | for k in range(n): #0~n-1 12 | for i in range(k): #0~k-1 13 | if solds[i] < solds[k]: 14 | tab[k] = max(tab[k], tab[i]+1) 15 | 16 | print(tab) 17 | print(n - max(tab)) 18 | 19 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP_색상환_1회답.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | k = int(input()) 3 | 4 | # i개 색중 j개 색을 선택하는 경우의수 dp 5 | # i : 1~n 6 | # j : 1~k 7 | dp = [[0]*k for _ in range(n)] 8 | for i in range(0, n): 9 | dp[i][0] = i+1 10 | 11 | for i in range(3, n): 12 | for j in range(1, k): 13 | if j <= i/2: 14 | dp[i][j] = dp[i-1][j] + dp[i-2][j-1] 15 | 16 | print(dp[n-1][k-1] % 1_000_000_003) -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP_신나는 함수 실행_1회.py: -------------------------------------------------------------------------------- 1 | def w(a, b, c, memo={}): 2 | # breakpoint() 3 | if (a,b,c) in memo: 4 | return memo[(a,b,c)] 5 | else: 6 | if a <= 0 or b <= 0 or c <= 0: 7 | memo[(a,b,c)] = 1 8 | return 1 9 | 10 | elif a > 20 or b > 20 or c > 20: 11 | if (20,20,20) in memo: 12 | memo[(a,b,c)] = memo[(20,20,20)] 13 | return w(20, 20, 20, memo) 14 | 15 | elif a < b and b < c: 16 | if (a,b,c-1) in memo and\ 17 | (a,b-1,c-1) in memo and\ 18 | (a,b-1,c) in memo: 19 | memo[(a,b,c)] = memo[(a,b,c-1)] + memo[(a,b-1,c-1)] - memo[(a, b-1, c)] 20 | return w(a, b, c-1,memo) + w(a, b-1, c-1,memo) - w(a, b-1, c,memo) 21 | 22 | else: 23 | if (a-1,b,c) in memo\ 24 | and (a-1,b-1,c) in memo\ 25 | and (a-1,b,c-1) in memo\ 26 | and (a-1,b-1,c-1) in memo: 27 | memo[(a,b,c)] = memo[(a-1, b, c)] + memo[(a-1, b-1, c)] + memo[(a-1, b, c-1)] - memo[(a-1, b-1, c-1)] 28 | 29 | return w(a-1, b, c, memo) + w(a-1, b-1, c, memo) + w(a-1, b, c-1, memo) - w(a-1, b-1, c-1, memo) 30 | 31 | 32 | while True: 33 | a, b, c = map(int, input().split()) 34 | if (a,b,c) == (-1,-1,-1): 35 | break 36 | print(f'w({a}, {b}, {c}) =', w(a,b,c)) 37 | 38 | 39 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP_연속합_1회답.py: -------------------------------------------------------------------------------- 1 | # ~ 4:00 2 | n = int(input()) 3 | seq = list(map(int, input().split())) 4 | 5 | # n = 10 6 | # seq = [10, -4, 3, 1, 5, 6, -35, 12, 21, -1] 7 | 8 | # 가장 큰 합. 연속. 9 | # 점화식 : seq[1] ~ seq[:n] = f(n) 10 | tab = [None for _ in range(n)] 11 | tab[0] = seq[0] 12 | for i in range(1, n): 13 | tab[i] = max(seq[i], tab[i-1]+seq[i]) 14 | print(max(tab)) 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP_정수 삼각형_1회.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | tri = [None]*n 3 | for i in range(n): 4 | tri[i] = list(map(int, input().split())) 5 | 6 | # dp - tab 7 | tab = [None for _ in range(n)] 8 | for i in range(n): 9 | tab[i] = [0]*(i+1) 10 | 11 | def dp_tab(): 12 | tab[0][0] = tri[0][0] # 맨위 삽입 13 | for x in range(1, n): 14 | for y in range(len(tri[x])): 15 | km = [] 16 | if y-1 >= 0: 17 | km.append(tab[x-1][y-1]) 18 | if y < len(tri[x])-1: 19 | km.append(tab[x-1][y]) 20 | tab[x][y] = tri[x][y] + max(km) 21 | 22 | 23 | dp_tab() 24 | 25 | print(max(tab[-1])) 26 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP_팰린드롬?_1회답.py: -------------------------------------------------------------------------------- 1 | import sys 2 | input = sys.stdin.readline 3 | 4 | n = int(input()) 5 | seq = list(map(int, input().split())) 6 | m = int(input()) 7 | 8 | dp_tab = [[False]*(n) for _ in range(n)] 9 | 10 | for e in range(n): 11 | for s in range(0, e+1): 12 | if e == s: 13 | dp_tab[s][e] = 1 14 | elif e - s == 1: 15 | if seq[e] == seq[s]: 16 | dp_tab[s][e] = 1 17 | else: 18 | dp_tab[s][e] = 0 19 | else: 20 | if seq[e] == seq[s] and dp_tab[s+1][e-1] == 1: 21 | dp_tab[s][e] = 1 22 | else: 23 | dp_tab[s][e] = 0 24 | 25 | # print(time.time() - t0, 's') 26 | # for p in dp_tab: 27 | # print(p) 28 | 29 | for _ in range(m): 30 | s, e = map(int, input().split()) 31 | print(dp_tab[s-1][e-1]) -------------------------------------------------------------------------------- /solution_codes/baekjoon_DP_피보나치 수_1회.py: -------------------------------------------------------------------------------- 1 | import time 2 | from contextlib import contextmanager 3 | 4 | class Timer: 5 | def __init__(self, f): 6 | self.func = f 7 | def __call__(self, *args, **kwargs): 8 | t0 = time.time() 9 | res = self.func(*args, **kwargs) 10 | print(f'[{self.func.__name__}] executed in {time.time() - t0}s') 11 | return res 12 | 13 | @contextmanager 14 | def time_elapsed(): 15 | t0 = time.time() 16 | yield 17 | print(f'task executed in {time.time() - t0}s') 18 | 19 | 20 | n = int(input()) 21 | 22 | 23 | f1 = 0 24 | 25 | # def fib_recur(n): 26 | # global f1 27 | # if n == 1 or n == 2: 28 | # f1 += 1 29 | # return 1 30 | # else: 31 | # return fib_recur(n-1) + fib_recur(n-2) 32 | 33 | # fib_recur(n) 34 | # print(f1) 35 | 36 | @Timer 37 | def fib_dp(n): 38 | f2 = 0 39 | tab = [0]*(n+1) # 0 ~ n 40 | tab[1], tab[2] = 1, 1 41 | for i in range(3,n+1): 42 | f2 += 1 43 | tab[i] = tab[i-1] + tab[i-2] 44 | print('f2 called:', f2) 45 | return tab[-1] 46 | 47 | print(fib_dp(n)) 48 | 49 | 50 | f3 = 0 51 | memo = {} 52 | memo[1] = 1 53 | memo[2] = 1 54 | 55 | def fib_dp_recur(n, memo=memo): 56 | global f3 57 | f3 += 1 58 | if n in memo: 59 | return memo[n] 60 | else: 61 | if n-1 in memo and n-2 in memo: 62 | memo[n] = memo[n-1] + memo[n-2] 63 | return fib_dp_recur(n-1) + fib_dp_recur(n-2) 64 | 65 | with time_elapsed(): 66 | print(fib_dp_recur(n)) 67 | 68 | print('f3 called:', f3) 69 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_구현, 백트래킹_사다리 조작_1회답.py: -------------------------------------------------------------------------------- 1 | # ~6:30 2 | # n, m, h = map(int, input().split()) 3 | n, m, h = 7, 1, 5 4 | # n, m, h = 2, 1, 3 5 | # n, m, h = 10, 1, 30 6 | import time 7 | 8 | 9 | lines = [[0]*(n-1) for _ in range(h)] # h X n 10 | for _ in range(m): 11 | x, y = map(int, input().split()) 12 | lines[x-1][y-1] = 1 13 | 14 | # 도착 숫자 리턴하는 함수 구현 15 | def arrive(lines): 16 | flist = list(range(1,n+1)) 17 | # 매 가로줄마다 사다리 놓인 곳의 숫자를 바꿈 18 | for ix in range(h): 19 | for iy in range(n-1): 20 | if lines[ix][iy] == 1: 21 | flist[iy], flist[iy+1] = flist[iy+1], flist[iy] 22 | return flist 23 | 24 | def check(lines, startx, starty, count): # startx, starty 처음에 0,0 25 | global max_count 26 | 27 | if m == 0: 28 | max_count = 0 29 | return 30 | 31 | if arrive(lines) == list(range(1,n+1)): 32 | print('found') 33 | time.sleep(1) 34 | if max_count == -1 or count < max_count: 35 | max_count = count 36 | return 37 | 38 | if count == 3 or (0 < max_count <= count): 39 | return 40 | 41 | # time.sleep(1) 42 | # print('lines:') 43 | # for l in lines: 44 | # print(l) 45 | 46 | 47 | 48 | for x in range(max(0,startx), h): 49 | for y in range(n-1): 50 | if (x == startx and y < starty) or lines[x][y] == 1: 51 | continue 52 | else: # 비어있으면 - 주변 체크 53 | empty = True 54 | for i in range(2): 55 | ny = y + dy[i] 56 | if 0 <= ny < n-1: 57 | if lines[x][ny] == 1: # 근처에 이미 놓아져 있으면 58 | empty = False 59 | break 60 | if empty: 61 | # new_lines = [l[:] for l in lines] 62 | lines[x][y] = 1 63 | check(lines, x, y+2, count+1) 64 | lines[x][y] = 0 65 | return 66 | 67 | 68 | dy = (-1,1) 69 | max_count = -1 70 | check(lines, -1, -1, 0) 71 | print(max_count) 72 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_구현_시험감독_1회답.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | al = list(map(int,input().split())) 3 | b,c = map(int, input().split()) 4 | 5 | ''' 6 | 총감독 : 각각의 시험장 1명. 7 | 부감독 : 제한없음. 8 | 총감독 한명당 b명. 부감독 한명당 c명 9 | ''' 10 | 11 | '''구현? 12 | 각 리스트에서 13 | ''' 14 | 15 | sup = n # 총감독 수 n명 16 | 17 | for a in al: 18 | a -= b 19 | if a <= 0: 20 | continue 21 | elif a % c == 0: # a 여전히 남고 부감독 딱 맞는경우 22 | second = a // c # 시험장 당 부감독 수. 남는학생은 부감독 하나더 23 | elif a % c != 0: 24 | second = a // c + 1 25 | 26 | sup += second # 총에 부감독 수 추가 27 | 28 | print(sup) 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_구현_시험감독_2회.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | al = list(map(int,input().split())) 3 | b,c = map(int, input().split()) 4 | 5 | ''' 6 | 총감독 : 각각의 시험장 1명. 7 | 부감독 : 제한없음. 8 | 총감독 한명당 b명. 부감독 한명당 c명 9 | ''' 10 | 11 | '''구현? 12 | 각 리스트에서 13 | ''' 14 | 15 | sup = n # 총감독 수 n명 16 | 17 | for a in al: 18 | a -= b 19 | if a <= 0: 20 | continue 21 | elif a % c == 0: # a 여전히 남고 부감독 딱 맞는경우 22 | second = a // c # 시험장 당 부감독 수. 남는학생은 부감독 하나더 23 | elif a % c != 0: 24 | second = a // c + 1 25 | 26 | sup += second # 총에 부감독 수 추가 27 | 28 | print(sup) 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_그래프_최단경로_1회답.py: -------------------------------------------------------------------------------- 1 | import heapq, math 2 | 3 | v, e = map(int, input().split()) 4 | start = int(input()) 5 | graph = [[] for _ in range(v+1)] 6 | for _ in range(e): 7 | a, b, c = map(int, input().split()) 8 | graph[a].append((b, c)) 9 | 10 | 11 | INF = math.inf 12 | distance = [INF]*(v+1) 13 | 14 | # 다익스트라 15 | def dijkstra(start): 16 | q = [] 17 | # 시작 노드 최단 경로는 0으로 설정하고 큐에 삽입 18 | heapq.heappush(q, (0, start)) 19 | distance[start] = 0 20 | while q: 21 | dist, now = heapq.heappop(q) # 제일 짧은 거리부터 불러옴 22 | if dist > distance[now]: # 이미 거리가 짧은 경우 갱신 필요 없음 23 | continue 24 | for next, length in graph[now]: 25 | cost = dist + length 26 | if cost < distance[next]: 27 | distance[next] = cost 28 | heapq.heappush(q, (cost, next)) 29 | 30 | 31 | 32 | dijkstra(start) 33 | for d in distance[1:]: 34 | if d == INF: 35 | print('INF') 36 | else: 37 | print(d) -------------------------------------------------------------------------------- /solution_codes/baekjoon_그래프_택배 배송_1회.py: -------------------------------------------------------------------------------- 1 | # ~11:30 2 | import heapq 3 | n, m = map(int, input().split()) 4 | 5 | # 다익스트라 - 먼저 dist, graph 를 정의 6 | # dist는 무한으로 초기화 7 | INF = int(1e9) 8 | dist = [INF]*(n+1) 9 | graph = [[] for _ in range(n+1)] 10 | for _ in range(m): 11 | a, b, c = map(int, input().split()) 12 | graph[a].append((b,c)) 13 | graph[b].append((a,c)) 14 | 15 | # 다익스트라 시작 - 먼저 start 노드의 거리를 0으로 하고 q에 넣음 16 | def dijkstra(start): 17 | q = [] 18 | dist[start] = 0 19 | heapq.heappush(q, (0, start)) 20 | while q: 21 | cost, now = heapq.heappop(q) 22 | if dist[now] < cost: 23 | continue 24 | # cost가 dist[now]보다 작으면, 최단거리후보이므로 q에 넣는 것. 25 | for next, length in graph[now]: 26 | # now에서 이어진 next와 길이 length 27 | if cost + length < dist[next]: 28 | dist[next] = cost + length 29 | heapq.heappush(q, (cost + length, next)) 30 | 31 | dijkstra(1) 32 | print(dist[n]) 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_그래프_한 줄로 서기_1회.py: -------------------------------------------------------------------------------- 1 | # 줄을 어떻게 서야 하는지 완성해야 함 2 | from itertools import combinations 3 | from collections import deque 4 | ''' 5 | 위상 정렬 6 | 목적 : '방향성에 거스르지 않도록 모든 노드를 순서대로 나열하는 것' 7 | 1. 진입차수가 0인 노드를 큐에 넣는다. 8 | 2. 큐가 빌 때까지 다음을 반복한다. 9 | 1) 큐에서 원소를 꺼내 해당 노드 출발간선을 그래프에서 제거한다. 10 | 2) 진입차수가 0이 된 노드를 큐에 넣는다. 11 | ''' 12 | 13 | n = int(input()) 14 | 15 | left_tall = [0] + list(map(int, input().split())) 16 | # 0 , 2 1 1 0 17 | 18 | # 자신보다 키큰사람을 가리키는 간선 그래프 (X) 19 | # 처음 그래프는 자신이외 모든 사람을 가리켜야 함 20 | graph = [[]] + [list(range(1, n+1)) for _ in range(1, n+1)] 21 | for i in range(1, n+1): 22 | graph[i].remove(i) 23 | print(graph) 24 | 25 | # graph에서 left_tall 만큼 뽑고, 그것이 위상정렬 되는지 확인하며 진행 26 | comb_graph = [[]] + \ 27 | [list(combinations(graph[i], left_tall[i])) for i in range(1, n+1)] 28 | print(comb_graph) 29 | 30 | def dfs(output_graph, t): # -> graph를 반환해야 함 31 | if t == n: 32 | print('graph_to_topology:', output_graph) 33 | result = topology(output_graph) 34 | if len(result) < n: 35 | return 36 | elif len(result) == n: 37 | print(result) 38 | return 39 | 40 | else: 41 | new_output = output_graph[:] 42 | for comb in comb_graph[t]: 43 | new_output[t] = list(comb) 44 | dfs(new_output, t+1) 45 | 46 | def topology(graph): 47 | indegree = [0]*(n+1) 48 | for node in range(1, n+1): 49 | for next in graph[node]: 50 | indegree[next] += 1 51 | result = [] 52 | q = deque() 53 | 54 | # 처음은 차수 0인 노드 큐 삽입 55 | for i in range(1, n+1): 56 | if indegree[i] == 0: 57 | q.append(i) 58 | 59 | # 큐가 빌 때까지 반복 60 | while q: 61 | now = q.popleft() 62 | result.append(now) # 큐에 들어간 노드 순서대로 출력하면됨 63 | # 해당 원소와 연결된 노드 진입차수에서 1 빼기 64 | for i in graph[now]: 65 | indegree[i] -= 1 66 | # 새롭게 진입차수 0이 되는 노드를 큐에 삽입 67 | if indegree[i] == 0: 68 | q.append(i) 69 | return result 70 | 71 | 72 | 73 | 74 | dfs([[] for _ in range(n+1)], 1) 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_그리디_보석 도둑_1회답.py: -------------------------------------------------------------------------------- 1 | # ~ 12:00 2 | import sys 3 | import heapq 4 | 5 | input = sys.stdin.readline 6 | 7 | n, k = map(int, input().split()) 8 | seq = [tuple(map(int, input().split())) for _ in range(n)] # (무게, 가격) ] 9 | 10 | bags = [int(input()) for _ in range(k)] 11 | 12 | ''' 13 | 가장 무게 작은 용량의 가방부터 14 | 무게 같거나 작은 보석들을 heap에 가격을 집어넣는다 (보석은 무게순) 15 | 이때 같은 가격이면 무게 무거운것부터 넣어주어야 가장 무거운 것이 처음으로 오게됨. 16 | 즉 사전에 보석을 무거운것부터 정렬해 주어야 함 17 | 그리고 heap에서 pop하면 가장 가격 높고, 무거운것이 탐색할 필요없이 처음으로 딱 나온다. 18 | ''' 19 | 20 | # 무게 큰것 순으로 정렬. 가격은 heap 인덱스로 넣으므로 정렬 필요없음. 21 | seq.sort() # 무게 오름차순으로 정렬 22 | bags.sort() # 가방도 오름차순으로 정렬 23 | 24 | # print('check queue') 25 | # print(q) 26 | total = 0 27 | temp = [] 28 | for i in range(k): 29 | bag = bags[i] 30 | # print('bag weight:', bag) 31 | while seq and bag >= seq[0][0]: # 무게 32 | weight, price = seq.pop(0) 33 | # print(weight, price) 34 | heapq.heappush(temp, -price) # 음수로 넣으면 heappop 시 최댓값부터 -로 반환시킴 35 | # print(temp, seq) 36 | if temp: 37 | total -= heapq.heappop(temp) 38 | elif not seq: 39 | break 40 | 41 | print(total) 42 | 43 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_백트래킹_소문난 칠공주_1회답.py: -------------------------------------------------------------------------------- 1 | board = [list(input()) for _ in range(5)] 2 | 3 | # 7명 결성. 4명은 무조건 S로 포함 4 | dx = (-1, 1, 0, 0) 5 | dy = (0, 0, -1, 1) 6 | all_group = list() # {(x, y), (x1, y1)} 으로 구성된 리스트 7 | dup_count = 0 8 | # 모든 경우로 재귀 -> 연결된 경우, S 4개인경우를 리턴 - 백트래킹 9 | def dfs(ppls: list, group: list, visited: list): 10 | global dup_count 11 | if ppls.count('Y') >= 4: 12 | return 13 | # exit 14 | if len(ppls) == 7: 15 | # S 4이상 - all_group에 있는지 보고 없으면 추가하기 16 | if ppls.count('S') >= 4: 17 | if set(group) not in all_group: 18 | all_group.append(set(group)) 19 | else: 20 | # print(group) 21 | dup_count += 1 22 | return 23 | else: 24 | for gx, gy in group: 25 | for i in range(4): 26 | nx, ny = gx + dx[i], gy + dy[i] 27 | if 0 <= nx < 5 and 0 <= ny < 5: 28 | if not visited[nx][ny]: 29 | visited[nx][ny] = True 30 | group.append((nx, ny)) 31 | ppls.append(board[nx][ny]) 32 | # 재귀 33 | dfs(ppls, group, visited) 34 | visited[nx][ny] = False 35 | group.pop(-1) 36 | ppls.pop(-1) 37 | 38 | for x in range(5): 39 | for y in range(5): 40 | if board[x][y] == 'S': 41 | visited = [[False]*5 for _ in range(5)] 42 | visited[x][y] = True 43 | dfs(list(board[x][y]), [(x, y)], visited) 44 | 45 | print(len(all_group)) 46 | print('duplicated:', dup_count) 47 | 48 | # for g in all_group: 49 | # print('===========') 50 | # bb = [[False]*5 for _ in range(5)] 51 | # for gx, gy in g: 52 | # bb[gx][gy] = True 53 | # for b in bb: 54 | # print(b) 55 | 56 | # print(all_group) 57 | 58 | 59 | # print(len(all_group)) 60 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_브루트포스_하늘에서 별똥별이 빗발친다_1회.py: -------------------------------------------------------------------------------- 1 | n, m, l, k = map(int, input().split()) 2 | star_loc = [list(map(int, input().split())) for _ in range(k)] 3 | 4 | ''' 5 | 1. bf - 하나씩 이동하면서 몇개튕겨내는지 계산 6 | 2. 좌표 정렬 - x최소, 7 | ''' 8 | 9 | max_stars = 0 10 | 11 | xgrid = [] 12 | ygrid = [] 13 | for x, y in star_loc: 14 | xgrid.append(x) 15 | ygrid.append(y) 16 | xgrid = list(set(xgrid)) 17 | ygrid = list(set(ygrid)) 18 | xgrid.sort() 19 | ygrid.sort() 20 | 21 | xarea = [-l, -l, l, l] 22 | yarea = [l, -l, l, -l] 23 | 24 | for x in xgrid: 25 | for y in ygrid: 26 | for i in range(4): 27 | stars = 0 28 | xm, ym = x + xarea[i], y + yarea[i] 29 | for sx, sy in star_loc: 30 | if x <= sx <= xm and y <= sy <= ym: 31 | stars += 1 32 | if max_stars < stars: 33 | max_stars = stars 34 | 35 | print(k-max_stars) 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_소수_소수 구하기_1회답.py: -------------------------------------------------------------------------------- 1 | # 에라토스테네스의 체 2 | import math 3 | 4 | m, n = map(int, input().split()) 5 | # m,n = 3, 16 6 | isnum = [True]*(n+1) 7 | isnum[1] = False 8 | isnum[0] = False 9 | for i in range(2, int(math.sqrt(n))+1): 10 | #소수 2부터 가장 큰수의 제곱근까지 배수를 지워나감 11 | if isnum[i]: 12 | j = 2 # 자기자신 이외니까 2부터 곱함 13 | while i*j <= n: 14 | if isnum[i * j]: 15 | isnum[i * j] = False 16 | j += 1 17 | for i in range(m, n+1): 18 | if isnum[i]: 19 | print(i) -------------------------------------------------------------------------------- /solution_codes/baekjoon_순열조합_암호 만들기_1회.py: -------------------------------------------------------------------------------- 1 | 2 | from itertools import combinations 3 | l, c = map(int, input().split()) 4 | ch_list = input().split() 5 | 6 | # l,c = 4, 6 7 | # ch_list = ['a','t','c','i','s','w'] 8 | 9 | vowel = list('aeiou') 10 | # 조합 - 정렬하여 출력 11 | for ans in combinations(sorted(ch_list), l): 12 | loc = [v in ans for v in vowel] 13 | if any(loc): 14 | if l - sum(loc) >= 2: 15 | print(''.join(ans)) 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_시뮬레이션_킹_1회.py: -------------------------------------------------------------------------------- 1 | kp, sp, n = input().split() 2 | kc, kr = list(kp) 3 | sc, sr = list(sp) 4 | n = int(n) 5 | 6 | for i in range(ord('A'), ord('H')+1): 7 | if ord(kc) == i: 8 | kca = ord(kc)-ord('A') 9 | if ord(sc) == i: 10 | sca = ord(sc)-ord('A') 11 | 12 | kc, sc = kca, sca 13 | kr = int(kr) - 1 14 | sr = int(sr) - 1 15 | 16 | coms = [input() for _ in range(n)] 17 | 18 | arrow = ['R', 'L', 'B', 'T', 'RT', 'LT', 'RB', 'LB'] 19 | dx = (0, 0, -1, 1, 1, 1, -1, -1) 20 | dy = (1, -1, 0, 0, 1, -1, 1, -1) 21 | 22 | for c in coms: 23 | for i, di in enumerate(arrow): 24 | if c == di: 25 | nx = kr + dx[i] 26 | ny = kc + dy[i] 27 | if nx < 0 or nx >= 8 or ny < 0 or ny >= 8: 28 | break 29 | elif (nx, ny) == (sr, sc): 30 | sx = sr + dx[i] 31 | sy = sc + dy[i] 32 | if sx < 0 or sx >= 8 or sy < 0 or sy >= 8: 33 | break 34 | sr, sc = sx, sy 35 | kr, kc = nx, ny 36 | break 37 | # col + row 38 | # king 39 | print(chr(ord('A') + kc) + str(kr+1)) 40 | 41 | # stone 42 | print(chr(ord('A') + sc) + str(sr+1)) -------------------------------------------------------------------------------- /solution_codes/baekjoon_이분탐색_도토리 숨기기_1회답.py: -------------------------------------------------------------------------------- 1 | n, k, d = map(int, input().split()) 2 | 3 | rules = [list(map(int, input().split())) for _ in range(k)] 4 | 5 | 6 | # 이분 탐색 -> 7 | def check_last(box): 8 | count = 0 9 | max_st = 0 10 | for start, end, width in rules: 11 | if start <= box: 12 | st = start 13 | if max_st < st: 14 | max_st = st 15 | while st <= box and st <= end: 16 | count += 1 17 | st += width 18 | if max_st < st: 19 | max_st = st 20 | return max_st, count 21 | 22 | def binary_search(start, end): 23 | 24 | if start > end: 25 | return False 26 | else: 27 | mid = (start + end) // 2 28 | st, check = check_last(mid) 29 | if check == d: 30 | (st, check) == (mid, d): 31 | 32 | 33 | elif check < d: # 마지막보다 앞 - 뒤 탐색 34 | return binary_search(mid+1, end) 35 | elif check > d: # 마지막 상자보다 뒤 - 앞 탐색 36 | return binary_search(start, mid) 37 | 38 | print(binary_search(1, n)) 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_이분탐색_흩날리는 시험지 속에서 내 평점이 느껴진거야_1회답.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 이분탐색 3 | parametric search 4 | 주어진 그룹에서 점수 x가 가능한지? 5 | 가능하면 더 늘리고, 가능하지 않으면 줄인다. 6 | 7 | 점수의 최솟값 : x 8 | x: 10 9 | 12 7 19 20 17 14 9 / 10 10 | 하지만 이 경우에는 그룹 최댓값이 더 커질 수 있음 11 | x를 하한선으로 하여 12 | 13 | 1) 양수이기 때문에 14 | 만들수 있는 최소한의 그룹을 만든다 -> 그래야 합이 커짐 15 | 2) 주어진 x에서 최소한의 그룹을 만들려면? 16 | -> 최대한 각 그룹이 x를 채우도록 함 17 | 3) x로 최소한의 그룹을 만들었는데 그룹 수가 넘어가면 18 | -> 더 큰 x 제한을 두고 그룹 만들기 19 | 4) 더 작은 x 경우는? 20 | -> 그룹수가 k만큼 다다르지 않으면 (제한이 너무 큼) 21 | ''' 22 | 23 | 24 | n, k = map(int, input().split()) 25 | nums = list(map(int, input().split())) 26 | 27 | start, end = 0, int(10**5)*20 + 1 28 | value = 0 29 | while start < end: 30 | mid = (start + end) // 2 31 | print('mid:', mid) 32 | # mid 점수를 최대로 할 때 - 그룹 수 체크 33 | groups = 0 34 | sum_ = 0 35 | for i in nums: 36 | sum_ += i 37 | if sum_ >= mid: 38 | sum_ = 0 39 | groups += 1 40 | if groups > k: 41 | break 42 | if groups >= k: 43 | value = mid 44 | # 더 큰 x를 탐색 45 | start = mid+1 46 | else: # 생성된 그룹이 너무 적다 -> k를 더 작게 47 | end = mid-1 48 | 49 | print(value) 50 | 51 | 52 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_정규식_FBI_1회.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | order = [] 4 | exists = False 5 | for i in range(5): 6 | text = input() 7 | if re.search('FBI', text) != None: 8 | order.append(str(i+1)) 9 | exists = True 10 | if not exists: 11 | print('HE GOT AWAY!') 12 | else: 13 | print(' '.join(order)) 14 | 15 | 16 | import re 17 | print(re.sub(r'([aeiou])p\1', r'\1', input())) -------------------------------------------------------------------------------- /solution_codes/baekjoon_정규식_javavsc_1회.py: -------------------------------------------------------------------------------- 1 | # 밑줄 있으면 c, 대문자 있으면 java 2 | # java - 첫단어 소문자, 다음단어부터는 첫글자만 대문자. -대문자로 단어 파악 3 | # c - _로 단어 파악 4 | import re 5 | text = input() 6 | # 탈락조건 : 첫번째 대문자. 밑줄과 대문자가 같이 있는 경우. 7 | # 탈락조건 통과 - java - 대문자를 소문자로 바꾸고 _소문자 로 치환. 8 | # c - _소문자 를 대문자로 치환. 9 | def answer(): 10 | # global newtext 11 | if text[0] == '_' or text[-1] == '_' or \ 12 | re.search('_{2,}',text) or text[0].isupper() or \ 13 | (re.search('_',text) and re.search('[A-Z]',text)): 14 | print('Error!') 15 | return 16 | elif re.search('_',text): 17 | # _소문자 -> 대문자 18 | newtext = re.sub('_[a-z]', lambda x: x.group(1).upper(),text) 19 | elif re.search('[A-Z]',text): 20 | # 대문자 -> _소문자 21 | newtext = re.sub('[A-Z]', lambda x: '_'+x.group(0).lower(), text) 22 | else: 23 | newtext = text 24 | print(newtext) 25 | return 26 | 27 | answer() 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_정규식_모음의개수_1회.py: -------------------------------------------------------------------------------- 1 | import re 2 | # text = '''How are you today? 3 | # Quite well, thank you, how about yourself? 4 | # I live at number twenty four. 5 | # ''' 6 | 7 | while True: 8 | text = input() 9 | if text == '#': 10 | break 11 | vow_list = re.findall('[aeiou]', text) 12 | print(len(vow_list)) 13 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_정규식_문서 검색_1회.py: -------------------------------------------------------------------------------- 1 | import re 2 | text = input() 3 | word = input() 4 | # 처음부터 매치시켜서 없애 나간다. greedy 5 | print(len(re.findall(word,text))) -------------------------------------------------------------------------------- /solution_codes/baekjoon_정규식_창영이의일기장_1회.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | text = input() 4 | pat = 'aeiou' 5 | for i in range(5): 6 | text = re.sub(pat[i]+'p'+pat[i],pat[i],text) 7 | print(text) -------------------------------------------------------------------------------- /solution_codes/baekjoon_정규식_출력형식이잘못되었습니다_1회.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 대소문자 차이 없이 같게봄 3 | 공백 유무만 봄 4 | ({[,]}) 같음 5 | , ; 같음 6 | ''' 7 | import re 8 | k = int(input()) 9 | 10 | 11 | text_list = [] 12 | for _ in range(k*2): 13 | text_list.append(input()) 14 | 15 | 16 | for j in range(k): 17 | check_list = [] 18 | for i in range(2): 19 | text = text_list.pop(0) 20 | text = text.lower() # 소문자로 통일 21 | text = re.sub('[{[(]',' ( ',text) 22 | text = re.sub('[]})]',' ) ',text) # 괄호 () 로 통일 23 | text = re.sub('[;,]',' , ',text) 24 | text = re.sub(':',' : ',text) 25 | text = re.sub('\.',' \. ',text) 26 | text = re.sub(' {1,}', ' ',text) # 공백 1개로 통일 27 | text = text.strip() # 양옆 공백 제거 28 | 29 | # 다 끝났으면 text_list에 추가 30 | check_list.append(text) 31 | 32 | # print(check_list) 33 | print(f'Data Set {j+1}:', end=' ') 34 | if check_list[0] == check_list[1]: 35 | if j != k-1: 36 | print('equal\n') 37 | else: 38 | print('equal') 39 | else: 40 | if j != k-1: 41 | print('not equal\n') 42 | else: 43 | print('not equal') 44 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_최단거리_파티_1회.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | n, m, x = map(int, input().split()) 4 | input_list = [list(map(int, input().split())) for _ in range(m)] 5 | graph = [[] for _ in range(n+1)] 6 | 7 | for start, end, dist in input_list: 8 | graph[start].append((dist, end)) # 거리, 다음노드 9 | 10 | def dijkstra(start): 11 | q = [] 12 | INF = int(1e9) 13 | dist = [INF] * (n+1) 14 | # start 부터 거리 0으로 q에 삽입 15 | heapq.heappush(q, (0, start)) 16 | dist[start] = 0 17 | while q: 18 | now_dist, now_node = heapq.heappop(q) 19 | if dist[now_node] < now_dist: 20 | continue 21 | for next_dist, next_node in graph[now_node]: 22 | cost = now_dist + next_dist # 힙에서 나온 거리 + 그래프 간선 거리 23 | if cost < dist[next_node]: # 다음 노드까지의 최단거리보다 cost가 작으면 갱신 24 | dist[next_node] = cost 25 | heapq.heappush(q, (cost, next_node)) # 갱신한 다음노드와 다음노드까지의 거리를 힙에 삽입 26 | 27 | return dist 28 | 29 | total_dist = [0]*(n+1) 30 | for i in range(1, n+1): #1~n 31 | total_dist[i] += dijkstra(i)[x] 32 | total_dist[i] += dijkstra(x)[i] 33 | 34 | 35 | print(max(total_dist[1:])) 36 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_최단거리_파티_2회.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | n, m, x = map(int, input().split()) 4 | 5 | vertex = [list(map(int, input().split())) for _ in range(m)] 6 | # 시작, 끝, 비용 7 | graph = [[] for _ in range(n+1)] 8 | 9 | for st, en, cost in vertex: 10 | graph[st].append((en, cost)) 11 | 12 | 13 | INF = int(1e9) 14 | 15 | def dijkstra(start): 16 | distance = [INF]*(n+1) 17 | distance[start] = 0 18 | q = [] 19 | heapq.heappush(q, (0, start)) 20 | while q: 21 | dist, now = heapq.heappop(q) 22 | if distance[now] < dist: 23 | continue 24 | for node, cost in graph[now]: 25 | if dist + cost < distance[node]: 26 | distance[node] = dist + cost 27 | heapq.heappush(q, (dist+cost, node)) 28 | return distance 29 | 30 | max_dist = 0 31 | for st in range(1, n+1): 32 | route = dijkstra(st)[x] + dijkstra(x)[st] 33 | if max_dist < route: 34 | max_dist = route 35 | print(max_dist) 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_투포인터_두 수의 합2_1회.py: -------------------------------------------------------------------------------- 1 | def solution(n, k, nums): 2 | # 합이 k에 가장 가까운 조합의 수 구하기 3 | nums.sort() 4 | left, right = 0, n-1 5 | min_diff = float('inf') 6 | count = 0 7 | while left < right: 8 | sum_ = nums[left] + nums[right] 9 | diff = abs(k - sum_) 10 | if min_diff > diff: 11 | count = 1 # 새로운 최솟값 나옴 12 | min_diff = diff 13 | elif min_diff == diff: 14 | count += 1 15 | 16 | if sum_ == k: 17 | left += 1 18 | right -= 1 19 | elif sum_ < k: 20 | left += 1 21 | else: 22 | right -= 1 23 | 24 | return count 25 | 26 | t = int(input()) 27 | for _ in range(t): 28 | n, k = map(int, input().split()) 29 | nums = list(map(int, input().split())) 30 | print(solution(n, k, nums)) -------------------------------------------------------------------------------- /solution_codes/baekjoon_투포인터_두 수의 합_1회.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | seq = list(map(int, input().split())) 3 | x = int(input()) 4 | 5 | # n = 9 6 | # seq = [5,12,7,10,9,1,2,3,11] 7 | # x = 13 8 | 9 | # 2 pointers 10 | left = 0 11 | right = n-1 12 | seq.sort() 13 | 14 | ans = 0 15 | while left < right: 16 | if seq[left] + seq[right] == x: 17 | ans += 1 18 | right -= 1 19 | elif seq[left] + seq[right] > x: 20 | right -= 1 21 | else: 22 | left += 1 23 | print(ans) 24 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_투포인터_두 용액_1회.py: -------------------------------------------------------------------------------- 1 | # ~7:40 2 | n = int(input()) 3 | seq = list(map(int, input().split())) 4 | seq.sort() 5 | 6 | left = 0 7 | right = n-1 8 | 9 | min_sum = (int(1e13), int(1e13)) 10 | exited = False 11 | while left < right: 12 | if seq[left] + seq[right] == 0: 13 | print(seq[left], seq[right]) 14 | exited = True 15 | break 16 | elif seq[left] + seq[right] < 0: 17 | if abs(sum(min_sum)) > abs(seq[left] + seq[right]): 18 | min_sum = (seq[left], seq[right]) 19 | left += 1 20 | else: 21 | if abs(sum(min_sum)) > abs(seq[left] + seq[right]): 22 | min_sum = (seq[left], seq[right]) 23 | right -= 1 24 | 25 | if not exited: 26 | print(min_sum[0], min_sum[1]) 27 | 28 | -------------------------------------------------------------------------------- /solution_codes/baekjoon_투포인터_두 용액_2회.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | n = int(input()) # 2~100000 4 | 5 | liq = list(map(int, input().split())) 6 | liq.sort() 7 | 8 | lp, rp = 0, n-1 9 | cand = [] 10 | min_ = 1<<100 11 | while lp < rp: 12 | sum_ = liq[lp] + liq[rp] 13 | if min_ > abs(sum_): 14 | min_ = abs(sum_) 15 | heapq.heappush(cand, (abs(sum_), (liq[lp], liq[rp]))) 16 | if sum_ == 0: 17 | break 18 | elif sum_ < 0: 19 | lp += 1 20 | elif sum_ > 0: 21 | rp -= 1 22 | 23 | print(*heapq.heappop(cand)[1]) 24 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_DP_금광_1회.py: -------------------------------------------------------------------------------- 1 | # 첫번째 열 어느 행이든 출발 가능 2 | # 출발 이후엔 열 개수 M 만큼 오른쪽위, 오른쪽, 오른쪽아래 세방향으로만 이동가능 3 | # ~12:00 4 | # dp 5 | # 점화식 - f(k) = f(k-1) + m 6 | n, m = map(int, input().split()) 7 | 8 | input_list = list(map(int, input().split())) 9 | board = [[0]*m for _ in range(n)] 10 | for x in range(n): 11 | for y in range(m): 12 | num = input_list.pop(0) 13 | board[x][y] = num 14 | 15 | dx = (-1,0,1) 16 | cand = [] 17 | def dfs(x, y, total): 18 | total += board[x][y] 19 | for i in range(3): 20 | nx = x + dx[i] 21 | ny = y + 1 22 | if ny == m: 23 | cand.append(total) 24 | return 25 | elif (0 <= nx < n) and (0 <= ny < m): 26 | dfs(nx, ny, total) 27 | else: 28 | return None 29 | 30 | import time 31 | 32 | t0 = time.time() 33 | for i in range(n): 34 | dfs(i, 0, 0) 35 | 36 | print(cand) 37 | print(max(cand)) 38 | print(time.time() - t0) 39 | 40 | 41 | 42 | 43 | 44 | 45 | def dp_tab(): 46 | tab = [[0]*m for _ in range(n)] 47 | for i in range(n): 48 | tab[i][0] = board[i][0] 49 | 50 | for y in range(1, m): 51 | for x in range(0, n): 52 | fm = [] 53 | for i in range(3): 54 | nx = x + dx[i] 55 | if (0 <= nx < n): 56 | fm.append(tab[nx][y-1]) 57 | print(x, y, fm) 58 | tab[x][y] = board[x][y] + max(fm) 59 | return tab 60 | 61 | t0 = time.time() 62 | ans_table = dp_tab() 63 | 64 | # print('ans_table') 65 | # for ans in ans_table: 66 | # print(ans) 67 | 68 | 69 | ans_cand = [] 70 | for i in range(n): 71 | ans_cand.append(ans_table[i][m-1]) 72 | 73 | print(max(ans_cand)) 74 | print(time.time() - t0) 75 | 76 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_DP_못생긴 수_1회.py: -------------------------------------------------------------------------------- 1 | # 2, 3, 5를 곱해가면서 작은 수부터 나열 2 | # ~ 11:20 3 | def ugly(n): 4 | tab = [1]*n 5 | for j in range(1, n): 6 | cand = [] 7 | for i in range(j): 8 | for mul in [2,3,5]: 9 | multi = tab[i]*mul 10 | if multi > tab[j-1]: 11 | cand.append(multi) 12 | tab[j] = min(cand) 13 | return tab[n-1] 14 | 15 | 16 | 17 | n = int(input()) 18 | print(ugly(n)) 19 | 20 | 21 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_DP_편집 거리_1회답.py: -------------------------------------------------------------------------------- 1 | # 삽입, 삭제, 교체 2 | # 연산 수를 최소화 3 | # ~12:00 4 | a = 'cat' 5 | 6 | b = 'cut' 7 | 8 | table = [[0]*(len(b)+1) for _ in range(len(a)+1)] 9 | 10 | table[0] = list(range(len(b)+1)) 11 | num = 0 12 | for i in range(len(table)): 13 | table[i][0] = num 14 | num += 1 15 | 16 | for col in range(1, len(b)+1): 17 | for row in range(1, len(a)+1): 18 | if a[row-1] == b[col-1]: 19 | table[row][col] = table[row-1][col-1] 20 | else: 21 | table[row][col] = 1+ min(table[row-1][col], 22 | table[row-1][col-1], 23 | table[row][col-1] 24 | ) 25 | 26 | for t in table: 27 | print(t) 28 | 29 | print(table[-1][-1]) 30 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_dfsbfs_DFS와BFS_1회.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 3 | 탐색을 시작할 정점의 번호 V가 주어진다. 4 | 5 | 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 6 | 7 | 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다. 8 | ''' 9 | from collections import deque 10 | 11 | n,m,v = map(int, input().split()) 12 | 13 | link = [] 14 | for _ in range(m): 15 | a, b = map(int, input().split()) 16 | if a <= b: 17 | link.append([a,b]) 18 | else: 19 | link.append([b,a]) 20 | 21 | # n,m,v = 1000, 1, 1000 22 | # link = [ 23 | # [999,1000] 24 | # ] 25 | 26 | link = sorted(link) 27 | ### dfs 28 | visited = [v] # 방문 29 | 30 | def dfs(node): 31 | for a, b in link: 32 | if a == node and b not in visited: 33 | visited.append(b) 34 | dfs(b) 35 | elif b == node and a not in visited: 36 | visited.append(a) 37 | dfs(a) 38 | 39 | # print(a,b) 40 | 41 | 42 | dfs(v) 43 | # print('dfs') 44 | # print(visited) 45 | for i in range(len(visited)): 46 | if i == len(visited)-1: 47 | print(visited[i]) 48 | else: 49 | print(visited[i], end=' ') 50 | 51 | 52 | ### bfs 53 | q = deque([]) 54 | 55 | bfs_visit = [v] 56 | q.append(v) 57 | 58 | 59 | def bfs(): 60 | while q: 61 | node = q.popleft() 62 | for a, b in link: 63 | if a == node and b not in bfs_visit: 64 | bfs_visit.append(b) 65 | q.append(b) 66 | elif b == node and a not in bfs_visit: 67 | bfs_visit.append(a) 68 | q.append(a) 69 | bfs() 70 | 71 | # print('bfs') 72 | for j in range(len(bfs_visit)): 73 | if j == len(bfs_visit)-1: 74 | print(bfs_visit[j]) 75 | else: 76 | print(bfs_visit[j], end=' ') 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_dfsbfs_경쟁적전염_1회.py: -------------------------------------------------------------------------------- 1 | # ~10:50 ~ 11:10 2 | ''' 3 | S초가 지난 후에 (X,Y)에 존재하는 바이러스의 종류를 출력하는 프로그램을 작성하시오. 4 | ''' 5 | from collections import deque 6 | 7 | n, k = map(int, input().split()) # 1~k까지의 바이러스 숫자 부여 8 | 9 | flask = [] 10 | for _ in range(n): 11 | flask.append(list(map(int, input().split()))) 12 | 13 | s, x, y = map(int, input().split()) 14 | 15 | # 초마다, 모든 바이러스에 대해서 숫자 순서대로 상하좌우를 살핀다. 16 | # 숫자 순서로 공백을 채워넣는다. 17 | loc_list = [[] for _ in range(k+1)] # 1~k 각각의 정보 18 | 19 | 20 | qlist = [] 21 | for row in range(n): 22 | for col in range(n): 23 | if flask[row][col] != 0: 24 | 25 | qlist.append((flask[row][col],row,col)) 26 | qlist = sorted(qlist, key=lambda x: x[0]) 27 | q = deque(qlist) # 1~k순서로 들어감 28 | 29 | ''' 30 | 방문 만들기. 31 | 방문 안했으면 방문처리. 32 | 근데 어떻게 순서대로 1,2,3? 33 | 옆에 비어있을때 한번씩만 채운다. 34 | ''' 35 | dx = (-1,0,1,0) 36 | dy = (0,-1,0,1) 37 | 38 | 39 | 40 | for _ in range(s): 41 | for _ in range(len(q)): 42 | num, qx, qy = q.popleft() 43 | # 상하좌우 조사 44 | for i in range(4): 45 | nx, ny = qx+dx[i], qy+dy[i] 46 | if nx >= 0 and ny >= 0 and nx < n and ny < n: 47 | if flask[nx][ny] == 0: 48 | flask[nx][ny] = num 49 | q.append((num,nx,ny)) 50 | 51 | 52 | print(flask[x-1][y-1]) 53 | 54 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_dfsbfs_괄호변환_1회.py: -------------------------------------------------------------------------------- 1 | p = input() 2 | 3 | # 올바른 괄호 문자열 판별 4 | def correct(p): 5 | count = 0 6 | for ch in p: 7 | if ch == '(': 8 | count += 1 9 | else: 10 | count -= 1 11 | if count < 0: 12 | return False 13 | if count == 0: 14 | return True 15 | else: 16 | return False 17 | 18 | # 균형잡힌 괄호 문자열 판별 19 | def divide(p): 20 | count = 0 21 | for i in range(len(p)): 22 | if p[i] == '(': 23 | count += 1 24 | else: 25 | count -= 1 26 | if count == 0: 27 | return p[:i+1], p[i+1:] 28 | 29 | def solution(p): 30 | if correct(p): 31 | return p 32 | else: 33 | u, v = divide(p) 34 | if correct(u): 35 | return u + solution(v) 36 | else: 37 | ans = '(' 38 | ans += solution(v) 39 | ans += ')' 40 | u = u[1:len(u)-1] 41 | for ch in u: 42 | if ch == '(': 43 | ans += ')' 44 | elif ch == ')': 45 | ans += '(' 46 | return ans 47 | 48 | 49 | 50 | print(solution(p)) 51 | 52 | 53 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_dfsbfs_맥주마시면서걸어가기_1회.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | t = int(input()) 4 | 5 | ans_list = [] 6 | 7 | for _ in range(t): 8 | n = int(input()) 9 | hx, hy = map(int, input().split()) 10 | conv_list = [] 11 | for _ in range(n): 12 | conv_list.append(list(map(int, input().split()))) 13 | px, py = map(int, input().split()) 14 | visited = [] 15 | 16 | def dfs(): 17 | st = deque([(hx,hy)]) 18 | while st: 19 | nx, ny = st.pop() 20 | visited.append((nx,ny)) 21 | if abs(nx-px) + abs(ny-py) <= 1000: 22 | return True 23 | else: 24 | for cx, cy in conv_list: 25 | if abs(nx-cx) + abs(ny-cy) <= 1000 and (cx,cy) not in visited: 26 | st.append((cx,cy)) 27 | return False 28 | if dfs(): 29 | ans_list.append('happy') 30 | else: 31 | ans_list.append('sad') 32 | 33 | 34 | # n, home, conv_list, px, py 35 | 36 | for ans in ans_list: 37 | print(ans) 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_dfsbfs_미로탐색_1회.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | n, m = map(int, input().split()) 4 | 5 | maze = [] 6 | for _ in range(n): 7 | maze.append(list(map(int, list(input())))) 8 | 9 | visited = [[False]*m for _ in range(n)] 10 | dx = (-1,1,0,0) 11 | dy = (0,0,-1,1) # 상하좌우 12 | def bfs(): 13 | q = deque() 14 | q.append((0,0)) 15 | visited[0][0] = 1 16 | while q: 17 | x, y = q.popleft() 18 | for i in range(4): 19 | nx = x + dx[i] 20 | ny = y + dy[i] 21 | if (0 <= nx < n and 0 <= ny < m) and maze[nx][ny] == 1 and not visited[nx][ny]: 22 | q.append((nx,ny)) 23 | visited[nx][ny] = visited[x][y] + 1 24 | 25 | bfs() 26 | print(visited[n-1][m-1]) 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_dfsbfs_빙산_1회.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | n, m = map(int, input().split()) 4 | 5 | ocean = [] 6 | for _ in range(n): 7 | ocean.append(list(map(int, input().split()))) 8 | 9 | dx = (-1,1,0,0) # 상하좌우 10 | dy = (0,0,-1,1) 11 | 12 | def melt(): 13 | global ocean 14 | melted = [o[:] for o in ocean] 15 | for x in range(n): 16 | for y in range(m): 17 | if ocean[x][y] > 0: # 빙산일때 18 | for i in range(4): 19 | nx = x + dx[i] # 주위 바다 조사 20 | ny = y + dy[i] 21 | if ocean[nx][ny] == 0 and melted[x][y] != 0: 22 | melted[x][y] -= 1 23 | ocean = [m[:] for m in melted] 24 | 25 | def pick(): 26 | for x in range(n): 27 | for y in range(m): 28 | if ocean[x][y] > 0: 29 | return x, y 30 | 31 | # bfs 32 | def bfs(): 33 | # 빙산 하나 찾기 34 | x, y = pick() 35 | 36 | # print('find', x, y) 37 | q = deque() 38 | visited = [[False]*m for _ in range(n)] 39 | q.append((x,y)) 40 | visited[x][y] = True 41 | while q: 42 | fx, fy = q.popleft() 43 | for i in range(4): 44 | nx = fx + dx[i] 45 | ny = fy + dy[i] 46 | if (0 <= nx < n and 0 <= ny < m) and ocean[nx][ny] > 0 and \ 47 | not visited[nx][ny]: 48 | q.append((nx,ny)) 49 | visited[nx][ny] = True 50 | 51 | 52 | return visited 53 | 54 | def find_div(visited): 55 | # visited False 중 0이 아닌 게 있으면 나눠진거임. 56 | for x in range(n): 57 | for y in range(m): 58 | if ocean[x][y] > 0 and not visited[x][y]: 59 | return True 60 | return False 61 | 62 | time = 0 63 | while True: 64 | time += 1 65 | melt() 66 | if sum([sum(o) for o in ocean]) == 0: 67 | print(0) 68 | break 69 | else: 70 | visited = bfs() 71 | 72 | if find_div(visited): 73 | print(time) 74 | break 75 | 76 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_dfsbfs_연산자끼워넣기_1회.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | n = int(input()) 4 | 5 | nums = list(map(int, input().split())) 6 | pl, mi, mu, di = map(int, input().split()) 7 | cal_list = '' 8 | for i in range(pl): 9 | cal_list += '+' 10 | for i in range(mi): 11 | cal_list += '-' 12 | for i in range(mu): 13 | cal_list += '*' 14 | for i in range(di): 15 | cal_list += '/' 16 | 17 | perm = list(set(permutations(cal_list))) 18 | 19 | # 연산자에서 하나씩 빼고 셈을 한다. 20 | minimal = 0 21 | maximal = 0 22 | 23 | checked = False 24 | for p in perm: 25 | for i in range(len(nums)): 26 | if i == 0: 27 | ans = nums[i] 28 | else: 29 | j = i-1 30 | if p[j] == '+': 31 | ans += nums[i] 32 | elif p[j] == '-': 33 | ans -= nums[i] 34 | elif p[j] == '*': 35 | ans *= nums[i] 36 | elif p[j] == '/': 37 | if ans >= 0: 38 | ans //= nums[i] 39 | else: 40 | ans = -(abs(ans) // nums[i]) 41 | if not checked: 42 | minimal = ans 43 | maximal = ans 44 | checked = True 45 | else: 46 | minimal = min(minimal, ans) 47 | maximal = max(maximal, ans) 48 | 49 | print(maximal) 50 | print(minimal) 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_dfsbfs_특정거리의도시찾기_1회.py: -------------------------------------------------------------------------------- 1 | # dfs - 스택, 재귀 2 | # bfs - 큐, for 3 | # ~3:30 #33 4 | from collections import deque 5 | ''' 6 | 최단 거리가 정확히 K인 모든 도시들의 번호를 출력하는 프로그램 7 | 최단 거리가 K인 모든 도시의 번호를 한 줄에 하나씩 오름차순으로 출력한다. 8 | 출발도시 번호 x 9 | ''' 10 | import sys 11 | input = sys.stdin.readline 12 | n,m,k,x = map(int, input().split()) 13 | 14 | connect = [[] for _ in range(n+1)] 15 | for _ in range(m): 16 | a, b = map(int, input().split()) 17 | connect[a].append(b) 18 | 19 | # connect = [] 20 | # for _ in range(m): 21 | # connect.append(list(map(int, input().split()))) 22 | 23 | start = x # 출발도시 24 | q = deque() 25 | visited = [-1]*(n+1) # 1~n 까지의 방문정보를 거리로 삽입 26 | 27 | q.append(start) 28 | visited[start] = 0 # 첫번째 방문처리 29 | 30 | while q: 31 | now = q.popleft() # 들어온 순서로 뻄. FIFO 32 | # for dpt, arr in connect: 33 | # if now == dpt: 34 | # if visited[arr] < 0: # 방문 안한 곳이라면 35 | # q.append(arr) 36 | # visited[arr] = visited[now] + 1 # 연결된 원래곳 거리 + 1 37 | for arr in connect[now]: 38 | if visited[arr] < 0: 39 | q.append(arr) 40 | visited[arr] = visited[now] + 1 41 | 42 | if k not in visited: 43 | print(-1) 44 | 45 | for num in range(len(visited)): 46 | if visited[num] == k: 47 | print(num) 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_구현_기둥과보설치_1회.py: -------------------------------------------------------------------------------- 1 | # ~7:00 2 | ''' 3 | 기둥 보 : 길이 1인 선분 4 | 기둥 : 바닥위 or 보 한쪽끝위, 또는 다른기둥 위에만 존재 5 | 보 : 한쪽끝이 기둥위, 또는 양쪽끝부분이 다른 보와 연결. 6 | 7 | 삭제 : 여전히 규칙 만족해야함 8 | 9 | build_frame: [x,y,a,b] 10 | (x,y) 좌표, (0 기둥 1 보), (0 삭제 1 설치) 11 | 12 | 13 | ''' 14 | # 걍 조건에 맞게 일일이 확인하면서 구현하면 될듯? 15 | n = 0 16 | build_frame = [[0,0,0,1],[2,0,0,1],[4,0,0,1],[0,1,1,1], 17 | [1,1,1,1],[2,1,1,1],[3,1,1,1],[2,0,0,0], 18 | [1,1,1,0],[2,2,0,1]] 19 | 20 | # build_frame = [[1,0,0,1],[1,1,1,1],[2,1,0,1],[2,2,1,1],[5,0,0,1],[5,1,0,1],[4,2,1,1],[3,2,1,1]] 21 | # 정렬 문제같음.. 22 | 23 | # 1. build_frame을 x기준 정렬, -> y기준 정렬 -> 모두 같은 경우 0-1 정렬(기둥-보) 24 | # 2. 설치와 삭제에서 조건을 만족하는지 확인하고 조건 안맞으면 삭제하기. 25 | # 3. 1) 순서대로 build_frame을 따라가고, 설치삭제가 조건 만족하는지 보고 붙임. 26 | # 4. 2) 끝까지 설치삭제 이루어졌으면, 정렬하면 끝. 27 | def check(build): 28 | for x,y,a in build: 29 | if a == 0: # 기둥 30 | if y == 0 or [x-1, y, 1] in build or [x, y, 1] in build or [x,y-1,0] in build: 31 | continue 32 | return False 33 | elif a == 1: # 보 - 한쪽끝이 기둥위, 또는 양쪽끝부분이 다른 보와 연결. 34 | if [x, y-1, 0] in build or [x+1, y-1, 0] in build or ([x-1, y, 1] in build and [x, y, 1] in build): 35 | continue 36 | return False 37 | 38 | return True 39 | 40 | 41 | def solution(n, build_frame): 42 | build_status = [] 43 | for i in range(len(build_frame)): 44 | x, y, a, b = build_frame[i] 45 | if b == 1: # 설치 46 | build_status.append([x,y,a]) 47 | if check(build_status): # 잘 지어진경우 48 | pass 49 | else: 50 | build_status.remove([x,y,a]) 51 | elif b == 0: # 제거 52 | build_status.remove([x,y,a]) 53 | if check(build_status): 54 | pass 55 | else: 56 | build_status.append([x,y,a]) 57 | 58 | return sorted(build_status) 59 | 60 | print(solution(n,build_frame)) -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_구현_럭키스트레이트_1회.py: -------------------------------------------------------------------------------- 1 | #~4:10 2 | ''' 3 | 캐릭터 점수 N 4 | 자릿수 기준 점수 N을 반으로 나눔. 5 | 왼쪽과 오른쪽의 합이 같으면 끝. 6 | ''' 7 | 8 | n = list(map(int,input())) 9 | # print(type(n[0])) 10 | 11 | div = len(n)//2 12 | left = n[:div] 13 | right = n[div:] 14 | if sum(left) == sum(right): 15 | print('LUCKY') 16 | else: 17 | print('READY') -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_구현_문자열압축_1회.py: -------------------------------------------------------------------------------- 1 | # ~10:25 2 | # input_str = input() 3 | 4 | 5 | input_str = "z"*100*10 6 | 7 | # x개단위를 비교하여 가장 적은 표현방식으로 만들기 8 | # greedy? 9 | 10 | output_str = '' 11 | temp = 1 12 | 13 | def find_nword(in_str, n): 14 | global output_str, temp 15 | if len(in_str) < n*2: 16 | if temp != 1: 17 | output_str += (str(temp)+in_str) 18 | else: 19 | output_str += in_str 20 | 21 | return 22 | 23 | start = in_str[:n] 24 | find = in_str[n:n*2] 25 | 26 | if start != find: 27 | # print('dif') 28 | if temp == 1: 29 | output_str += in_str[:n] 30 | 31 | else: 32 | output_str += (str(temp)+start) 33 | temp = 1 34 | 35 | # 다시 n번째 뒤부터 탐색 36 | find_nword(in_str[n:], n) 37 | 38 | 39 | else: # 같은 경우 40 | # print('same') 41 | # 등장 횟수를 업데이트 42 | temp += 1 43 | # n개 다음부터 다시 탐색 44 | find_nword(in_str[n:], n) 45 | 46 | 47 | 48 | 49 | for str_len in range(1, len(input_str)//2+1): 50 | find_nword(input_str, str_len) 51 | res = len(output_str) 52 | if str_len == 1: 53 | before = len(output_str) 54 | if res < before: 55 | before = res 56 | print('str_len:', str_len, 'output:', output_str) 57 | output_str = '' 58 | temp = 1 59 | 60 | print(before) -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_구현_문자열압축_2회.py: -------------------------------------------------------------------------------- 1 | # ~ 11:00 2 | def solution(s): 3 | answer = len(s) 4 | # 압축길이 : 최대가 s//2 5 | # 완탐 경우 - 2 ~ 500 6 | for l in range(1, len(s)//2+1): 7 | comp = '' 8 | count = 1 9 | for i in range(0, len(s)//l): 10 | if i == 0: 11 | before = s[:l] 12 | else: 13 | after = s[i*l : (i+1)*l] # l만큼 자름 14 | if before == after: 15 | count += 1 16 | 17 | if i == len(s)//l-1: 18 | comp += (str(count) + before) 19 | 20 | else: # 달라질때 21 | if count > 1: 22 | comp += (str(count) + before) 23 | else: 24 | comp += before 25 | before = after # after로 before를 치환 26 | count = 1 27 | 28 | if i == len(s)//l-1: 29 | comp += after 30 | 31 | comp += s[(i+1)*l:] 32 | if answer > len(comp): 33 | answer = len(comp) 34 | 35 | 36 | return answer 37 | 38 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_구현_문자열재정렬_1회.py: -------------------------------------------------------------------------------- 1 | #~4:15 2 | # 알파벳을 오름차순 정렬해서 출력 + 모든 숫자 더한값을 이어서 출력 3 | first = list(input()) 4 | num = list('0123456789') 5 | 6 | # 알파벳 정렬 7 | first_sort = sorted(first) 8 | num_idx = list() 9 | char = list() 10 | sum = 0 11 | for i in range(len(first_sort)): 12 | if first_sort[i] in num: 13 | sum += int(first_sort[i]) 14 | 15 | else: 16 | char.append(first_sort[i]) 17 | 18 | char.append(str(sum)) 19 | last = ''.join(char) 20 | 21 | print(last) -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_구현_외벽_점검_1회.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def solution(n, weak, dist): 4 | length = len(weak) 5 | # weak 길이 늘리기 6 | for w in range(length): 7 | weak.append(n+weak[w]) 8 | cand = [] 9 | for start in range(length): # 각 weak point를 출발점으로 설정 10 | # 끝점 설정 11 | 12 | for friends in list(permutations(dist, len(dist))): 13 | pos = weak[start] # 첫 출발지점 14 | count = 1 15 | for friend in friends: 16 | fr_dist = pos+friend 17 | if fr_dist < weak[start+length-1]: # 끝점이란? 시작점부터 마지막 weak까지의 거리 18 | count += 1 # 친구 추가 19 | pos = [i for i in weak if i > fr_dist][0] # 다음 취약지점부터 시작 20 | 21 | else: # 끝점 도달 22 | cand.append(count) 23 | # print('friends:', friends) 24 | # print('count:', count) 25 | return min(cand) if cand else -1 26 | 27 | print(solution(12, [1, 5, 6, 10], [1, 2, 3, 4])) 28 | print(solution(12, [1, 3, 4, 9, 10], [3, 5, 7])) -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_구현_치킨배달_1회.py: -------------------------------------------------------------------------------- 1 | # ~9:50 2 | n, m = map(int, input().split()) 3 | 4 | board = [] 5 | for _ in range(n): 6 | board.append(list(map(int, input().split()))) 7 | 8 | # 조합 구현 - 전체에서 m개를 조합으로 뽑는 경우의 수 9 | def comb(input_list, n): 10 | result = [] 11 | if len(input_list) < n: 12 | return result 13 | 14 | elif n == 1: 15 | for i in input_list: 16 | result.append([i]) 17 | 18 | else: 19 | temp = [j for j in input_list] 20 | for k in range(len(input_list)): 21 | temp.remove(input_list[k]) 22 | for p in comb(temp, n-1): 23 | result.append([input_list[k]] + p) 24 | 25 | return result 26 | 27 | # print(board) 28 | 29 | # 칰 위치 찾는 함수 30 | def find_chick_and_house(): 31 | chick = [] 32 | house = [] 33 | for row in range(n): 34 | for col in range(n): 35 | if board[row][col] == 2: 36 | chick.append((row,col)) 37 | elif board[row][col] == 1: 38 | house.append((row,col)) 39 | return house, chick 40 | 41 | 42 | # 칰 거리 구하는 함수 43 | def dist_chick(house, chick): 44 | sum_dist = 0 45 | for x, y in house: 46 | dist_one_list = [] 47 | for xc, yc in chick: 48 | dist_one_list.append(abs(x-xc) + abs(y-yc)) 49 | sum_dist += min(dist_one_list) 50 | 51 | return sum_dist 52 | 53 | # 치킨 및 집 위치 저장 54 | house, chick = find_chick_and_house() 55 | 56 | # m개만큼 치킨집 뽑음 57 | chick_case_list = comb(chick, m) 58 | 59 | # m개 뽑는 경우의 수에서 각각 치킨거리 구함 60 | chick_dist_list = [] 61 | for i in range(len(chick_case_list)): 62 | chick_dist_list.append(dist_chick(house, chick_case_list[i])) 63 | 64 | # print(chick_dist_list) 65 | print(min(chick_dist_list)) 66 | 67 | 68 | 69 | 70 | # print(comb([(2,3),(3,2),(4,1)], 3)) 71 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그래프_도시분할계획_1회.py: -------------------------------------------------------------------------------- 1 | # ~ 4:40 2 | 3 | # 두 마을을 나눈다. 4 | # 신장트리를 두개. how? 5 | # 일단 다 연결한 다음에 - 가장 큰 값을 빼면 무조건 6 | # 제일 최솟값으로 나눠지나? 반례 못찾겠으니 걍해보자. 7 | import sys 8 | input = sys.stdin.readline 9 | 10 | def find_parent(parent, x): 11 | if parent[x] != x: 12 | parent[x] = find_parent(parent, parent[x]) 13 | return parent[x] 14 | 15 | def union_parent(parent, a, b): 16 | a = find_parent(parent, a) 17 | b = find_parent(parent, b) 18 | if a < b: 19 | parent[b] = a 20 | else: 21 | parent[a] = b 22 | 23 | # 노드와 간선 입력받기 24 | n, m = map(int, input().split()) 25 | parent = list(range(n+1)) # 부모 테이블 초기화 26 | 27 | # 모든 간선 담을 리스트와 최종 비용 담을 변수 28 | edges = [] 29 | result = [] 30 | 31 | # 모든 간선 정보 입력받기 32 | for _ in range(m): 33 | a, b, c = map(int, input().split()) 34 | edges.append((c,a,b)) # 비용순으로 정렬 예정 35 | 36 | # 간선을 비용순으로 정렬 37 | edges.sort() 38 | # print(edges) 39 | 40 | # 간선 하나씩 확인 41 | for cost, a, b in edges: 42 | # 부모 노드가 같지 않는, 즉 사이클이 발생하지 않는 경우에만 집합에 포함 43 | if find_parent(parent, a) != find_parent(parent, b): 44 | union_parent(parent, a, b) 45 | result.append(cost) 46 | 47 | # Result에서 최댓값 하나 빼기 48 | # print(result) 49 | result.remove(max(result)) 50 | # print('removed', result) 51 | print(sum(result)) 52 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그래프_어두운길_1회.py: -------------------------------------------------------------------------------- 1 | # ~ 6:20 2 | # n, m = map(int, input().split()) 3 | 4 | 5 | n, m = 7, 11 6 | graph = [ 7 | (0, 1, 7), 8 | (0, 3, 5), 9 | (1, 2, 8), 10 | (1, 3, 9), 11 | (1, 4, 7), 12 | (2, 4, 5), 13 | (3, 4, 15), 14 | (3, 5, 6), 15 | (4, 5, 8), 16 | (4, 6, 9), 17 | (5, 6, 11) 18 | ] 19 | 20 | 21 | def find_parent(parent, x): 22 | if parent[x] != x: 23 | parent[x] = find_parent(parent, parent[x]) 24 | return parent[x] 25 | 26 | def union_parent(parent, a, b): 27 | a = find_parent(parent, a) 28 | b = find_parent(parent, b) 29 | if a < b: 30 | parent[b] = a 31 | else: 32 | parent[a] = b 33 | 34 | # 크루스칼 코드 - 최소의 비용으로 모든 도시 연결 35 | 36 | # 부모 리스트 생성 37 | parent = list(range(n)) # 0~n-1 38 | edges = [] 39 | result = 0 40 | total = 0 41 | for i in range(m): 42 | a, b, cost = graph[i]#map(int, input().split()) 43 | edges.append((cost, a, b)) 44 | total += cost 45 | edges.sort() 46 | 47 | for cost, a, b in edges: 48 | if find_parent(parent, a) != find_parent(parent, b): 49 | union_parent(parent, a, b) 50 | result += cost 51 | 52 | print(total - result) 53 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그래프_여행계획_1회.py: -------------------------------------------------------------------------------- 1 | def find_parent(parent, x): 2 | if parent[x] != x: 3 | parent[x] = find_parent(parent, parent[x]) 4 | return parent[x] 5 | 6 | def union_parent(parent, a, b): 7 | a = find_parent(parent, a) 8 | b = find_parent(parent, b) 9 | if a <= b: 10 | parent[b] = a 11 | else: 12 | parent[a] = b 13 | 14 | ''' 15 | 간선 주어짐 16 | 신장 트리를 만들어서, 17 | 여행 계획이 이어지는지 확인하면됨 18 | 그런데, 사이클이 있는 경우이다. 19 | 20 | 그냥 하나의 신장 트리 내에 계획의 원소가 존재하면 21 | 여행은 가능하다. 22 | ''' 23 | n, m = map(int, input().split()) 24 | 25 | # 같은 트리에 속하는지만 확인하면 되므로, 26 | # union 함수 수행한 뒤 부모 같은지만 확인하자. 27 | parent = list(range(n+1)) # 0~n 28 | 29 | graph = [[] for _ in range(n+1)] 30 | for i in range(n): # 0~ n-1 31 | row = list(map(int, input().split())) 32 | for j in range(n): 33 | if row[j] == 1: 34 | union_parent(parent, i+1, j+1) 35 | 36 | plan = list(map(int, input().split())) 37 | 38 | result = True 39 | for i in range(len((plan))): 40 | if i == 0: 41 | par = parent[plan[i]] 42 | else: 43 | if parent[plan[i]] != par: 44 | result = False 45 | 46 | if result: 47 | print('YES') 48 | else: 49 | print('NO') 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그래프_최종순위_1회답.py: -------------------------------------------------------------------------------- 1 | # ~ 1:40 2 | # t = int(input()) 3 | 4 | def find_parent(parent, x): 5 | if parent[x] != x: 6 | parent[x] = find_parent(parent, parent[x]) 7 | return parent[x] 8 | 9 | def union_parent(parent, a, b): 10 | a = find_parent(parent, a) 11 | b = find_parent(parent, b) 12 | if a < b: 13 | parent[b] = a 14 | else: 15 | parent[a] = b 16 | 17 | 18 | n = int(input()) 19 | rank = list(map(int, input().split())) 20 | 21 | parent = list(range(n+1)) 22 | 23 | m = int(input()) 24 | change = [] 25 | for _ in range(m): 26 | change.append(tuple(map(int, input().split()))) 27 | 28 | for a, b in change: 29 | union_parent(parent, a, b) 30 | 31 | print(parent) 32 | # case: ? 33 | def check(): 34 | new_rank = [r for r in rank] 35 | for a, b in change: 36 | if parent[a] != parent[b]: 37 | print('IMPOSSIBLE') 38 | return 39 | 40 | apos = rank.index(a) 41 | bpos = rank.index(b) 42 | order = 'asc' 43 | if apos < bpos: 44 | start, end = apos, bpos 45 | else: 46 | order = 'desc' 47 | start, end = bpos, apos 48 | 49 | if apos-bpos > 1: # 사이에 다른 팀 존재 50 | for c in rank[start+1:end]: 51 | if parent[c] != parent[a]: 52 | print('?') 53 | return 54 | 55 | print(apos,bpos,order) 56 | # 검사 통과한 경우 순위 변경 57 | napos, nbpos = new_rank.index(a), new_rank.index(b) 58 | if (order == 'asc' and napos < nbpos) or (order == 'desc' and napos > nbpos): 59 | new_rank[napos], new_rank[nbpos] = new_rank[nbpos], new_rank[napos] 60 | 61 | print(new_rank) 62 | return 63 | 64 | check() 65 | 66 | 67 | # case: impossible 68 | 69 | # case: possible 70 | 71 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그래프_커리큘럼_1회.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | n = int(input()) 4 | indegree = [0] * (n+1) 5 | graph = [[] for _ in range(n+1)] 6 | cost = [0] * (n+1) 7 | 8 | 9 | # 소요시간, 10 | for j in range(1, n+1): 11 | inp = list(map(int, input().split())) 12 | for i in range(len(inp)): 13 | if i == 0: # j과목의 소요시간 14 | cost[j] = inp[i] 15 | elif inp[i] != -1: # j과목의 선수과목 16 | prior = inp[i] 17 | graph[prior].append(j) 18 | indegree[j] += 1 19 | # 동시에 여러 강의 수강 가능 20 | # n까지의 최소시간 어떻게 계산? 21 | # 같은 length로 들어간 큐에서, 최소시간만 고려한다. 22 | 23 | # 위상 정렬 함수 24 | def topology_sort(): 25 | time = [c for c in cost] # 시간 후보 넣는 리스트 26 | q = deque() 27 | 28 | # 첫시작 : 선수과목 (indegree) 가 0인 노드 삽입 29 | for i in range(1, n+1): 30 | if indegree[i] == 0: 31 | q.append(i) 32 | 33 | # 큐가 빌때까지 반복 34 | while q: 35 | now = q.popleft() 36 | # result.append(now) 37 | # 현재 노드 소요시간 갱신 38 | # cost[now] += max(time[now]) 39 | # 연결 노드 진입차수에서 1 빼기 40 | for i in graph[now]: 41 | indegree[i] -= 1 42 | # 연결 노드의 시간 리스트에 추가 43 | # time[i].append(cost[now]) 44 | time[i] = max(time[i], cost[i]+time[now]) 45 | # 새롭게 0이 되는 노드를 큐에 삽입 46 | if indegree[i] == 0: 47 | q.append(i) 48 | 49 | for t in time[1:]: 50 | print(t) 51 | 52 | topology_sort() 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그래프_탑승구_1회.py: -------------------------------------------------------------------------------- 1 | # ~5:40 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: 12 | parent[b] = a 13 | else: 14 | parent[a] = b 15 | 16 | n = int(input()) # 도킹 개수 17 | k = int(input()) # 비행기 개수 18 | 19 | # 부모 테이블 20 | parent = list(range(n+1)) # 0~n 21 | planes = 0 22 | for _ in range(k): 23 | end = int(input()) 24 | planes += 1 25 | if parent[end] == end: 26 | union_parent(parent, end, end-1) 27 | elif parent[end] != 0: 28 | union_parent(parent, parent[end], parent[end]-1) 29 | else: 30 | planes -= 1 31 | break 32 | 33 | print(planes) 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그래프_팀결성_1회.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 0~N까지의 번호 학생 부여 3 | 팀 합치기와 같은팀여부 확인 연산 4 | ''' 5 | 6 | n, m = map(int, input().split()) 7 | 8 | def find_parent(parent, x): 9 | if parent[x] != x: 10 | parent[x] = find_parent(parent, parent[x]) 11 | return parent[x] 12 | 13 | def union_parent(parent, a, b): 14 | a = find_parent(parent, a) 15 | b = find_parent(parent, b) 16 | if a < b: 17 | parent[b] = a 18 | else: 19 | parent[a] = b 20 | 21 | student = list(range(0,n+2)) 22 | parent = list(range(0,n+2)) 23 | 24 | for _ in range(m): 25 | a, b, c = map(int, input().split()) 26 | if a == 0: # 팀 합치기 연산 27 | union_parent(parent, b, c) 28 | print('parent:', parent) 29 | else: # 같은 팀 확인 연산 30 | if find_parent(parent, b) == find_parent(parent, c): 31 | print('YES') 32 | else: 33 | print('NO') 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그래프_행성터널_1회.py: -------------------------------------------------------------------------------- 1 | # 신장 트리 2 | def find_parent(parent, x): 3 | if parent[x] != x: 4 | parent[x] = find_parent(parent, parent[x]) 5 | return parent[x] 6 | 7 | def union_parent(parent, a, b): 8 | a = find_parent(parent, a) 9 | b = find_parent(parent, b) 10 | if a < b: 11 | parent[b] = a 12 | else: 13 | parent[a] = b 14 | 15 | n = int(input()) 16 | # n = 5 17 | parent = list(range(n+1)) # 0~n 18 | # coords = [ 19 | # [11, -15, -15, 1], 20 | # [14, -5, -15, 2], 21 | # [-1, -1, -5, 3], 22 | # [10, -4, -1, 4], 23 | # [19, -4, 19, 5], 24 | # ] 25 | coords = [] 26 | for i in range(1, n+1): 27 | li = list(map(int, input().split())) 28 | li.append(i) 29 | coords.append(li) 30 | 31 | xsort = [(c[0], c[3]) for c in sorted(coords, key=lambda x: x[0])] 32 | ysort = [(c[1], c[3]) for c in sorted(coords, key=lambda x: x[1])] 33 | zsort = [(c[2], c[3]) for c in sorted(coords, key=lambda x: x[2])] 34 | 35 | edges = [] 36 | for data in [xsort, ysort, zsort]: 37 | for i in range(len(data)-1): 38 | # 거리, a, b 추가 39 | edges.append((abs(data[i+1][0]-data[i][0]), data[i][1], data[i+1][1])) 40 | 41 | edges.sort() # 거리 작은순으로 정렬 42 | 43 | result = 0 44 | for dist, a, b in edges: 45 | if find_parent(parent, a) != find_parent(parent, b): 46 | union_parent(parent, a, b) 47 | result += dist 48 | 49 | print(result) 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그리디_곱하기혹은더하기_1회.py: -------------------------------------------------------------------------------- 1 | # ~4:30 2 | ''' 3 | 0~9 로 문자열이 주어졌을때, 사이에 x 혹은 + 를 넣어 4 | 가장 큰 수를 구하는 프로그램을 작성하시오. 5 | 연산은 무조건 왼쪽부터''' 6 | 7 | # 0 1은 앞뒤는 곱하기 들어가면 안되고 무조건 더하기, 8 | # 2부터는 무조건 곱하기네? 9 | 10 | s = list(map(int,input())) 11 | 12 | 13 | for i in range(len(s)): 14 | if i == 0: 15 | result = s[i] 16 | else: 17 | if s[i] == 0 or s[i] == 1: 18 | result += s[i] 19 | elif s[i-1] == 0 or s[i-1] == 1: 20 | result += s[i] 21 | else: 22 | result *= s[i] 23 | 24 | print(result) 25 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그리디_만들수없는금액_1회.py: -------------------------------------------------------------------------------- 1 | # ~1:30 2 | n = int(input()) 3 | 4 | coins = list(map(int, input().split(' '))) 5 | # coins = sorted(coins) 6 | 7 | # coins = [1,1,2,3,9] 8 | # 만들수없는 금액중 최솟값 9 | # 1 1 2 3 9 10 | 11 | ''' 12 | target 1 13 | 1 있으니 1까지 만들수있음.. 다음 target-> 2 14 | 다음 1이 있으니 2까지 만들수있음. 다음 target -> 3 15 | 다음은 2가 있어서 4까지 만들수있음. 다음 target -> 5 16 | 다음은 3이 있어서 7까지 만들수있음. 다음 target -> 8 17 | 다음은 9가 있음. target보다 큰경우, 최소 9+1~7이기 때문에 8 못만듬. 18 | 19 | 20 | ''' 21 | target = 1 22 | for x in sorted(coins): 23 | if target < x: 24 | break 25 | target += x 26 | 27 | print(target) 28 | 29 | 30 | '''오답노트 31 | 32 | 아이디어를 떠올리기 쉽지 않다. 그리디적 사고방식 - 단순무식하게 다가간다. 33 | 일단 코인문제는, 정렬을 해서 34 | 하나하나 더해보면서 아이디어를 찾아야한다. 35 | 36 | ''' -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그리디_모험가 길드_1회답.py: -------------------------------------------------------------------------------- 1 | # ~1:15 2 | # 최대 모험가 그룹 3 | n = int(input()) 4 | # ppl_list = [int(i) for i in input().split()] 5 | ppl_list = [5, 2, 1, 1, 1, 1, 1, 1] 6 | 7 | # 제일 구성 많이 하려면, 3인 사람 부터 2를 최대한 껴준다. 8 | # 최대한 많은 사람에게 적은 사람을 붙여주고, 그다음 남은걸로 처리 9 | # 일단 정렬 10 | sort_list = sorted(ppl_list, reverse=True) 11 | print(sort_list) 12 | # 최대랑 그룹을 결정지어서 빼고, count를 한다 13 | # [3,2,2,2,1] 14 | 15 | # 첫번째 확인 16 | count = 0 17 | pick = 0 18 | while True: 19 | pick = sort_list[0] 20 | if len(sort_list) > pick: # 뽑아도 남는경우 21 | # pick 수 - 1 만큼 슬라이싱 22 | sort_list = sort_list[pick:] 23 | count += 1 24 | else: # 딱 맞거나 덜 남는경우 25 | count += 1 26 | break 27 | 28 | 29 | print(count) 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그리디_무지의먹방라이브_1회.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 1~N까지 음식이 있음 3 | N음식 먹으면 다시 1번음식이 온다 4 | 1초동안 먹고 남기고 다음음식 먹음 5 | food_times에 각 음식별 소요시간이 들어있다. 6 | [3,1,2] 7 | ''' 8 | 9 | k = int(input()) 10 | food_times = list(map(int, input().split())) 11 | 12 | 13 | order = 0 14 | 15 | for _ in range(k): 16 | 17 | while food_times[order] == 0: 18 | order += 1 19 | if order > len(food_times): 20 | print(-1) 21 | 22 | food_times[order] -= 1 23 | order += 1 24 | 25 | # 회전 구현 - food_times개수를 order이 넘어가면 다시 0 26 | if order == len(food_times): 27 | order = 0 28 | print(food_times) 29 | 30 | print((order + 1) % len(food_times)) 31 | 32 | ''' 33 | 1.while 극복하기 - 큐, 스택? 34 | queue에 집어넣고, 35 | 2. order를 조건에 맞게 이동하고, 그다음 순서로 간다음 출력하기. 36 | ''' 37 | 38 | 39 | # 다먹은 음식도 순서 있으므로 남겨두어야한다. 0이면 그냥 그다음꺼 먹기 -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그리디_문자열뒤집기_1회.py: -------------------------------------------------------------------------------- 1 | # ~4:40 2 | # 00101010 최소 뒤집기로 0 또는 1을 만들기 3 | 4 | # 101101101이면? 5 | # 그냥 순서 바뀔때까지 뒤집으면 되는데.. 6 | # 문제는 11110111100011111인경우? 1을 뒤집을지 0을 뒤집을지 알수없다. 7 | # 그러면, 연속된 1 세고 연속된 0을 세서, 그중 작은값을 리턴하면된다. 8 | 9 | import time 10 | import sys 11 | s = sys.stdin.readline().strip() 12 | # s = '10110110100011111' 13 | t0 = time.time() 14 | count = {'1':0, '0':0} 15 | for i in range(len(s)): 16 | # 연속된 0과 1 카운트하기 17 | if i == 0: 18 | now = s[i] 19 | count[now] += 1 20 | elif s[i] != s[i-1]: 21 | now = s[i] 22 | count[now] += 1 23 | else: 24 | continue 25 | print(time.time()-t0, 's') 26 | print(count.values()) 27 | print(min(count.values())) 28 | 29 | print(2/10**6) 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_그리디_볼링공고르기_1회.py: -------------------------------------------------------------------------------- 1 | # ~3:20 2 | 3 | # 무게가 다른 볼링공을 고르는 경우의 수 4 | 5 | # combination 직접구현 6 | def comb(inp_list, n): 7 | #1. 정렬하고 리턴값 생성 8 | inp_list = sorted(inp_list) 9 | result = [] 10 | 11 | #2. exit 생성. n보다 길이 작을 경우 result 리턴 12 | if len(inp_list) < n: 13 | return result 14 | 15 | #3. n = 1일경우, inp_list의 값을 차례로 result에 append한다. 16 | elif n == 1: 17 | for i in inp_list: 18 | result.append([i]) 19 | 20 | #4. 재귀 구현 21 | ## 하나씩 빼고 그것을 가지고 재귀 Loop 생성 22 | else: 23 | temp = [j for j in inp_list] 24 | for k in range(len(inp_list)): 25 | 26 | temp.remove(inp_list[k]) 27 | for p in comb(temp, n-1): 28 | result.append([inp_list[k]] + p) 29 | 30 | 31 | return result 32 | 33 | 34 | n, m = map(int, input().split()) 35 | 36 | weight_list = list(map(int, input().split())) 37 | 38 | # weight_list = [1,3,2,3,2] 39 | 40 | # 조합 리스트 하고, 그중에서 무게 같은걸 뺀다. 41 | # 무게 같은 것들을 뽑아내서 그것의 조합을 구해서 처음 리스트에서 뺌 42 | 43 | num_list = list(range(1,n+1)) # 1~n 44 | 45 | comb_num = len(comb(num_list, 2)) 46 | 47 | # 같은 무게끼리의 조합 수를 구한다 48 | same_comb_count = 0 49 | for weight in set(weight_list): 50 | count = weight_list.count(weight) 51 | if count > 1: 52 | same_comb_count += int(count*(count-1)/2) #nC2 53 | 54 | print(comb_num - same_comb_count) 55 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_이진탐색_고정점찾기_1회.py: -------------------------------------------------------------------------------- 1 | ## ~2:00 2 | def binary_search(array, start, end): 3 | if start > end: 4 | return -1 5 | else: 6 | mid = (start + end) // 2 7 | if array[mid] == mid: 8 | return mid 9 | elif array[mid] > mid: 10 | # 더 작은쪽 조사 11 | return binary_search(array, start, mid-1) 12 | else: 13 | return binary_search(array, mid+1, end) 14 | 15 | 16 | n = int(input()) 17 | array = list(map(int, input().split())) 18 | 19 | print(binary_search(array, 0, n-1)) 20 | 21 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_이진탐색_공유기설치_1회.py: -------------------------------------------------------------------------------- 1 | # ~2:30 2 | n, c = map(int, input().split()) 3 | 4 | array = [] 5 | for _ in range(n): 6 | array.append(int(input())) 7 | array.sort() 8 | 9 | # 최소, 최대 간격 설정 10 | min_gap = 1 11 | max_gap = array[-1] - array[0] 12 | 13 | # 최적의 인접간격 14 | result = 0 15 | 16 | while min_gap <= max_gap: 17 | mid = (min_gap + max_gap) // 2 # 중간점을 간격으로 설정 18 | count = 1 19 | now = array[0] 20 | # 공유기 설치 21 | for i in range(1, len(array)): 22 | if array[i] - now >= mid: 23 | now = array[i] 24 | count += 1 25 | if c <= count: # 공유기가 확보된 양보다 더 설치된 경우: 간격 줄여서 26 | result = mid 27 | min_gap = mid+1 # 최소간격을 mid+1로 잡고 다시 실행 28 | else: # 공유기 양만큼 설치가 불가능한 경우 29 | max_gap = mid-1 # 최대간격을 mid-1로 줄이고 다시 실행 30 | 31 | print(result) -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_이진탐색_특정수개수_1회.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left, bisect_right 2 | 3 | ''' 4 | bisect_left(list, a) : 정렬된 list내에서, a를 왼쪽에 삽입할 인덱스를 구함 5 | bisect_right(list, a): 정렬된 list내에서, a를 오른쪽 삽입할 인덱스를 구함 6 | ''' 7 | 8 | def binary_search(array, value, start, end): 9 | if start > end: 10 | return None 11 | else: 12 | mid = (start + end) // 2 13 | if array[mid] == value: 14 | return mid 15 | elif array[mid] > value: 16 | return binary_search(array, value, start, mid-1) 17 | else: 18 | return binary_search(array, value, mid+1, end) 19 | 20 | n, x = map(int, input().split()) 21 | 22 | array = list(map(int, input().split())) 23 | 24 | left_idx = bisect_left(array, x) 25 | right_idx = bisect_right(array, x) 26 | 27 | if left_idx != right_idx: 28 | print(right_idx - left_idx) 29 | else: 30 | print(-1) 31 | 32 | 33 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_정렬_국영수_1회.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | 3 | students = [] 4 | for _ in range(n): 5 | name, kuk, young, su = input().split() 6 | students.append([name, int(kuk), int(young), int(su)]) 7 | 8 | students.sort(key=lambda x: (-x[1], x[2], -x[3], x[0])) 9 | 10 | for s in students: 11 | print(s[0]) -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_정렬_실패율_1회.py: -------------------------------------------------------------------------------- 1 | N = 5 2 | stages = [6,6,6,6,6,6] 3 | stages.sort() 4 | failure = [[i, 0] for i in range(N+1)] 5 | 6 | idx = stages[0] 7 | # 처음 수부터 N보다 큰 경우를 생각해 주어야 한다. 이것이 결정적 반례 8 | if idx <= N: 9 | failure[idx][1] = stages.count(idx) / len(stages[0:]) 10 | 11 | for i in range(1, len(stages)): 12 | if stages[i] > stages[i-1]: 13 | if stages[i] <= N: 14 | idx = stages[i] 15 | failure[idx][1] = stages.count(idx) / len(stages[i:]) 16 | 17 | failure = failure[1:] 18 | failure.sort(key=lambda x: (-x[1],x[0])) 19 | # print(failure) 20 | answer = [] 21 | for f in failure: 22 | answer.append(f[0]) 23 | print(answer) 24 | 25 | 26 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_정렬_안테나_1회.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | 3 | 4 | loc = list(map(int, input().split())) 5 | 6 | loc.sort() 7 | print(loc[ (len(loc)-1) // 2]) 8 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_정렬_카드정렬하기_1회.py: -------------------------------------------------------------------------------- 1 | # ~11:00 2 | import heapq 3 | 4 | n = int(input()) 5 | decks = [] 6 | for _ in range(n): 7 | heapq.heappush(decks, int(input())) 8 | 9 | answer = 0 10 | while len(decks) > 1: 11 | a = heapq.heappop(decks) 12 | b = heapq.heappop(decks) 13 | heapq.heappush(decks, a+b) 14 | answer += (a+b) 15 | 16 | print(answer) 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_최단거리_플로이드_1회.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | m = int(input()) 3 | INF = int(1e9) 4 | graph = [[INF]*(n+1) for _ in range(n+1)] 5 | 6 | # 대각선은 0 7 | for x in range(n+1): 8 | for y in range(n+1): 9 | if x == y: 10 | graph[x][y] = 0 11 | 12 | for _ in range(m): 13 | a, b, c = map(int, input().split()) 14 | if c < graph[a][b]: 15 | graph[a][b] = c 16 | 17 | 18 | # 플로이드 워셜 19 | # fab = min(fab, fak + fkb) 20 | for k in range(1, n+1): 21 | for x in range(1, n+1): 22 | for y in range(1, n+1): 23 | graph[x][y] = min(graph[x][y], graph[x][k] + graph[k][y]) 24 | 25 | # 출력 26 | for x in range(1, n+1): 27 | for y in range(1, n+1): 28 | if graph[x][y] == INF: 29 | print(0, end=' ') 30 | else: 31 | print(graph[x][y], end=' ') 32 | print('') 33 | 34 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_최단경로_미래도시_1회.py: -------------------------------------------------------------------------------- 1 | # ~3:00 2 | ''' 3 | 양방향 4 | 소요시간 1 5 | 소개팅.. K번 회사에 존재 6 | 1 - K - X 최소시간 7 | X에 도달 못하면 -1 출력 8 | ''' 9 | import heapq 10 | 11 | n, m = map(int, input().split()) 12 | INF = int(1e9) 13 | 14 | graph = [[] for _ in range(n+1)] 15 | for _ in range(m): 16 | a, b = map(int, input().split()) 17 | graph[a].append(b) 18 | graph[b].append(a) 19 | 20 | 21 | x, k = map(int, input().split()) 22 | 23 | def dijkstra(start, end): 24 | dist = [INF]* (n+1) 25 | dist[start] = 0 26 | q = [] 27 | heapq.heappush(q, (0,start)) 28 | 29 | while q: 30 | cost, next = heapq.heappop(q) 31 | if cost > dist[next]: 32 | continue 33 | for node in graph[next]: 34 | distance = cost + 1 35 | if distance < dist[node]: 36 | dist[node] = distance 37 | heapq.heappush(q, (distance, node)) 38 | 39 | if dist[end] != INF: 40 | return dist[end] 41 | else: 42 | return False 43 | 44 | ans1 = dijkstra(1,k) 45 | ans2 = dijkstra(k, x) 46 | if ans1 and ans2: 47 | print(ans1 + ans2) 48 | else: 49 | print(-1) 50 | 51 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_최단경로_숨바꼭질_1회.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | n, m = map(int, input().split()) 4 | # 1번으로부터 가장 먼 헛간 찾기 5 | # 다익스트라 6 | 7 | graph = [[] for _ in range(n+1)] 8 | 9 | for _ in range(m): 10 | a, b = map(int, input().split()) 11 | graph[a].append(b) 12 | graph[b].append(a) 13 | 14 | INF = int(1e9) 15 | dist = [INF] * (n+1) 16 | 17 | def dijkstra(start): 18 | q = [] 19 | dist[start] = 0 20 | heapq.heappush(q, (0, start)) 21 | while q: 22 | distance, now = heapq.heappop(q) 23 | if dist[now] < distance: 24 | continue 25 | cost = distance + 1 26 | for next in graph[now]: 27 | if cost < dist[next]: 28 | dist[next] = cost 29 | heapq.heappush(q, (cost, next)) 30 | 31 | # 다익스트라 알고리즘 수행하여 dist 갱신 32 | dijkstra(1) 33 | 34 | # print('dist') 35 | # print(dist) 36 | # 정답 출력 37 | dmax = max(dist[1:]) 38 | nodes = [] 39 | for i in range(1, n+1): 40 | if dist[i] == dmax: 41 | nodes.append(i) 42 | 43 | print(nodes[0], dmax, len(nodes)) 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_최단경로_전보_1회.py: -------------------------------------------------------------------------------- 1 | # ~9:20 2 | ''' 3 | c에서 보낸 메시지 받는 도시 개수, 도시들이 메시지 받는데까지 걸리는 시간 4 | 다익스트라 / 플로이드 워셜? 5 | c에서 각 도시까지 최단시간 구하고, inf 아닌 도시들의 시간을 더한다. 6 | ''' 7 | import heapq 8 | 9 | n, m, c = map(int, input().split()) 10 | INF = int(1e9) 11 | graph = [[] for _ in range(n+1)] 12 | for _ in range(m): 13 | x, y, z = map(int, input().split()) 14 | graph[x].append((y,z)) 15 | 16 | def dijkstra(start): 17 | q = [] 18 | dist = [INF]* (n+1) 19 | dist[start] = 0 20 | heapq.heappush(q, (0, start)) 21 | while q: 22 | cost, next = heapq.heappop(q) 23 | if cost > dist[next]: 24 | continue 25 | for node, distance in graph[next]: 26 | time = cost + distance 27 | if time < dist[node]: 28 | dist[node] = time 29 | heapq.heappush(q, (time, node)) 30 | return dist 31 | dist = dijkstra(c) 32 | count = 0 33 | total_time = 0 34 | for i in range(1,len(dist)): 35 | cons = dist[i] 36 | if 0 < cons < INF: 37 | count += 1 38 | total_time = max(total_time, cons) 39 | 40 | # print(dist) 41 | print(count, total_time) 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_최단경로_정확한순위_1회.py: -------------------------------------------------------------------------------- 1 | # 성적 순위를 정확히 알수 있는 학생의 수 구하기 2 | # ~ 11:00 3 | n, m = map(int,input().split()) 4 | 5 | ''' 6 | 순위를 정확히 안다 - 모든 학생들과 연결된다 7 | 플로이드 워셜 복잡도 O(N**3) 이므로 100**3 연산 충분함 8 | 일반적 플로이드워셜 알고리즘 수행 후, 9 | 연결되는 경우를 세서 다른 노드와 모두 연결되면 순위를 알 수 있다. 10 | ''' 11 | 12 | INF = int(1e9) 13 | graph = [[INF]*(n+1) for _ in range(n+1)] 14 | 15 | for x in range(1, n+1): 16 | for y in range(1, n+1): 17 | if x == y: 18 | graph[x][y] = 0 19 | 20 | for _ in range(m): 21 | a, b = map(int, input().split()) # a < b 22 | graph[a][b] = 1 23 | # graph[b][a] = 1 24 | 25 | 26 | 27 | 28 | # 플로이드 워셜 29 | # 거리는 필요없고 도달 여부만 알면 되므로, 혹시 연결이 된다면 INF에서 1로 바뀌게 된다. 30 | for k in range(1, n+1): 31 | for x in range(1, n+1): 32 | for y in range(1, n+1): 33 | graph[x][y] = min(graph[x][y], graph[x][k] + graph[k][y]) 34 | 35 | for g in graph: 36 | print(g) 37 | 38 | result = 0 39 | # 한 명씩 체크하며 도달 가능한지 보기 40 | for st in range(1, n+1): 41 | count = 0 42 | for a in range(1, n+1): 43 | if graph[a][st] != INF or graph[st][a] != INF: 44 | count += 1 45 | 46 | if count == n: 47 | result += 1 48 | 49 | 50 | print(result) 51 | 52 | -------------------------------------------------------------------------------- /solution_codes/bookcodingtest_최단경로_화성탐사_1회답.py: -------------------------------------------------------------------------------- 1 | n = 3 2 | # cost = [ 3 | # [5,5,4], 4 | # [3,9,1], 5 | # [3,2,7] 6 | # ] 7 | 8 | n = 5 9 | cost = [ 10 | [3, 7, 2, 0, 1], 11 | [2, 8, 0, 9, 1], 12 | [1, 2, 1, 8, 1], 13 | [9, 8, 9, 2, 0], 14 | [3, 6, 5, 1, 5] 15 | ] 16 | 17 | # n = 7 18 | # cost = [ 19 | # [9,0,5,1,1,5,3], 20 | # [4,1,2,1,6,5,3], 21 | # [0,7,6,1,6,8,5], 22 | # [1,1,7,8,3,2,3], 23 | # [9,4,0,7,6,4,1], 24 | # [5,8,3,2,4,8,3], 25 | # [7,4,8,4,8,3,4] 26 | # ] 27 | 28 | # 다익스트라 - heapq를 써서, 이동거리가 짧은 경우부터 29 | # 시간복잡도 ElogV -> 10000 * log125*125 이므로 다익스트라로 해야함 30 | import heapq 31 | 32 | dx = (1,-1,0,0) 33 | dy = (0,0,1,-1) 34 | 35 | INF = int(1e9) 36 | dist = [[INF]*n for _ in range(n)] 37 | 38 | def dijkstra(): 39 | q = [] 40 | dist[0][0] = cost[0][0] 41 | heapq.heappush(q, (dist[0][0], 0, 0)) 42 | while q: 43 | distance, x, y = heapq.heappop(q) 44 | if dist[x][y] < distance: 45 | continue 46 | for i in range(4): 47 | nx = x + dx[i] 48 | ny = y + dy[i] 49 | if (0 <= nx < n and 0 <= ny < n): 50 | dc = distance + cost[nx][ny] 51 | if dc < dist[nx][ny]: 52 | dist[nx][ny] = dc 53 | heapq.heappush(q, (dc, nx, ny)) 54 | 55 | dijkstra() 56 | print(dist[n-1][n-1]) 57 | 58 | -------------------------------------------------------------------------------- /solution_codes/codility_정규식_LongestPassword_1회.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | S = "test 5 a0A pass007 ?xy1 ?##pass007!#" 4 | def solution(S): 5 | for word in sorted(S.split(' '), key=lambda x: len(x), reverse=True): 6 | if len(re.compile('[^a-zA-Z0-9]').findall(word)) > 0: 7 | continue 8 | alplen = len(re.compile('[a-zA-z]').findall(word)) 9 | numlen = len(re.compile('[0-9]').findall(word)) 10 | if alplen%2 == 0 and numlen%2 == 1: 11 | return len(word) 12 | 13 | return -1 14 | 15 | print(solution(S)) -------------------------------------------------------------------------------- /solution_codes/programmers_BFS_게임 맵 최단거리_1회답.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | dx = (-1, 1, 0, 0) 4 | dy = (0, 0, -1, 1) 5 | 6 | def solution(maps): 7 | n = len(maps) 8 | m = len(maps[0]) 9 | q = deque([]) 10 | 11 | dist = [[-1]*m for _ in range(n)] 12 | q.append((0,0)) # x, y, depth 13 | dist[0][0] = 1 14 | while q: 15 | x, y = q.popleft() 16 | for i in range(4): 17 | nx, ny = x + dx[i], y + dy[i] 18 | if 0 <= nx < n and 0 <= ny < m: 19 | if maps[nx][ny] == 1: 20 | if dist[nx][ny] == -1 or dist[x][y] + 1 < dist[nx][ny]: 21 | dist[nx][ny] = dist[x][y] + 1 22 | q.append((nx,ny)) 23 | 24 | 25 | return dist[n-1][m-1] -------------------------------------------------------------------------------- /solution_codes/programmers_BFS_내리막길_1회답.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | # bfs - heap으로 최대부터 뽑기 4 | 5 | m, n = map(int, input().split()) 6 | 7 | board = [list(map(int, input().split())) for _ in range(m)] 8 | 9 | visited = [[0]*n for _ in range(m)] 10 | before = [[False]*n for _ in range(m)] 11 | 12 | dx = (-1, 1, 0, 0) 13 | dy = (0, 0, -1, 1) 14 | visited[0][0] = 1 15 | 16 | q = [(board[0][0], 0, 0)] 17 | 18 | while q: 19 | h, x, y = heapq.heappop(q) 20 | if before[x][y]: 21 | continue 22 | before[x][y] = True 23 | for i in range(4): 24 | nx, ny = x + dx[i], y + dy[i] 25 | if 0 <= nx < m and 0 <= ny < n: 26 | if board[x][y] > board[nx][ny]: 27 | visited[nx][ny] += visited[x][y] 28 | heapq.heappush(q, (-board[nx][ny], nx, ny)) 29 | 30 | 31 | print(visited[m-1][n-1]) 32 | -------------------------------------------------------------------------------- /solution_codes/programmers_BFS_리코쳇 로봇_1회답.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | dx = (-1, 1, 0, 0) 4 | dy = (0, 0, -1, 1) 5 | 6 | def move(x, y, d, r, c, board): 7 | while True: 8 | nx, ny = x + dx[d], y + dy[d] 9 | if nx < 0 or nx >= r or ny < 0 or ny >= c: 10 | return x, y 11 | if board[nx][ny] == 'D': 12 | return x, y 13 | x, y = nx, ny 14 | 15 | def bfs(x, y, visited, r, c, board): 16 | q = deque([]) 17 | visited[x][y] = 0 18 | q.append((x, y)) 19 | while q: 20 | qx, qy = q.popleft() 21 | for i in range(4): 22 | nx, ny = move(qx, qy, i, r, c, board) 23 | if visited[nx][ny] < 0: 24 | visited[nx][ny] = visited[qx][qy] + 1 25 | if board[nx][ny] == 'G': 26 | return visited[nx][ny] 27 | q.append((nx, ny)) 28 | return -1 29 | 30 | def solution(board): 31 | # 최단경로 : bfs (미로 등, 끝까지 탐색할 필요 없음. DFS는 끝까지 왔다가 돌아가기 때문에 비효율적일 수 있다) 32 | r = len(board) 33 | c = len(board[0]) 34 | visited = [[-1]*c for _ in range(r)] 35 | for x in range(r): 36 | for y in range(c): 37 | if board[x][y] == 'R': 38 | return bfs(x, y, visited, r, c, board) -------------------------------------------------------------------------------- /solution_codes/programmers_DFS,BFS_타겟 넘버_1회.py: -------------------------------------------------------------------------------- 1 | def solution(numbers, target): 2 | global count 3 | count = 0 4 | # 플러스 마이너스 번갈아 트리 탐색 5 | def dfs(seq, cal): 6 | global count 7 | if not seq: # 빈 리스트 8 | if cal == target: 9 | count += 1 10 | return 11 | new_cal = cal + seq[0] 12 | dfs(seq[1:], new_cal) 13 | new_cal = cal - seq[0] 14 | dfs(seq[1:], new_cal) 15 | 16 | 17 | dfs(numbers, 0) 18 | 19 | 20 | return count -------------------------------------------------------------------------------- /solution_codes/programmers_DP_N으로 표현_1회답.py: -------------------------------------------------------------------------------- 1 | def solution(N, number): 2 | dp = [set() for _ in range(9)] 3 | for i in range(1, 9): # 1~8 4 | dp[i].add(int(str(N)*i)) 5 | # 더해서 i가 되는 dp 끼리 연산하기 6 | for j in range(1, i): 7 | for op1 in dp[j]: 8 | for op2 in dp[i-j]: 9 | dp[i].add(op1 + op2) 10 | dp[i].add(op1 - op2) 11 | dp[i].add(op1 * op2) 12 | if op2 != 0: 13 | dp[i].add(op1 // op2) 14 | if op1 != 0: 15 | dp[i].add(op2 // op1) 16 | if number in dp[i]: 17 | return i 18 | return -1 -------------------------------------------------------------------------------- /solution_codes/programmers_DP_등굣길_1회.py: -------------------------------------------------------------------------------- 1 | def solution(m, n, puddles): 2 | board = [[0]*m for _ in range(n)] 3 | board[0][0] = 1 # 시작점 1 4 | for px, py in puddles: 5 | board[py-1][px-1] = -1 6 | for x in range(n): 7 | for y in range(m): 8 | # print(x,y) 9 | if board[x][y] == -1: # 물이면: 10 | continue # 다음칸으로 11 | # print('not water') 12 | now = 0 13 | lx, ly = x, y-1 # 왼쪽칸 14 | ux, uy = x-1, y # 윗칸 15 | if 0 <= lx and 0 <= ly: 16 | if board[lx][ly] >= 0: # 물 아니면 17 | now += board[lx][ly] 18 | if 0 <= ux and 0 <= uy: 19 | if board[ux][uy] >= 0: 20 | now += board[ux][uy] 21 | board[x][y] += now 22 | 23 | # print('board;') 24 | # for b in board: 25 | # print(b) 26 | # print('result:', board[n-1][m-1] % 1000000007) 27 | 28 | return board[n-1][m-1] % 1000000007 -------------------------------------------------------------------------------- /solution_codes/programmers_DP_빛의 경로 사이클_1회.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | import sys 3 | 4 | sys.setrecursionlimit(int(1e8)) 5 | 6 | def solution(grid): 7 | ''' 8 | 모든 grid 에서 4방향으로 쏘기 9 | 같은 사이클 판별? -> 처음 방향 처음 위치로 오면 길이 리턴 10 | 같은 방향 하나라도 공유되면 같은 사이클이다 11 | ''' 12 | dx = (-1, 0, 1, 0) # 12부터 시계방향 13 | dy = (0, 1, 0, -1) 14 | r, c = len(grid), len(grid[0]) 15 | path_len_dict = {} 16 | memo = defaultdict(int) 17 | def recur(x, y, di, length, pnum): 18 | # memo exit 19 | if memo[(x, y, di)]: # 0 이상의 값을 가지면 20 | if memo[(x, y, di)] != pnum: # 이미 처리된 경로 21 | return # 길이 반환 22 | else: # 출발지로 돌아옴 23 | path_len_dict[pnum] = length 24 | return 25 | 26 | # exit 아니면 현재 경로를 저장 27 | memo[(x, y, di)] = pnum 28 | 29 | nx, ny = (x + dx[di]) % r, (y + dy[di]) % c 30 | if grid[nx][ny] == 'R': 31 | di = (di + 1) % 4 32 | elif grid[nx][ny] == 'L': 33 | di = (di - 1) % 4 34 | # s면 di 그대로 35 | recur(nx, ny, di, length + 1, pnum) 36 | 37 | path_num = 1 38 | for x in range(r): 39 | for y in range(c): 40 | for i in range(4): 41 | recur(x, y, i, 0, path_num) 42 | path_num += 1 43 | 44 | answer = [] 45 | for key in path_len_dict.keys(): 46 | answer.append(path_len_dict[key]) 47 | 48 | 49 | return sorted(answer) -------------------------------------------------------------------------------- /solution_codes/programmers_DP_코딩테스트 연습_1회답.py: -------------------------------------------------------------------------------- 1 | # 코딩 테스트 공부 2 | # 박우석 3 | def solution(alp, cop, problems): 4 | # DP - bottom-up 5 | max_algo = max([p[0] for p in problems]) 6 | max_code = max([p[1] for p in problems]) 7 | 8 | if alp >= max_algo and cop >= max_code: 9 | return 0 10 | 11 | dp_tab = [[int(1e9)]*(max_code+1) for _ in range(max_algo+1)] 12 | dp_tab[min(alp, max_algo)][min(cop, max_code)] = 0 13 | 14 | for a in range(alp, max(alp, max_algo)+1): 15 | for c in range(cop, max(cop, max_code)+1): 16 | 17 | if a > max_algo: 18 | a = max_algo 19 | if c > max_code: 20 | c = max_code 21 | 22 | if a+1 <= max_algo: 23 | dp_tab[a+1][c] = min(dp_tab[a+1][c], dp_tab[a][c] + 1) 24 | 25 | if c+1 <= max_code: 26 | dp_tab[a][c+1] = min(dp_tab[a][c+1], dp_tab[a][c] + 1) 27 | 28 | for alp_req, cop_req, alp_rwd, cop_rwd, cost in problems: 29 | if a >= alp_req and c >= cop_req: # 풀수있는 문제 30 | 31 | a_with_rwd = min(a + alp_rwd, max_algo) 32 | c_with_rwd = min(c + cop_rwd, max_code) 33 | 34 | dp_tab[a_with_rwd][c_with_rwd] = min(dp_tab[a_with_rwd][c_with_rwd], 35 | dp_tab[a][c] + cost) 36 | 37 | return dp_tab[max_algo][max_code] -------------------------------------------------------------------------------- /solution_codes/programmers_구현, 수학_교점에 별 만들기_1회.py: -------------------------------------------------------------------------------- 1 | def solution(line): 2 | points = [] 3 | # line 원소 중에 교점 생기는 경우 교점 정보 저장 4 | for i in range(len(line)-1): 5 | a, b, e = line[i] 6 | for j in range(i+1, len(line)): 7 | c, d, f = line[j] 8 | if a*d == b*c: 9 | continue 10 | else: 11 | p = ( 12 | (b*f - e*d) / (a*d - b*c), 13 | (e*c - a*f) / (a*d - b*c) 14 | ) 15 | if p[0]%1 == 0 and p[1]%1 == 0: # 정수 좌표일때 16 | points.append(tuple(map(int, p))) 17 | 18 | # 저장된 정보들로 별을 나타내기 19 | # x 최소 최대 / y 최소 최대 찾기 20 | minx = min(points, key=lambda x: x[0])[0] 21 | maxx = max(points, key=lambda x: x[0])[0] 22 | miny = min(points, key=lambda x: x[1])[1] 23 | maxy = max(points, key=lambda x: x[1])[1] 24 | 25 | # x 최소 , y 최소를 0으로 하고 그만큼 모든 점들을 이동 26 | new_points = [] 27 | for nx, ny in points: 28 | new_points.append((nx-minx, ny-miny)) 29 | 30 | # x 최대 - 최소 / y 최대 - 최소 길이의 배열을 정의하여 모든 포인트를 *로 넣기 31 | lenx = maxx - minx + 1 32 | leny = maxy - miny + 1 33 | # print('new_p') 34 | # print(new_points) 35 | answer = [['.']*(lenx) for _ in range(leny)] 36 | for nx, ny in new_points: 37 | answer[leny-1-ny][nx] = '*' 38 | 39 | new_answer = [] 40 | for a in answer: 41 | new_answer.append(''.join(a)) 42 | 43 | return new_answer -------------------------------------------------------------------------------- /solution_codes/programmers_구현_스타 수열_1회답.py: -------------------------------------------------------------------------------- 1 | 2 | from collections import Counter 3 | 4 | def solution(a): 5 | max_len = 0 6 | c = Counter(a) 7 | for key in c.keys(): 8 | value = c[key] 9 | if value > max_len: 10 | # 뒤의 두개 탐색하며 진행 11 | count = 0 12 | idx = 0 13 | while idx < len(a)-1: 14 | # 현재칸, 뒷칸 모두 아닌 경우 및 현재칸, 뒷칸이 같은 경우는 카운트 불가 15 | if (a[idx] != key and a[idx+1] != key) or (a[idx] == a[idx+1]): 16 | idx += 1 17 | else: 18 | count += 1 19 | idx += 2 20 | 21 | max_len = max(max_len, count) 22 | 23 | return max_len*2 -------------------------------------------------------------------------------- /solution_codes/programmers_그래프, dfs_네트워크_1회.py: -------------------------------------------------------------------------------- 1 | # ~12:30 2 | 3 | # 서로소 집합 풀이 4 | def find_parent(parent, x): 5 | if parent[x] != x: 6 | parent[x] = find_parent(parent, parent[x]) 7 | return parent[x] 8 | 9 | def union_parent(parent, a, b): 10 | a = find_parent(parent, a) 11 | b = find_parent(parent, b) 12 | if a < b: 13 | parent[b] = a 14 | else: 15 | parent[a] = b 16 | 17 | def solution(n, computers): 18 | parent = list(range(0,n)) #0 ~ n-1 19 | for x in range(n): 20 | for y in range(x): 21 | # print(x,y) 22 | if computers[x][y] == 1: 23 | union_parent(parent, x, y) 24 | print(parent[:]) 25 | answer = len(set(parent[:])) 26 | return answer 27 | 28 | print(solution(5, [[1,0,0,0,0], 29 | [0,1,0,0,0], 30 | [0,0,1,0,1], 31 | [0,0,0,1,0], 32 | [0,0,1,0,1] 33 | ])) 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /solution_codes/programmers_그래프, dfs_네트워크_2회.py: -------------------------------------------------------------------------------- 1 | # 11:00 2 | # from collections import deque 3 | 4 | def solution(n, computers): 5 | answer = 0 # 네트워크 개수 6 | ''' 7 | 0 ~ n-1 을 visited 8 | 돌면서 각 행에 연결정보 있는지 체크. 큐에 넣는다 (자기자신 빼고) 9 | ''' 10 | visited = [False]*(n) 11 | 12 | for i in range(n): 13 | queue = [] 14 | if not visited[i]: 15 | queue.append(i) 16 | while queue: 17 | q = queue.pop(0) 18 | for y in range(n): 19 | if q != y and computers[q][y] == 1 and not visited[y]: 20 | queue.append(y) 21 | visited[y] = True 22 | answer += 1 23 | 24 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_그래프, 다익스트라_가장 먼 노드_1회답.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | INF = int(1e9) 3 | 4 | def solution(n, edge): 5 | # 최단경로 시 간선이 가장 많은 노드의 개수 6 | # 1번으로부터 최단경로 - 다익스트라 7 | 8 | # graph 생성 9 | graph = [[] for _ in range(n+1)] # 작은 -> 큰 으로 정렬됨. 10 | for st, en in edge: 11 | graph[st].append(en) 12 | graph[en].append(st) 13 | 14 | # visited = [False]*(n+1) 15 | distance = [INF]*(n+1) 16 | 17 | # 1번의 distance = 0 으로 초기화 18 | distance[1] = 0 19 | 20 | q = [] 21 | heapq.heappush(q, (0, 1)) 22 | while q: 23 | # print(q) 24 | dist, now = heapq.heappop(q) 25 | if distance[now] < dist: 26 | continue 27 | else: 28 | for next_node in graph[now]: 29 | cost = dist + 1 30 | if distance[next_node] > cost: 31 | distance[next_node] = cost 32 | heapq.heappush(q, (cost, next_node)) 33 | 34 | answer = 0 35 | max_dist = max(distance[1:]) 36 | for i in range(1, n+1): 37 | if distance[i] == max_dist: 38 | answer += 1 39 | # print(distance[1:]) 40 | # print('end') 41 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_그래프, 다익스트라_가장 먼 노드_2회.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | 3 | def solution(n, edge): 4 | answer = 0 5 | graph = [[] for _ in range(n+1)] # 각 노드별 이어진 다음 노드와 거리 넣기 6 | 7 | for st, en in edge: 8 | graph[st].append(en) 9 | graph[en].append(st) 10 | 11 | distance = [int(1e9)]*(n+1) 12 | q = [] 13 | 14 | def dijkstra(start): 15 | distance[start] = 0 16 | heappush(q, (0, start)) 17 | while q: 18 | dist, now = heappop(q) 19 | if distance[now] < dist: # 큐에서 꺼낸 거리보다 이미 더 작음 20 | continue 21 | for node in graph[now]: 22 | cost = dist + 1 23 | if cost < distance[node]: 24 | # 큐에서 꺼낸 dist + 다음노드까지의 거리 = cost 가 25 | # distance의 다음노드 거리보다 짧으면 갱신하고, 이 거리가 최소이기 때문에 큐에 넣음 26 | distance[node] = cost 27 | heappush(q, (cost, node)) 28 | 29 | dijkstra(1) 30 | 31 | 32 | return distance[1:].count(max(distance[1:])) -------------------------------------------------------------------------------- /solution_codes/programmers_그래프_게임 개발_1회답.py: -------------------------------------------------------------------------------- 1 | # 완성까지 걸리는 최소시간 2 | # 위상 정렬 3 | # 진입차수 이용 4 | from collections import deque 5 | 6 | n = int(input()) 7 | 8 | graph = [[] for _ in range(n+1)] 9 | indegree = [0] * (n+1) # 해당 노드가 방문되기 위해 먼저 거쳐야하는 노드 수 10 | coms = [[]] + [list(map(int, input().split())) for _ in range(n)] 11 | for i in range(1, n+1): 12 | line = coms[i] 13 | for node in line[1:-1]: # 먼저 지어져야하는 건물 간선에 다음노드 추가 14 | graph[node].append(i) 15 | indegree[i] += 1 16 | 17 | # 진입차수 0부터 큐에 넣음 18 | q = deque([]) 19 | time = [0]*(n+1) 20 | for g in range(1, n+1): 21 | if not indegree[g]: 22 | q.append(g) 23 | while q: 24 | now = q.popleft() 25 | time[now] += coms[now][0] 26 | # 다음 노드의 진입차수를 1 뺀다 27 | for next_node in graph[now]: 28 | time[next_node] = max(time[next_node], time[now]) 29 | indegree[next_node] -= 1 30 | # 새롭게 진입차수 0 되는 노드 삽입 31 | if indegree[next_node] == 0: 32 | q.append(next_node) 33 | 34 | print(*time[1:]) -------------------------------------------------------------------------------- /solution_codes/programmers_그래프_등산코스 정하기_1회.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | def solution(n, paths, gates, summits): 4 | graph = [[] for _ in range(n+1)] 5 | for a, b, cost in paths: 6 | graph[a].append((b, cost)) # 다음노드, 거리 7 | graph[b].append((a, cost)) # 양방향 8 | 9 | # 출입구 하나 정하고, 산봉우리 중 하나 방문, 다시 출입구로 돌아옴 10 | # 이 코스에서 최대거리가 최소일 때 산봉우리와 최대거리를 리턴 11 | # 최소 여러개면 산봉우리 번호 낮은거를 리턴 12 | 13 | # 다익스트라 변형 - 최소 거리를 합산하는게 아니라, 그냥 최대 거리만 남겨둔다 14 | # 1 - 5 - 1 일때, 1 - 5 에서 최대 거리만 남겨두고, 다시 5 - 1 에서 최대 거리만 남겨둔다 15 | INF = int(1e9) 16 | def dijkstra(gates): 17 | distance = [INF]*(n+1) 18 | 19 | q = [] 20 | 21 | for g in gates: 22 | heapq.heappush(q, (0, g)) 23 | distance[g] = 0 24 | while q: 25 | dist, now = heapq.heappop(q) 26 | if distance[now] < dist or now in summits: 27 | continue 28 | for next_node, next_dist in graph[now]: 29 | cost = max(next_dist, dist) # 변형 30 | if cost < distance[next_node]: 31 | distance[next_node] = cost 32 | heapq.heappush(q, (cost, next_node)) 33 | return distance 34 | 35 | 36 | sum_list = [] 37 | g_dist = dijkstra(gates) 38 | for s in summits: 39 | heapq.heappush(sum_list, (g_dist[s], s)) 40 | intensity, sum_num = heapq.heappop(sum_list) 41 | 42 | return [sum_num, intensity] -------------------------------------------------------------------------------- /solution_codes/programmers_그래프_순위_1회답.py: -------------------------------------------------------------------------------- 1 | # 집합으로 풀이 - 이긴 경우, 진 경우 2 | def solution(n, results): 3 | wins = [set() for _ in range(n+1)] 4 | loses = [set() for _ in range(n+1)] 5 | for w, l in results: 6 | wins[w].add(l) # 어떤 팀을 이겼는지 7 | loses[l].add(w) # 어떤 팀한테 졌는지 8 | 9 | # 이기면 그동안 상대 팀이 이긴 전적 가져오고 10 | # 지면 그동안 상대 팀이 진 전적 가져오기 11 | # O(n^2) 12 | for i in range(1, n+1): 13 | for j in range(1, n+1): 14 | if j in wins[i] or i in loses[j]: # i가 j 이김 15 | wins[i].update(wins[j]) 16 | loses[j].update(loses[i]) 17 | elif i in wins[j] or j in loses[i]: # j가 i 이김 18 | wins[j].update(wins[i]) 19 | loses[i].update(loses[j]) 20 | answer = 0 21 | for k in range(1, n+1): 22 | if len(wins[k]) + len(loses[k]) == n-1: 23 | answer += 1 24 | 25 | return answer 26 | 27 | # 플로이드 워셜 이용한 풀이 28 | def solution(n, results): 29 | board = [[0]*(n+1) for _ in range(n+1)] 30 | for w, l in results: 31 | board[w][l] = 1 # w가 l 이김 32 | board[l][w] = -1 # l은 w한테 짐 33 | # 플로이드 워셜 알고리즘 - k, a, b 순서 중요. 34 | for k in range(1, n+1): 35 | for x in range(1, n+1): 36 | for y in range(1, n+1): 37 | # 양수이면 관계 파악 가능, 음수 혹은 0이면 불가능 38 | if board[x][k] * board[k][y] > 0: # 지고 지거나 이기고 이기면 확인됨 39 | board[x][y] = board[x][k] 40 | answer = 0 41 | for i in range(1, n+1): 42 | if board[i][1:].count(0) == 1: 43 | answer += 1 44 | 45 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_그래프_합승 택시 요금_1회.py: -------------------------------------------------------------------------------- 1 | def solution(n, s, a, b, fares): 2 | 3 | # 제한사항 : 지점 200개 이하 4 | # 200*200*200 = 6000000 -> 플로이드 가능 5 | 6 | # 플로이드 워셜 - 1~n까지 7 | INF = int(1e9) 8 | dp = [[INF]*(n+1) for _ in range(n+1)] 9 | for i in range(1, n+1): 10 | dp[i][i] = 0 11 | for x, y, cost in fares: 12 | dp[x][y] = cost 13 | dp[y][x] = cost 14 | 15 | for k in range(1, n+1): 16 | for x in range(1, n+1): 17 | for y in range(1, n+1): 18 | dp[x][y] = min(dp[x][y], dp[x][k] + dp[k][y]) 19 | 20 | # 모든 최단거리가 구해짐. 21 | # A-B 가 같이 이동함 -> 따로 이동 22 | # 같이 가는 노드를 모든 경우에서 구해봄 23 | # S -> K (같이) 24 | # K -> A 25 | # K -> B (따로) 26 | min_fare = int(1e9) 27 | for mid in range(1, n+1): 28 | fare = dp[s][mid] + dp[mid][a] + dp[mid][b] 29 | if min_fare > fare: 30 | min_fare = fare 31 | 32 | return min_fare -------------------------------------------------------------------------------- /solution_codes/programmers_그리디, 투포인터_두 큐 합 같게 만들기_1회답.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | def ex1(queue1, queue2): 5 | q1, q2 = deque([q for q in queue1]), deque([q for q in queue2]) 6 | temp = q1.popleft() 7 | q2.append(temp) 8 | return q1, q2 9 | 10 | def ex2(queue1, queue2): 11 | q1, q2 = deque([q for q in queue1]), deque([q for q in queue2]) 12 | temp = q2.popleft() 13 | q1.append(temp) 14 | return q1, q2 15 | 16 | def solution(queue1, queue2): 17 | q = deque([]) 18 | 19 | qsum = (sum(queue1) + sum(queue2)) 20 | if qsum % 2 != 0 : 21 | return -1 22 | else: 23 | qsum = qsum // 2 24 | 25 | queue1 = deque(queue1) 26 | queue2 = deque(queue2) 27 | 28 | 29 | # ex1, ex2를 반복하며 합이 같아질때까지 한다. 30 | # 불가능하거나 중복되는 경우는 어떻게 고려? 31 | # 지나왔던 값이 또 나오면 불가로 판단. 리턴시킴 32 | def dfs(queue1, queue2, count, memo=[]): 33 | # print(queue1, queue2, count, memo) 34 | if sum(queue1) == sum(queue2): 35 | return count 36 | else: 37 | if queue1 in memo or queue2 in memo: 38 | return -1 39 | else: 40 | 41 | if queue1: 42 | memo.append(queue1) 43 | new_queue1, new_queue2 = ex1(queue1, queue2) 44 | dfs(new_queue1, new_queue2, count+1, memo) 45 | memo.pop() 46 | if queue2: 47 | memo.append(queue2) 48 | new2_queue1, new2_queue2 = ex2(queue1, queue2) 49 | dfs(new2_queue1, new2_queue2, count+1, memo) 50 | memo.pop() 51 | 52 | 53 | answer = dfs(queue1, queue2, 0, []) 54 | 55 | 56 | 57 | # q.popleft() 58 | # q.append() 59 | return answer 60 | 61 | 62 | -------------------------------------------------------------------------------- /solution_codes/programmers_그리디, 투포인터_두 큐 합 같게 만들기_2회답.py: -------------------------------------------------------------------------------- 1 | # 우석 - 두 큐 합 같게 만들기 2 | from collections import deque 3 | import copy 4 | 5 | def solution(queue1, queue2): 6 | 7 | queue1, queue2 = deque(queue1), deque(queue2) 8 | 9 | 10 | # 합을 같게 만들 수 있으므로, greedy로 크면 빼고 작으면 넣는 식으로 간다. 11 | # 상태들을 저장하고 혹시 같은 상태가 오면 -1 12 | answer = 0 13 | s1, s2 = sum(queue1), sum(queue2) 14 | init1 = copy.deepcopy(queue1) 15 | init2 = copy.deepcopy(queue2) 16 | 17 | while True: 18 | if answer > int(1e6): 19 | return -1 20 | 21 | if s1 > s2: 22 | qpop = queue1.popleft() 23 | queue2.append(qpop) 24 | s1 -= qpop 25 | s2 += qpop 26 | if queue1 == init1 or queue1 == init2 : 27 | return -1 28 | 29 | answer += 1 30 | 31 | elif s1 < s2: 32 | qpop = queue2.popleft() 33 | queue1.append(qpop) 34 | s1 += qpop 35 | s2 -= qpop 36 | if queue1 == init1 or queue1 == init2: 37 | 38 | return -1 39 | answer += 1 40 | else: 41 | return answer 42 | -------------------------------------------------------------------------------- /solution_codes/programmers_그리디_체육복_1회.py: -------------------------------------------------------------------------------- 1 | # ~4:30 2 | def solution(n, lost, reserve): 3 | # lost에 없는 남은 체육복 학생들이 lost에 빌려준다. 4 | # lost랑 번호 차이가 1만 나야 한다. 5 | new = [] 6 | # lost와 reserve에 같이 있는 경우, 7 | # 1 더하고 lost, reserve에서 같이 뺀다. 8 | overlap = [] 9 | for l in lost: 10 | if l in reserve: 11 | print('중복', l) 12 | reserve.remove(l) 13 | overlap.append(l) 14 | print(reserve) 15 | 16 | lost = list(set(lost) - set(overlap)) 17 | 18 | 19 | 20 | for l in lost: 21 | print('l', 'lost') 22 | print(l) 23 | print(lost) 24 | 25 | 26 | l1 = l - 1 # 입을수있는 사이즈 27 | l2 = l + 1 28 | if l1 in reserve: 29 | new.append(l) 30 | reserve.remove(l1) 31 | print('l1') 32 | print(l, l1) 33 | continue # 다음으로 넘어감 34 | if l2 in reserve: 35 | new.append(l) 36 | reserve.remove(l2) 37 | print('l2') 38 | print(l, l2) 39 | continue 40 | answer = n - (len(lost)-len(new)) 41 | return answer 42 | 43 | print(solution(5, [1,2], [2,3,5])) -------------------------------------------------------------------------------- /solution_codes/programmers_수학_124 나라의 숫자_1회.py: -------------------------------------------------------------------------------- 1 | # ~ 11:30 2 | 3 | def solution(n): 4 | answer = '' 5 | nums = [0,1,2,4] 6 | while n > 3: 7 | div = n // 3 8 | rem = n % 3 9 | if rem == 0: 10 | div -= 1 11 | rem = 3 12 | answer = str(nums[rem]) + answer 13 | n = div 14 | answer = str(nums[n]) + answer 15 | return answer 16 | 17 | print(solution(25)) -------------------------------------------------------------------------------- /solution_codes/programmers_스택, 큐_같은 숫자는 싫어_1회.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(arr): 4 | q = deque(arr) 5 | p1 = q.popleft() 6 | ans = deque([]) 7 | if not q: 8 | return arr 9 | while q: 10 | 11 | p2 = q.popleft() # 하나 더뽑음 12 | 13 | if p1 == p2: 14 | if not q: 15 | ans.append(p1) 16 | continue 17 | else: 18 | ans.append(p1) 19 | p1 = p2 20 | if not q: 21 | ans.append(p2) 22 | 23 | return list(ans) 24 | -------------------------------------------------------------------------------- /solution_codes/programmers_스택, 큐_기능개발_1회.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(pro, spd): 4 | answer = [] 5 | comp = deque([]) 6 | qpro = deque(pro) 7 | qspd = deque(spd) 8 | p = qpro.popleft() 9 | s = qspd.popleft() 10 | total_date = (100 - p) // s # 며칠후에 배포가능 11 | if (100 - p) % s > 0: 12 | total_date += 1 # 안맞아떨어지면 하루 추가 13 | 14 | comp.append(p) 15 | 16 | while qpro: 17 | qp = qpro.popleft() 18 | qs = qspd.popleft() 19 | 20 | due_date = (100 - qp) // qs 21 | if (100 - qp) % qs > 0: 22 | due_date += 1 23 | 24 | if total_date >= due_date: 25 | # 다음 작업 기간이 총진행일보다 같거나 일찍끝남 26 | comp.append(qp) 27 | if not qpro: 28 | answer.append(len(comp)) 29 | break 30 | else: # 다음작업이 더걸림 - 앞선것을 배포 31 | answer.append(len(comp)) # 배포 32 | comp = deque([]) 33 | total_date = due_date 34 | if not qpro: 35 | answer.append(1) 36 | break 37 | else: 38 | qpro.appendleft(qp) 39 | qspd.appendleft(qs) 40 | 41 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_스택, 큐_올바른 괄호_1회.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(s): 4 | answer = True 5 | oc = 0 6 | qs = deque(s) 7 | while qs: 8 | q = qs.popleft() 9 | if q == '(': 10 | oc += 1 11 | else: 12 | oc -= 1 13 | if oc < 0: 14 | return False 15 | 16 | 17 | if oc != 0: 18 | return False 19 | 20 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_스택, 큐_주식 가격_1회.py: -------------------------------------------------------------------------------- 1 | # ~11:15 10분 2 | from collections import deque 3 | 4 | def solution(prices): 5 | time = 0 6 | answer = [] 7 | q = deque(prices) 8 | while q: 9 | notdec = 0 10 | cur = q.popleft() 11 | for fp in q: 12 | if fp >= cur: 13 | notdec += 1 14 | answer.append(notdec) 15 | 16 | 17 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_스택, 큐_짝지어 제거하기_1회.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def solution(s): 4 | q = deque([]) 5 | if len(s) == 1: 6 | return 0 7 | po = 0 8 | while po < len(s): 9 | if po == len(s) - 1: 10 | q.append(s[po]) 11 | po += 1 12 | elif s[po+1] != s[po]: 13 | q.append(s[po]) 14 | po += 1 15 | else: # 다음것이 같은 문자면 16 | po += 2 # 다음 다음으로 이동 17 | if po > len(s)-1: 18 | break 19 | while q: 20 | qnum = q.pop() 21 | if qnum == s[po]: #그다음것이 q있는것이랑 같다면 22 | po += 1 # 그다음으로 이동 23 | else: 24 | q.append(qnum) # 다시 q에 넣음 25 | break # q랑 다음것이 다르면, 빠져나옴 26 | 27 | return 0 if q else 1 # q가 남아 있으면 제거 못했으므로 0, q가 비었다면 다 제거한 것이므로 1 -------------------------------------------------------------------------------- /solution_codes/programmers_스택, 큐_프린터_1회.py: -------------------------------------------------------------------------------- 1 | # ~ 10:30 2 | from collections import deque 3 | 4 | def solution(pri, loc): 5 | answer = 0 6 | q_pri = deque(tuple(zip(range(len(pri)), pri))) 7 | # (위치정보 0~n-1, 중요도) 8 | 9 | count = 0 # 인쇄된 문서 카운트 10 | 11 | while q_pri: 12 | # pri에서 하나빼고, 이게 뺀 큐의 max보다 큰지 판단 13 | position, priority = q_pri.popleft() # 위치정보, 중요도 14 | if not q_pri: # 마지막까지 다뺸경우 15 | return count+1 16 | if priority >= max(q_pri, key = lambda x: x[1])[1]: 17 | # 뺀다 18 | count += 1 19 | if position == loc: 20 | return count 21 | else: 22 | q_pri.append((position, priority)) 23 | 24 | return count -------------------------------------------------------------------------------- /solution_codes/programmers_시뮬레이션_주차 요금 계산_1회.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from math import ceil 3 | 4 | def solution(fees, records): 5 | 6 | btime, bcost, utime, ucost = fees # 기본시간, 기본요금, 단위시간, 단위요금 7 | 8 | ''' 9 | ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", 10 | "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", 11 | "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"] 12 | ''' 13 | # 누적 주차시간 계산 14 | costs = defaultdict(int) # 누적시간 15 | times = {} 16 | for rec in records: 17 | t, num, st = rec.split() 18 | hour, minute = t[:2], t[3:] 19 | if st == 'IN': 20 | # 입차 - 시각 남겨둠 21 | times[num] = [int(hour), int(minute)] 22 | else: 23 | # 출차 - 입차시각과 차 구해서 주차시간 기억 24 | ent_hour, ent_minute = times[num] 25 | # 누적시간을 분으로 갱신 26 | costs[num] += ((int(hour) - ent_hour)*60 + (int(minute) - ent_minute)) 27 | # 출차했으면 입차를 없앰 28 | del times[num] 29 | # 남아있는 입차시간을 23:59에서 빼서 누적시간 더함 30 | for car in times: 31 | ent_hour, ent_minute = times[car] 32 | costs[car] += ((23 - ent_hour)*60 + (59 - ent_minute)) 33 | 34 | prices = [] 35 | for cnum, elapsed in costs.items(): 36 | 37 | prices.append( 38 | ( 39 | cnum, 40 | bcost + ceil(max(elapsed - btime, 0) / utime) * ucost) 41 | ) 42 | 43 | 44 | prices.sort(key = lambda x: x[0]) 45 | 46 | 47 | # 차량 번호가 작은 자동차부터 청구할 주차 요금 48 | return [p[1] for p in prices] -------------------------------------------------------------------------------- /solution_codes/programmers_완전탐색_모의고사_1회.py: -------------------------------------------------------------------------------- 1 | # ~ 11:30 2 | def solution(answers): 3 | p1 = [1, 2, 3, 4, 5] 4 | p2 = [2, 1, 2, 3, 2, 4, 2, 5] 5 | p3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] 6 | 7 | pe1 = p1*(len(answers)//len(p1) + 1) 8 | pe2 = p2*(len(answers)//len(p2) + 1) 9 | pe3 = p3*(len(answers)//len(p3) + 1) 10 | 11 | pe1 = pe1[:len(answers)] 12 | pe2 = pe2[:len(answers)] 13 | pe3 = pe3[:len(answers)] 14 | 15 | cor = [0, 0, 0, 0] 16 | for i in range(len(answers)): 17 | if pe1[i] == answers[i]: 18 | cor[1] += 1 19 | if pe2[i] == answers[i]: 20 | cor[2] += 1 21 | if pe3[i] == answers[i]: 22 | cor[3] += 1 23 | result = [] 24 | max_c = max(cor) 25 | for i in range(1, 4): 26 | if cor[i] == max_c: 27 | result.append(i) 28 | 29 | return result -------------------------------------------------------------------------------- /solution_codes/programmers_완전탐색_소수 찾기_1회.py: -------------------------------------------------------------------------------- 1 | # ~ 11:00 2 | from itertools import permutations 3 | import numpy as np 4 | 5 | def solution(numbers): 6 | # 소수 판별? 2~sqrt(자기자신)까지 해서 나머지 계속 생기면 됨 7 | def is_sosu(number): 8 | for i in range(2, int(np.sqrt(number))+1): 9 | if number%i == 0: 10 | return False 11 | return True 12 | 13 | answer = [] 14 | 15 | perm = [] 16 | for l in range(1, len(numbers)+1): 17 | perm += list(set(permutations(numbers, l))) 18 | 19 | 20 | # print(perm) 21 | for i in perm: 22 | num = int(''.join(i)) 23 | if num in [0, 1]: continue 24 | # print(is_sosu(num)) 25 | if is_sosu(num): 26 | answer.append(num) 27 | 28 | return len(set(answer)) -------------------------------------------------------------------------------- /solution_codes/programmers_완전탐색_최소직사각형_1회.py: -------------------------------------------------------------------------------- 1 | def solution(sizes): 2 | max_h, max_v = 0, 0 3 | # 가로 < 세로로 맞춤 4 | for h, v in sizes: 5 | if h < v: 6 | h, v = v, h 7 | if max_h < h: 8 | max_h = h 9 | if max_v < v: 10 | max_v = v 11 | 12 | return max_h*max_v -------------------------------------------------------------------------------- /solution_codes/programmers_완전탐색_카펫_1회.py: -------------------------------------------------------------------------------- 1 | def solution(brown, yellow): 2 | answer = [] 3 | total = brown + yellow 4 | for hor in range(1, total//2): # 가로 기준 진행 5 | if total % hor != 0 or total // hor > hor: 6 | continue 7 | ver = total // hor 8 | check_brown = 2*(hor + ver - 2) # 갈색 노란색 개수 확인 9 | check_yellow = total - check_brown 10 | if brown == check_brown and yellow == check_yellow: 11 | return [hor, ver] -------------------------------------------------------------------------------- /solution_codes/programmers_완전탐색_피로도_1회.py: -------------------------------------------------------------------------------- 1 | # ~11:00 2 | from itertools import permutations 3 | def solution(k, dungeons): 4 | comb = permutations(dungeons, len(dungeons)) 5 | # 한 조합 당 탐험 가능한지 확인 6 | max_dun = 0 7 | for seq in comb: 8 | # print('seq:', seq) 9 | user_k = k 10 | dun_count = 0 11 | for need, cost in seq: 12 | # print('need, cost:', need, cost) 13 | if user_k >= need: 14 | user_k -= cost 15 | # print('user_k rest:', user_k) 16 | dun_count += 1 17 | else: break 18 | 19 | if max_dun < dun_count: 20 | max_dun = dun_count 21 | 22 | 23 | return max_dun -------------------------------------------------------------------------------- /solution_codes/programmers_이분탐색_입국심사_1회.py: -------------------------------------------------------------------------------- 1 | # ~ 3:30 50분 - 4:40 분에 품. 총 110분 소요. 2 | ans_cand = int(1e9)**2 3 | 4 | def solution(n, times): 5 | def binary_search(array, start, end): 6 | global ans_cand 7 | if start > end: 8 | return False 9 | else: 10 | mid = (start + end) // 2 11 | cand_time = array[mid] 12 | nc = 0 13 | for t in times: 14 | nc += cand_time//t 15 | if nc < n: # 더 적은 사람밖에 안됨 - 큰쪽 탐색 16 | return binary_search(array, mid+1, end) 17 | else: # 맞아떨어짐 - 더 작은쪽 있는지 탐색 18 | if ans_cand > cand_time: 19 | ans_cand = cand_time 20 | return binary_search(array, start, mid-1) 21 | 22 | grid = range(n*min(times)+1) 23 | 24 | binary_search(grid, 0, len(grid)-1) 25 | 26 | 27 | return ans_cand 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /solution_codes/programmers_이분탐색_입국심사_2회.py: -------------------------------------------------------------------------------- 1 | def solution(n, times): 2 | 3 | # 몇분으로 잡을때 심사가 다 되는지? 4 | # 최대시간 : 사람수 * 최대시간 5 | max_time = n*max(times) 6 | start, end = 1, max_time 7 | answer = int(1e15) 8 | while start <= end: 9 | mid = (start + end)//2 10 | # mid 시간 내 심사가 다 가능한지 확인 11 | total = sum([mid//t for t in times]) 12 | if total < n: # 시간내 심사 불가 13 | start = mid+1 14 | elif total >= n: # 시간내 심사 가능 15 | if answer > mid: 16 | answer = mid 17 | end = mid-1 18 | 19 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_카운터_시소 짝꿍_1회답.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | import math 3 | 4 | def solution(weights): 5 | answer = 0 6 | c = Counter(weights) 7 | # 먼저 무게 같은 사람을 빼기 8 | for w in c.keys(): 9 | if c[w] >= 2: 10 | # 2명이상이면 nC2 로 쌍의 수를 더하기 11 | answer += math.comb(c[w],2) 12 | # print('same:', answer) 13 | weights = set(weights) # 같은 무게끼리는 처리했으니 중복을 지움 14 | # 2:3, 2:4, 3:4 15 | for w in weights: # 다른 무게들별로 16 | if w*3/2 in weights: 17 | answer += (c[w] * c[w*3/2]) 18 | if w*2 in weights: 19 | answer += (c[w] * c[w*2]) 20 | if w*4/3 in weights: 21 | answer += (c[w] * c[w*4/3]) 22 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_큐, 구현_행렬 테두리 회전하기_1회.py: -------------------------------------------------------------------------------- 1 | # 풀이 시간 45분 2 | from collections import deque 3 | 4 | def solution(rows, columns, queries): 5 | 6 | board = [] 7 | for i in range(rows): 8 | board.append([i*columns+a for a in range(1, columns+1)]) 9 | 10 | answer = [] 11 | # 마지막 쿼리는 돌릴 필요 없음. 12 | for i in range(len(queries)): 13 | 14 | # 테두리 뽑아서 큐에 저장 15 | x1, y1, x2, y2 = queries[i] 16 | x1 -= 1; y1 -= 1; x2 -= 1; y2 -= 1 17 | q = deque([]) 18 | # 윗변 19 | for j in range(y1, y2): 20 | q.append(board[x1][j]) 21 | # 오른쪽 22 | for j in range(x1, x2): 23 | q.append(board[j][y2]) 24 | # 아랫변 25 | for j in range(y2, y1, -1): 26 | q.append(board[x2][j]) 27 | # 왼쪽 28 | for j in range(x2, x1, -1): 29 | q.append(board[j][y1]) 30 | 31 | answer.append(min(q)) 32 | 33 | if i < len(queries)-1: 34 | ### 큐 하나 밀려서 뽑아서 배열 넣기 35 | for j in range(y1, y2): 36 | num = q.popleft() 37 | board[x1][j+1] = num 38 | # 오른쪽 39 | for j in range(x1, x2): 40 | num = q.popleft() 41 | board[j+1][y2] = num 42 | # 아랫변 43 | for j in range(y2, y1, -1): 44 | num = q.popleft() 45 | board[x2][j-1] = num 46 | # 왼쪽 47 | for j in range(x2, x1, -1): 48 | num = q.popleft() 49 | board[j-1][y1] = num 50 | 51 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_투포인터_좋다_1회답.py: -------------------------------------------------------------------------------- 1 | ## 시도 2 : 투포인터 2 | # 한 숫자가 다른 두 수로 표현되는지를 한 숫자를 제외한 리스트에서 투포인터로 접근. 3 | # -5 -5 -4 -3 1 2 2 3 4 | n = int(input()) 5 | nums = list(map(int, input().split())) 6 | nums.sort() 7 | goods = 0 8 | for i in range(n): 9 | ex_list = nums[:i] + nums[i+1:] 10 | left, right = 0, n-2 11 | while left < right: 12 | sum_ = ex_list[left] + ex_list[right] 13 | if sum_ == nums[i]: 14 | goods += 1 15 | break 16 | elif sum_ > nums[i]: 17 | right -= 1 18 | else: 19 | left += 1 20 | print(goods) 21 | 22 | 23 | ## 시도 1 : Counter 과 set을 이용함 -> 다른 두 수의 합을 고려 못함.. 24 | # n = int(input()) 25 | # nums = list(map(int, input().split())) 26 | # from collections import Counter 27 | # good = 0 28 | 29 | # sums = set() 30 | # for i in range(1, n): 31 | # for j in range(i): 32 | # sums.add(nums[i]+nums[j]) 33 | 34 | # counter = Counter(nums) 35 | # print('sums:', sums) 36 | # print('set_counter:', set(counter.keys())) 37 | # good_set = sums & set(nums) 38 | # print('good_set:', good_set) 39 | # for g in good_set: 40 | # good += counter[g] 41 | # print(good) -------------------------------------------------------------------------------- /solution_codes/programmers_해시_오픈채팅방_1회.py: -------------------------------------------------------------------------------- 1 | #3:30 2 | def solution(record): 3 | result = {} 4 | for r in record: 5 | if len(r.split()) == 2: 6 | com, userid = r.split() 7 | elif len(r.split()) == 3: 8 | com, userid, name = r.split() 9 | # print(r.split()) 10 | if com != 'Leave': 11 | result[userid] = name 12 | 13 | answer = [] 14 | for r in record: 15 | if len(r.split()) == 2: 16 | com, userid = r.split() 17 | elif len(r.split()) == 3: 18 | com, userid, name = r.split() 19 | if com == 'Enter': 20 | answer.append(f'{result[userid]}님이 들어왔습니다.') 21 | elif com == 'Leave': 22 | answer.append(f'{result[userid]}님이 나갔습니다.') 23 | 24 | return answer -------------------------------------------------------------------------------- /solution_codes/programmers_힙_더 맵게_1회.py: -------------------------------------------------------------------------------- 1 | from heapq import heapify, heappop, heappush 2 | 3 | def solution(scoville, K): 4 | 5 | count = 0 6 | # 불가능 경우 처리하기 7 | heapify(scoville) # 최소 - 최대 8 | # for _ in range(int(1e6)): 9 | while True: 10 | dish1 = heappop(scoville) 11 | # K 체크 12 | if dish1 >= K: 13 | return count 14 | # 큐 비어있으면 -1 리턴 15 | if not scoville: return -1 16 | dish2 = heappop(scoville) 17 | mix = dish1 + (dish2*2) 18 | heappush(scoville, mix) 19 | count += 1 -------------------------------------------------------------------------------- /solution_codes/programmers_힙_이중우선순위큐_1회답.py: -------------------------------------------------------------------------------- 1 | # 최댓값, 최솟값을 한번에 O(logn)으로 빼는 방법? 2 | # 1. 그때그때 정렬 3 | def solution(operations): 4 | answer = [] 5 | queue = [] 6 | for op in operations: 7 | com, num = op.split() 8 | num = int(num) 9 | if com == 'I': 10 | queue.append(num) 11 | elif com == 'D' and len(queue) > 0: 12 | if num == 1: 13 | queue.sort() 14 | queue.pop() # 최댓값 삭제 15 | elif num == -1: 16 | queue.sort() 17 | queue.pop(0) # 최솟값 삭제 18 | 19 | return [max(queue), min(queue)] if queue else [0, 0] -------------------------------------------------------------------------------- /solution_codes/samsung_DFSBFS, 구현_주사위굴리기_1회.py: -------------------------------------------------------------------------------- 1 | n,m,x,y,k = map(int, input().split()) 2 | 3 | board = [] 4 | for _ in range(n): 5 | board.append(list(map(int, input().split()))) 6 | 7 | order = list(map(int, input().split())) 8 | 9 | opp = { 10 | 1:6, 11 | 2:5, 12 | 3:4, 13 | 4:3, 14 | 5:2, 15 | 6:1 16 | } 17 | 18 | # 이동 -> 복사 (주사위 dict에 반영) -> 상단 출력 19 | # 처음 놓인 top 과 down 20 | top = 1 21 | front = 5 22 | right = 3 23 | 24 | # 이동 25 | def move(ord): # 주사위 상태를 바꿈. 26 | global top, front, right 27 | if ord == 1: # 동 28 | track = [top,right,opp[top],opp[right]] # 트랙 설정 29 | right = top 30 | top = track[(track.index(top)-1)] 31 | # front 그대로 32 | elif ord == 2: # 서 33 | track = [top,right,opp[top],opp[right]] # 트랙 설정 34 | right = opp[top] 35 | top = track[(track.index(top)+1) % 4] 36 | elif ord == 3: # 북 37 | track = [top, front, opp[top], opp[front]] 38 | front = opp[top] 39 | top = track[(track.index(top)+1) % 4] 40 | # print('dice: ',top,front,right) 41 | else: # 4 남 42 | track = [top, front, opp[top], opp[front]] 43 | front = top 44 | top = track[(track.index(top)-1)] 45 | 46 | # 실제 이동 하면서 번호 바꾸기 47 | written = { 48 | 1:0, 49 | 2:0, 50 | 3:0, 51 | 4:0, 52 | 5:0, 53 | 6:0 54 | } 55 | 56 | dx = [0,0,-1,1] 57 | dy = [1,-1,0,0] 58 | for ord in order: #1,2,3,4 59 | if x+dx[ord-1] < 0 or y+dy[ord-1] < 0 or x+dx[ord-1] >= n or y+dy[ord-1] >= m: 60 | continue 61 | move(ord) 62 | x += dx[ord-1] 63 | y += dy[ord-1] 64 | if board[x][y] == 0: 65 | board[x][y] = written[opp[top]] # 바닥면 숫자를 칸에 복사 66 | else: 67 | written[opp[top]] = board[x][y] # 주사위에 칸숫자 복사 68 | board[x][y] = 0 69 | 70 | print(written[top]) 71 | 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /solution_codes/samsung_DFSBFS, 구현_테트로미노_2회.py: -------------------------------------------------------------------------------- 1 | # 테트로미노 하나를 적절히 놓아 수가 최대가 되도록 하기 2 | # 회전이나 대칭도 가능. -> 길이 4인 dfs 3 | # from collections import deque 4 | import sys 5 | input = sys.stdin.readline 6 | 7 | dx = (-1, 0, 1, 0) #시계방향 8 | dy = (0, 1, 0, -1) 9 | 10 | max_sum = 0 11 | 12 | def dfs(x, y, length, ns): 13 | global max_sum 14 | if length > 4: 15 | if max_sum < ns: 16 | max_sum = ns 17 | return 18 | else: 19 | for i in range(4): 20 | nx, ny = x + dx[i], y + dy[i] 21 | if 0 <= nx < n and 0 <= ny < m: 22 | if not visited[nx][ny]: 23 | visited[nx][ny] = True 24 | ns += board[nx][ny] 25 | # 방문 안했을 경우 방문하고 nums에 추가 26 | dfs(nx, ny, length+1, ns) 27 | visited[nx][ny] = False 28 | ns -= board[nx][ny] 29 | 30 | def middle(x, y): 31 | global max_sum 32 | ds = [[(x-1, y+1), (x-1, y), (x-1, y-1)], 33 | [(x+1, y+1), (x+1, y), (x+1, y-1)], 34 | [(x-1, y-1), (x, y-1), (x+1, y-1)], 35 | [(x-1, y+1), (x, y+1), (x+1, y+1)] 36 | ] 37 | for s in ds: 38 | msum = board[x][y] 39 | isThree = True 40 | for nx, ny in s: 41 | if 0 <= nx < n and 0 <= ny < m: 42 | msum += board[nx][ny] 43 | else: 44 | isThree = False 45 | break 46 | if isThree: 47 | if max_sum < msum: 48 | max_sum = msum 49 | # print('middle') 50 | # print(s) 51 | 52 | n, m = map(int, input().split()) 53 | board = [list(map(int, input().split())) for _ in range(n)] 54 | 55 | 56 | visited = [[False]*m for _ in range(n)] 57 | for r in range(n): 58 | for c in range(m): 59 | dfs(r, c, 1, 0) 60 | middle(r, c) 61 | 62 | print(max_sum) -------------------------------------------------------------------------------- /solution_codes/samsung_DFSBFS, 구현_퇴사_2회.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | 3 | 4 | times, costs = [], [] 5 | for _ in range(n): 6 | t, p = map(int, input().split()) 7 | times.append(t) 8 | costs.append(p) 9 | 10 | 11 | # n일에 받는 최대수익 : f(t) = max(pi + f(t+ti), f(t+1)) 12 | tab = [0]*n 13 | # 끝날 tab 기입 14 | if times[-1] == 1: 15 | tab[-1] = costs[-1] 16 | 17 | for i in range(n-2, -1, -1): #n-2 ~ 0 18 | next = i+times[i] 19 | if next > n: 20 | tab[i] = tab[i+1] 21 | elif next == n: 22 | tab[i] = max(costs[i], tab[i+1]) 23 | else: 24 | tab[i] = max(costs[i] + tab[next], tab[i+1]) 25 | 26 | # print(tab) 27 | # print(tab) 28 | print(tab[0]) 29 | -------------------------------------------------------------------------------- /solution_codes/samsung_dfs, 백트래킹_스타트와 링크_1회답.py: -------------------------------------------------------------------------------- 1 | # ~7:00 2 | n = int(input()) 3 | s = [list(map(int, input().split())) for _ in range(n)] 4 | 5 | # n = 4 6 | # s = [ 7 | # [0, 1, 2, 3], 8 | # [4, 0, 5, 6], 9 | # [7, 1, 0, 2], 10 | # [3, 4, 5, 0], 11 | # ] 12 | 13 | def dfs(depth, idx): 14 | global min_diff 15 | # depth 가 n // 2일때, visited 아닌곳이 자동으로 상대편 16 | # 점수를 계산해서 최소값 갱신 17 | if depth == n // 2: 18 | print('reached. depth == ', n // 2) 19 | print('visited:', visited) 20 | score1, score2 = 0, 0 21 | for v in range(n): 22 | if visited[v]: 23 | # v 이전까지의 visited를 찾아 s[i][j] 를 더함 24 | for j in range(v): 25 | if visited[j]: 26 | score1 += (s[j][v] + s[v][j]) 27 | else: 28 | for k in range(v): 29 | if not visited[k]: 30 | score2 += (s[k][v] + s[v][k]) 31 | diff = abs(score1 - score2) 32 | if diff < min_diff: 33 | min_diff = diff 34 | return 35 | 36 | # dfs로 depth 증가시키면서 여러 경우로 재귀. combination 과 유사함 37 | for i in range(idx, n): 38 | print('not reached, depth = ', depth) 39 | print('visited = ', visited) 40 | visited[i] = True 41 | dfs(depth+1, i+1) 42 | visited[i] = False 43 | 44 | min_diff = int(1e9) 45 | visited = [False]*n 46 | 47 | dfs(0, 0) 48 | 49 | print(min_diff) 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /solution_codes/samsung_구현_경사로_1회.py: -------------------------------------------------------------------------------- 1 | # ~13:00 2 | n, l = map(int, input().split()) 3 | board = [] 4 | for _ in range(n): 5 | board.append(list(map(int, input().split()))) 6 | 7 | # n, l = 6, 2 8 | 9 | # board = [ 10 | # [3, 3, 3, 3, 3, 3], 11 | # [2, 3, 3, 3, 3, 3], 12 | # [2, 2, 2, 3, 2, 3], 13 | # [1, 1, 1, 2, 2, 2], 14 | # [1, 1, 1, 3, 3, 1], 15 | # [1, 1, 2, 3, 3, 2]] 16 | 17 | # board = [ 18 | # [3, 2, 1, 1, 2, 3], 19 | # [3, 2, 2, 1, 2, 3], 20 | # [3, 2, 2, 2, 3, 3], 21 | # [3, 3, 3, 3, 3, 3], 22 | # [3, 3, 3, 3, 2, 2], 23 | # [3, 3, 3, 3, 2, 2], 24 | # ] 25 | 26 | # 회전 보드 27 | rot_board = [] 28 | for i in range(n): 29 | rot_list = [] 30 | for row in board: 31 | rot_list.append(row[i]) 32 | rot_board.append(rot_list) 33 | 34 | 35 | def cango(hor): 36 | visit = [False]*n # 경사로 놓은 위치 리스트 37 | for i in range(n-1): 38 | if abs(hor[i+1] - hor[i]) > 1: 39 | return False 40 | elif hor[i+1] == hor[i] + 1: # 다음칸이 한칸 더높은경우 41 | # 앞쪽에 L만큼 hor[i]와 같은 높이가 있는지 판단 42 | if i+1 >= l: 43 | if hor[i+1-l:i+1] == [hor[i] for _ in range(l)] and\ 44 | visit[i+1-l:i+1] == [False]*l: # 경사로 있는지도 판단 45 | for v in range(i+1-l, i+1): 46 | visit[v] = True 47 | # 존재하면 해당위치 경사로 세우기 48 | else: 49 | return False 50 | else: 51 | return False 52 | 53 | elif hor[i+1] == hor[i] - 1: #한칸 더낮은경우 54 | # 다음 L만큼 hor[i+1]와 같은높이 있는지 판단 55 | if n-1-i >= l: 56 | if hor[i+1:i+1+l] == [hor[i+1] for _ in range(l)]: 57 | for v in range(i+1, i+1+l): 58 | visit[v] = True 59 | else: 60 | return False 61 | else: 62 | return False 63 | # print('passed!') 64 | # print(hor, visit) 65 | return True 66 | 67 | # 끝에서 끝까지 갈수있는지 판단 68 | roads = 0 69 | for hor in board: 70 | if cango(hor): 71 | roads += 1 72 | 73 | for ver in rot_board: 74 | if cango(ver): 75 | roads += 1 76 | 77 | print(roads) 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /solution_codes/samsung_구현_톱니바퀴_1회.py: -------------------------------------------------------------------------------- 1 | # 1시간 2 | # ~11:00 3 | gears = [[]] + [list(map(int, input())) for _ in range(4)] 4 | 5 | n = int(input()) 6 | rot = [list(map(int, input().split())) for _ in range(n)] 7 | 8 | # 회전 리스트 반환 함수 9 | def rotate(num, di): 10 | global gears 11 | gear = gears[num][:] 12 | if di == 1: # 시계 13 | new_gear = [gear[-1]] + gear[:-1] 14 | else: # 반시계 15 | new_gear = gear[1:] +[gear[0]] 16 | gears[num] = new_gear 17 | return 18 | 19 | # 같이 회전할 대상 정하는 함수 20 | def which_to_rotate(num, di): 21 | # 묶인 부분 - 1번 2, 2번 6 2, 3번 6 2, 4번 6 22 | rot_gears = [[num, di]] 23 | leftgear = gears[num][6] 24 | rightgear = gears[num][2] 25 | 26 | # 왼쪽 체크 27 | check = num - 1 28 | rotate = di 29 | while check > 0: 30 | if gears[check][2] != leftgear: 31 | rotate *= -1 32 | rot_gears.append([check, rotate]) 33 | else: 34 | break 35 | leftgear = gears[check][6] 36 | check -= 1 37 | 38 | # 오른쪽 체크 39 | check = num + 1 40 | rotate = di 41 | while check < 5: 42 | if gears[check][6] != rightgear: 43 | rotate *= -1 44 | rot_gears.append([check, rotate]) 45 | else: 46 | break 47 | rightgear = gears[check][2] 48 | check += 1 49 | return rot_gears # 회전할 기어 반환 50 | 51 | 52 | # 먼저 회전 대상 정하고, 맞붙은 곳 확인, 극이 만약 다르면 반대로 회전. 끝. 53 | for num, di in rot: 54 | rotate_cand = which_to_rotate(num, di) 55 | for gn, gd in rotate_cand: 56 | rotate(gn, gd) 57 | 58 | # 점수 계산 59 | answer = 0 60 | points = [None,1,2,4,8] 61 | for i in range(1, 5): #1~4 62 | if gears[i][0] == 1: 63 | answer += points[i] 64 | 65 | print(answer) 66 | -------------------------------------------------------------------------------- /solution_codes/samsung_시뮬레이션_놀이기구 탑승_1회.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 로직 순서: 3 | 1. for x : for y 로 접근 4 | 2. 비어있는 칸 세기 / 인접 좋아하는 친구 세기 5 | 3. (좋아하는 친구, 비어있는 칸, x, y)로 정렬. 많 많 적 적 이 중 첫번째로 이동 6 | ''' 7 | dx = (-1, 1, 0, 0) 8 | dy = (0, 0, -1, 1) 9 | 10 | def place(id): 11 | global board 12 | cand = [] 13 | for x in range(n): 14 | for y in range(n): 15 | empty = 0 16 | friends = 0 17 | for i in range(4): 18 | nx, ny = x + dx[i], y + dy[i] 19 | if 0 <= nx < n and 0 <= ny < n: 20 | if board[nx][ny] == 0: 21 | empty += 1 22 | elif board[nx][ny] in graph[id]: 23 | friends += 1 24 | cand.append((friends, empty, x, y)) 25 | cand.sort(key=lambda x: (-x[0], -x[1], x[2], x[3])) 26 | 27 | # 그자리가 빈칸 아니면 넘어감 28 | for c in range(len(cand)): 29 | f, e, cx, cy = cand[c] 30 | if board[cx][cy]: # 빈칸 아니면 31 | continue 32 | else: 33 | board[cx][cy] = id 34 | break 35 | return 36 | 37 | 38 | n = int(input()) 39 | graph = [None for _ in range(n*n+1)] # 0~n까지의 학생 40 | seq = [] 41 | 42 | for _ in range(n*n): 43 | n0, n1, n2, n3, n4 = list(map(int, input().split())) 44 | graph[n0] = [n1, n2, n3, n4] 45 | seq.append(n0) 46 | 47 | board = [[0]*n for _ in range(n)] # nxn 0은 빈칸 48 | 49 | for id in seq: 50 | place(id) 51 | 52 | score = 0 53 | score_board = [0,1,10,100,1000] 54 | # 인접한 친구에 따라 점수 부여 55 | for x in range(n): 56 | for y in range(n): 57 | friends = 0 58 | st = board[x][y] 59 | if not st: 60 | continue 61 | for i in range(4): 62 | nx, ny = x + dx[i], y + dy[i] 63 | if 0 <= nx < n and 0 <= ny < n: 64 | if board[nx][ny] in graph[st]: 65 | friends += 1 66 | 67 | score += score_board[friends] 68 | 69 | print(score) -------------------------------------------------------------------------------- /solution_codes/samsung_시뮬레이션_돌아가는 팔각의자_1회.py: -------------------------------------------------------------------------------- 1 | ## 주석처리 해지하면 input.txt에서 입력을 읽어올 수 있음 2 | # import sys 3 | # sys.stdin = open('input.txt', 'r') 4 | 5 | board = [list(map(int, input())) for _ in range(4)] 6 | n = int(input()) 7 | 8 | def rotate(num, di): 9 | if di == 1: # 시계 - 마지막이 앞에옴 10 | board[num-1] = [board[num-1][-1]] + board[num-1][:-1] 11 | elif di == -1: 12 | board[num-1] = board[num-1][1:] + [board[num-1][0]] 13 | 14 | def check(num, di): # 다른의자 회전할지 말지 판단 - 의자 기준으로 왼쪽, 오른쪽 끝까지 15 | rot_list = [0]*4 16 | rot_list[num-1] = di 17 | 18 | left, right = board[num-1][6], board[num-1][2] 19 | cur_di = di 20 | # 왼쪽 21 | for i in range(num-2, -1, -1): 22 | next_left, next_right = board[i][6], board[i][2] 23 | if next_right == left: 24 | break # 회전 안하므로 멈춤 25 | else: 26 | cur_di *= -1 # 반대방향 27 | rot_list[i] = cur_di 28 | left = next_left 29 | 30 | cur_di = di 31 | # 오른쪽 32 | for j in range(num, 4): 33 | next_left, next_right = board[j][6], board[j][2] 34 | if next_left == right: 35 | break 36 | else: 37 | cur_di *= -1 38 | rot_list[j] = cur_di 39 | right = next_right 40 | 41 | return rot_list 42 | 43 | for _ in range(n): 44 | table, direc = map(int, input().split()) 45 | rotate_list = check(table, direc) # [-1, 1, -1, 1] 46 | 47 | for k in range(1, 5): 48 | rotate(k, rotate_list[k-1]) 49 | 50 | ans = [] 51 | for i in range(4): 52 | ans.append(board[i][0]) 53 | 54 | print(1*ans[0] + 2*ans[1] + 4*ans[2] + 8*ans[3]) -------------------------------------------------------------------------------- /solution_codes/samsung_시뮬레이션_드래곤 커브_1회.py: -------------------------------------------------------------------------------- 1 | # ~9:30 50분 2 | n = int(input()) 3 | curves = [list(map(int, input().split())) for _ in range(n)] 4 | 5 | # 드래곤 커브와 네 점이 만나는 사각형의 수를 구하자. 6 | # x가 열, y가 행 7 | dx = (0, -1, 0, 1) # 0123 방향에 맞게 8 | dy = (1, 0, -1, 0) 9 | def dragon(y, x, d, g): 10 | dot_list = [] 11 | navi = [] 12 | # 0세대 선 긋기 13 | dot_list.append((y, x)) 14 | dot_list.append((y + dy[d], x + dx[d])) 15 | navi.append(d) # 방향을 추가 16 | for i in range(1, g+1): 17 | # 끝점부터 방향 리스트 만들기 18 | for na in navi[::-1]: # [d] 19 | # 시계 90도 회전 20 | na_90 = (na+1) % 4 21 | navi.append(na_90) 22 | # 처음 점부터 시작하여 만들어진 navi로 새로운 dot_list 생성 23 | dot_list = [(y, x)] 24 | nx, ny = x, y 25 | for na in navi: 26 | nx, ny = nx + dx[na], ny + dy[na] 27 | dot_list.append((ny, nx)) 28 | 29 | return dot_list 30 | 31 | # 드래곤 커브로 지나가는 모든점 set으로 중복없이 저장 32 | dot_set = set() 33 | for x, y, d, g in curves: 34 | dot_set.update(dragon(x,y,d,g)) 35 | 36 | # 4개점 겹치는 사각형 개수 세기 37 | squares = 0 38 | for sx in range(1, 101): 39 | for sy in range(1, 101): 40 | sq_set = {(sx-1, sy-1), (sx, sy-1), (sx-1, sy), (sx, sy)} 41 | if sq_set & dot_set == sq_set: 42 | squares += 1 43 | 44 | print(squares) 45 | -------------------------------------------------------------------------------- /solution_codes/samsung_시뮬레이션_로봇 청소기_1회답.py: -------------------------------------------------------------------------------- 1 | # ~11:40 ~3:30 2 | 3 | n, m = map(int, input().split()) 4 | r, c, d = map(int, input().split()) 5 | board = [list(map(int, input().split())) for _ in range(n)] 6 | 7 | # 0 북 1 동 2 남 3 서 8 | dx = (-1, 0, 1, 0) 9 | dy = (0, 1, 0, -1) 10 | 11 | # n, m = 3, 3 12 | # r, c, d = 1, 1, 0 13 | # board = [ 14 | # [1, 1, 1], 15 | # [1, 0, 1], 16 | # [1, 1, 1], 17 | # ] 18 | 19 | # n, m = 11, 10 20 | # r, c, d = 7, 4, 0 21 | # board = [ 22 | # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 23 | # [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], 24 | # [1, 0, 0, 0, 1, 1, 1, 1, 0, 1], 25 | # [1, 0, 0, 1, 1, 0, 0, 0, 0, 1], 26 | # [1, 0, 1, 1, 0, 0, 0, 0, 0, 1], 27 | # [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], 28 | # [1, 0, 0, 0, 0, 0, 0, 1, 0, 1], 29 | # [1, 0, 0, 0, 0, 0, 1, 1, 0, 1], 30 | # [1, 0, 0, 0, 0, 0, 1, 1, 0, 1], 31 | # [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], 32 | # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 33 | # ] 34 | 35 | 36 | x = r 37 | y = c 38 | 39 | board[x][y] = 2 40 | chore = 1 41 | 42 | count = 0 43 | while True: 44 | d -= 1 45 | if d < 0: 46 | d += 4 47 | nx = x + dx[d] 48 | ny = y + dy[d] 49 | 50 | if 0 <= nx < n and 0 <= ny < m: 51 | if board[nx][ny] == 0: 52 | count = 0 # 초기화 53 | board[nx][ny] = 2 # 청소 (방문) 54 | chore += 1 55 | x, y = nx, ny # 전진 56 | 57 | elif count < 3: # 청소 이미 했거나 벽인 경우 58 | count += 1 59 | 60 | else: # 모든 방향 청소 돼있음 61 | rd = (d + 2) % 4 # 반대방향 62 | rx = x + dx[rd] 63 | ry = y + dy[rd] 64 | if 0 <= rx < n and 0 <= ry < m and board[rx][ry] != 1 : 65 | x, y = rx, ry 66 | count = 0 67 | else: 68 | break # 청소 끝 69 | print(chore) 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /solution_codes/samsung_시뮬레이션_아기 상어_1회.py: -------------------------------------------------------------------------------- 1 | # ~ 18:10 현재 40분 소요 2 | # 20분 내 정리하기 3 | def find_shark(): 4 | for x in range(n): 5 | for y in range(n): 6 | if board[x][y] == 9: 7 | return x, y 8 | 9 | def bfs(x, y): 10 | global size 11 | # 행, 열 순으로 찾는다. 12 | q = deque([]) 13 | visited = [[False]*n for _ in range(n)] 14 | visited[x][y] = True 15 | q.append((x, y, 0)) 16 | catch = [] 17 | 18 | while q: 19 | qx, qy, qd = q.popleft() 20 | for i in range(4): 21 | nx, ny = qx + dx[i], qy + dy[i] 22 | if 0 <= nx < n and 0 <= ny < n: 23 | if not visited[nx][ny]: 24 | # 빈칸 25 | if board[nx][ny] == 0 or board[nx][ny] == size: 26 | visited[nx][ny] = True 27 | q.append((nx, ny, qd+1)) 28 | elif board[nx][ny] < size: 29 | visited[nx][ny] = True 30 | catch.append((qd+1, nx, ny)) 31 | 32 | # 여기 불안함.. 33 | # if catch: 34 | # break 35 | if catch: 36 | return sorted(catch)[0][1], sorted(catch)[0][2], sorted(catch)[0][0] 37 | else: 38 | return False, False, False # 못잡았으니 리턴 39 | 40 | 41 | 42 | 43 | # import sys 44 | from collections import deque 45 | 46 | # sys.stdin = open('solution_codes/input.txt', "r") 47 | # sys.stdin = open('input.txt', "r") 48 | 49 | n = int(input()) 50 | board = [list(map(int, input().split())) for _ in range(n)] 51 | # 0 빈칸 , 1~6 물고기 크기, 9 상어 위치 52 | dx = (-1, 1, 0, 0) 53 | dy = (0, 0, -1, 1) 54 | 55 | 56 | # 상어 찾기 57 | sx, sy = find_shark() 58 | size = 2 59 | time = 0 60 | bucket = 0 61 | # 상어 이동 62 | while True: 63 | # 물고기 찾기 64 | next_x, next_y, dist = bfs(sx, sy) 65 | # 더이상 먹을 수 있는거 없으면 끝 66 | if next_x is False: 67 | break 68 | time += dist 69 | # 거리가 가까운 물고기 먹음 70 | board[sx][sy] = 0 71 | sx, sy = next_x, next_y # 이동 72 | board[sx][sy] = 9 # 이동한 자리는 상어 73 | bucket += 1 74 | 75 | if bucket == size: 76 | bucket = 0 77 | size += 1 78 | 79 | print(time) 80 | -------------------------------------------------------------------------------- /solution_codes/samsung_시뮬레이션_자율주행 자동차_1회.py: -------------------------------------------------------------------------------- 1 | # import sys 2 | # import time 3 | 4 | # sys.stdin = open('./input.txt', 'r') 5 | # 시계방향 상 우 하 좌 6 | dx = (-1, 0, 1, 0) 7 | dy = (0, 1, 0, -1) 8 | 9 | def move(x, y, d): 10 | global total 11 | moved = False 12 | for _ in range(4): 13 | d = (d-1)%4 # 좌회전 14 | nx, ny = x + dx[d], y + dy[d] 15 | if 0 <= nx < n and 0 <= ny < m: 16 | if board[nx][ny] == 0 and not visited[nx][ny]: 17 | visited[nx][ny] = True 18 | x, y = nx, ny # 이동 19 | moved = True 20 | total += 1 21 | # print('move!', x, y, d) 22 | return x, y, d 23 | if not moved: # 안움직였으면 후진 24 | d = (d-2)%4 # 반대 25 | nx, ny = x + dx[d], y + dy[d] 26 | if board[nx][ny] == 0: 27 | x, y = nx, ny # 도로이므로 후진 28 | d = (d-2)%4 # 방향 원래대로 29 | return x, y, d 30 | else: 31 | # 후진도 못하므로 멈춤 32 | return None, None, None 33 | 34 | 35 | n, m = map(int, input().split()) 36 | x, y, d = map(int, input().split()) 37 | 38 | board = [list(map(int, input().split())) for _ in range(n)] 39 | 40 | # 도로 0 인도 1 41 | visited = [[False]*m for _ in range(n)] 42 | visited[x][y] = True 43 | total = 1 44 | 45 | #반복 46 | canGo = True 47 | while canGo: 48 | # print('canGo:', x, y, d) 49 | x, y, d = move(x, y, d) 50 | if x == None: 51 | canGo = False 52 | 53 | print(total) -------------------------------------------------------------------------------- /solution_codes/samsung_시뮬레이션_컨베이어 벨트 위의 로봇_1회.py: -------------------------------------------------------------------------------- 1 | # 1시 간30분 2 | # 14:45 ~ 15:00 15분 3 | # 17:20 ~ 18:00 40분 4 | 5 | def rotate(): 6 | global A, robots, q 7 | # A 회전 8 | A = [A[-1]] + A[:-1] 9 | # 로봇 회전 10 | robots = [robots[-1]] + robots[:-1] 11 | # 로봇 내림 12 | if robots[n-1] > 0: 13 | # print('robot out') 14 | robots[n-1] = 0 15 | q.popleft() 16 | 17 | def put_robot(rn): 18 | if A[0] > 0 and robots[0] == 0: 19 | robots[0] = rn 20 | A[0] -= 1 21 | q.append(rn) 22 | return True 23 | return False 24 | 25 | def move_robot(): 26 | global A 27 | # robot 올린 순서대로 번호 부여 28 | qr = deque(list(q)) 29 | while qr: 30 | rn = qr.popleft() 31 | # rn 위치 찾고 조건에 맞게 이동 32 | ri = robots.index(rn) 33 | rnext = (ri+1) % (2*n) 34 | if A[rnext] > 0 and robots[rnext] == 0: # 한칸 전진 35 | robots[ri], robots[rnext] = robots[rnext], robots[ri] 36 | A[rnext] -= 1 37 | if robots[n-1] > 0: 38 | # print('robot out') 39 | robots[n-1] = 0 40 | q.popleft() 41 | 42 | 43 | # import sys 44 | # sys.stdin = open('input.txt', "r") 45 | from collections import deque 46 | # 컨베이어 벨트 47 | n, k = map(int, input().split()) 48 | A = list(map(int, input().split())) 49 | # A1, A2 ~ An 50 | robots = [0]*(2*n) 51 | step = 0 52 | q = deque([]) 53 | rn = 1 54 | while True: 55 | step += 1 56 | # print('step:', step) 57 | # print('q:', q) 58 | 59 | # 1이 올리는 위치, N 이 내리는 위치 60 | 61 | rotate() 62 | # print('rotate:') 63 | # print('conv:', A) 64 | # print('robots:', robots) 65 | 66 | move_robot() 67 | # print('move_robot:') 68 | # print('conv:', A) 69 | # print('robots:', robots) 70 | 71 | if put_robot(rn): 72 | rn += 1 73 | # print('put_robot:') 74 | # print('conv:', A) 75 | # print('robots:', robots) 76 | 77 | count = 0 78 | for c in A: 79 | if c == 0: 80 | count += 1 81 | if count >= k: 82 | print(step) 83 | break 84 | -------------------------------------------------------------------------------- /solution_codes/sql_GROUP BY_동명 동물 수 찾기_1회.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME, count(ANIMAL_ID) as COUNT FROM ANIMAL_INS as ani 2 | WHERE NAME IS NOT NULL 3 | GROUP BY NAME 4 | HAVING COUNT >= 2 5 | ORDER BY NAME -------------------------------------------------------------------------------- /solution_codes/sql_GROUP BY_저자 별 카테고리 별 매출액 집계하기_1회.sql: -------------------------------------------------------------------------------- 1 | SELECT a.author_id, a.author_name, b.category, 2 | sum(s.sales*b.price) as total_sales FROM book_sales as s 3 | JOIN book as b on b.book_id = s.book_id 4 | join author as a on a.author_id = b.author_id 5 | 6 | WHERE s.sales_date >= '2022-01-01' and s.sales_date <= '2022-01-31' 7 | 8 | GROUP BY a.author_name, b.category 9 | 10 | ORDER BY a.author_id ASC, b.category DESC -------------------------------------------------------------------------------- /solution_codes/sql_GROUP BY_즐겨찾기가 가장 많은 식당 정보 출력하기_1회.sql: -------------------------------------------------------------------------------- 1 | SELECT food_type, rest_id, rest_name, favorites as favorites FROM rest_info 2 | 3 | WHERE (food_type, favorites) in ( 4 | SELECT food_type, max(favorites) FROM rest_info 5 | GROUP BY food_type 6 | 7 | ) 8 | 9 | ORDER BY food_type DESC -------------------------------------------------------------------------------- /solution_codes/sql_JOIN_없어진 기록 찾기_1회.sql: -------------------------------------------------------------------------------- 1 | -- out에 있는데 In에 없는것 - > left join 에서 inner join 뺌 2 | SELECT o.ANIMAL_ID, o.NAME FROM ANIMAL_OUTS as o 3 | WHERE o.ANIMAL_ID NOT IN ( 4 | SELECT o.ANIMAL_ID FROM ANIMAL_OUTS as o 5 | INNER JOIN ANIMAL_INS ON ANIMAL_INS.ANIMAL_ID = o.ANIMAL_ID 6 | ) 7 | ORDER BY ANIMAL_ID -------------------------------------------------------------------------------- /solution_codes/sql_JOIN_특정 기간동안 대여 가능한 자동차들의 대여비용 구하기_1회.sql: -------------------------------------------------------------------------------- 1 | -- # 1:40 ~ 2:34 총 54분 걸림.. 2 | SELECT distinct(h.car_id), c.car_type, 3 | # 30일간의 대여 금액이 50만원 이상 200만원 미만 4 | round(c.daily_fee/100*(100-p.discount_rate) * 30) as FEE 5 | FROM car_rental_company_rental_history as h 6 | JOIN car_rental_company_car as c ON h.car_id = c.car_id 7 | JOIN car_rental_company_discount_plan as p on p.car_type = c.car_type 8 | 9 | WHERE p.duration_type in ('30일 이상') and 10 | c.car_type in ('세단', 'SUV') and 11 | h.car_id not in 12 | ( 13 | SELECT car_id 14 | FROM car_rental_company_rental_history 15 | WHERE (start_date <= '2022-11-01' and end_date <= '2022-11-30' and end_date >= '2022-11-01') # 1 - end date가 사이에 있음 16 | OR (start_date <= '2022-11-30' and start_date >= '2022-11-01' and end_date >= '2022-11-30')# 2 - start date가 사이에 있음 17 | -- # 3 - start, end 모두 안에 있음 18 | OR (start_date <= '2022-11-30' and start_date >= '2022-11-01' and end_date <= '2022-11-30' and end_date >= '2022-11-01') 19 | -- # 4 - start, end 모두 바깥에 있음 20 | OR (start_date <= '2022-11-01' and end_date >= '2022-11-30') 21 | ) 22 | 23 | HAVING FEE >= 500000 and FEE <= 2000000 24 | ORDER BY FEE DESC, c.car_type ASC, h.car_id DESC -------------------------------------------------------------------------------- /solution_codes/sql_SELECT, UNION_오프라인 온라인 판매 데이터 통합하기_1회답.sql: -------------------------------------------------------------------------------- 1 | SELECT substr(sales_date, 1, 10) as sales_date, f.PRODUCT_ID, NULL as USER_ID, f.SALES_AMOUNT FROM offline_sale as f 2 | -- # WHERE f.sales_date LIKE "2022-03%" 3 | WHERE f.sales_date >= '2022-03-01' AND f.sales_date < '2022-04-01' 4 | UNION 5 | SELECT substr(sales_date, 1, 10) as sales_date, o.PRODUCT_ID, o.USER_ID, o.SALES_AMOUNT FROM online_sale as o 6 | -- # WHERE f.sales_date >= '2022-03-01' AND f.sales_date < '2022-04-01' 7 | -- # WHERE o.sales_date LIKE "2022-03%" 8 | WHERE o.sales_date >= '2022-03-01' AND o.sales_date < '2022-04-01' 9 | 10 | 11 | 12 | -- # OUTER JOIN offline_sale AS f 13 | 14 | 15 | ORDER BY sales_date, product_id, user_id; -------------------------------------------------------------------------------- /solution_codes/sql_STRING_조건에 맞는 사용자 정보 조회하기_1회답.sql: -------------------------------------------------------------------------------- 1 | # 9:35 2 | # ID, 닉네임, 전체주소: 시, 도로명 주소, 상세 주소, 전화번호: 삽입 3 | SELECT distinct(u.USER_ID), u.NICKNAME, 4 | concat(u.CITY, ' ', u.STREET_ADDRESS1, ' ', u.STREET_ADDRESS2) as 전체주소, 5 | concat(substr(u.TLNO, 1, 3), '-', substr(u.TLNO, 4, 4), '-', substr(u.TLNO, 8)) as 전화번호 6 | FROM USED_GOODS_BOARD as g 7 | JOIN USED_GOODS_USER as u ON g.WRITER_ID = u.USER_ID 8 | WHERE g.WRITER_ID in ( 9 | SELECT g.WRITER_ID FROM USED_GOODS_BOARD as g 10 | GROUP BY g.WRITER_ID 11 | HAVING count(g.TITLE) >= 3 12 | ) 13 | ORDER BY u.USER_ID DESC -------------------------------------------------------------------------------- /solution_codes/sql_STRING_조회수가 가장 많은 중고거래 게시판의 첨부파일 조회하기_1회답.sql: -------------------------------------------------------------------------------- 1 | # 9:13 시작 2 | SELECT concat("/home/grep/src/",f.BOARD_ID,'/',f.FILE_ID,f.FILE_NAME,f.FILE_EXT) AS FILE_PATH 3 | FROM used_goods_file as f 4 | LEFT JOIN used_goods_board as b ON b.BOARD_ID = f.BOARD_ID 5 | WHERE b.VIEWS = ( 6 | SELECT max(VIEWS) FROM used_goods_board 7 | ) 8 | ORDER BY f.FILE_ID DESC 9 | # concat("/home/grep/src/",f.BOARD_ID,f.FILE_ID) -------------------------------------------------------------------------------- /temp/baekjoon_녹색 옷 입은 애가 젤다지.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | # 최소 금액 잃으며 끝까지 이동 3 | 4 | board = [list(map(int, input().split())) for _ in range(n)] 5 | 6 | dx = (-1, 0, 1, 0) 7 | dy = (0, -1, 0, 1) 8 | 9 | min_lup = int(1e9) 10 | 11 | def dfs(x, y, visited, lup): 12 | 13 | global min_lup 14 | 15 | new_visited = [v[:] for v in visited] 16 | new_visited[x][y] = True 17 | # n-1, n-1 에서 최소금액 갱신 후 종료 18 | if (x, y) == (n-1, n-1): 19 | if min_lup > lup: 20 | min_lup = lup 21 | return 22 | 23 | # x, y 네방향으로 이동 24 | for i in range(4): 25 | nx = x + dx[i] 26 | ny = y + dy[i] 27 | if 0 <= nx < n and 0 <= ny < n: 28 | if not new_visited[nx][ny]: 29 | new_lup = lup + board[nx][ny] 30 | dfs(nx, ny, new_visited, new_lup) 31 | 32 | return 33 | 34 | visited = [[False]*n for _ in range(n)] 35 | # visited[0][0] = True 36 | dfs(0, 0, visited, board[0][0]) 37 | print(min_lup) 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /temp/baekjoon_숨바꼭질 3.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.setrecursionlimit = 5000 3 | n, k = map(int, input().split()) 4 | 5 | # top-down 6 | def find(x, t, memo: dict): 7 | # memoization - 확인해서 값 있으면 갱신하고 리턴 8 | if x == k: 9 | return t 10 | # k가 아닐 경우 메모하고 나옴 11 | if x-1 >= 0: 12 | if x-1 in memo: 13 | memo[x] = min(memo[x], memo[x-1]+1) 14 | return 15 | else: 16 | find(x-1, t+1, memo) 17 | if x+1 <= 100000: 18 | if x+1 in memo: 19 | memo[x] = min(memo[x], memo[x+1]+1) 20 | return 21 | else: 22 | find(x+1, t+1, memo) 23 | if 2*x <= 100000: 24 | if 2*x in memo: 25 | memo[x] = min(memo[x], memo[2*x]) 26 | else: 27 | find(2*x, t, memo) 28 | 29 | print(find(n, 0, dict())) 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /temp/baekjoon_좋다.py: -------------------------------------------------------------------------------- 1 | # 어떤 수가 다른 두 수 두개의 합 2 | # N개의 수 주어지면 좋은수의 개수 몇개인지 3 | 4 | # 투포인터 5 | # two-pointer 6 | 7 | n = int(input()) 8 | nums = list(map(int, input().split())) 9 | 10 | nums.sort() 11 | good = 0 12 | 13 | for i in range(n): 14 | selected = nums[i] 15 | # 투포인터 16 | p1 = 0 # 작은곳부터 출발포인터 17 | p2 = n-1 # 큰곳에서 출발포인터 18 | while p1 < p2: 19 | if p1 == i: 20 | p1 += 1 21 | if p2 == i: 22 | p2 -= 1 23 | if p1 >= p2: 24 | break 25 | psum = nums[p1] + nums[p2] 26 | if psum == selected: 27 | good += 1 28 | break 29 | elif psum < selected: 30 | p1 += 1 31 | else: 32 | p2 -= 1 33 | 34 | 35 | print(good) --------------------------------------------------------------------------------