Repository: DKU-STUDY/Algorithm Branch: master Commit: 6f78efdbefd8 Files: 2389 Total size: 1.6 MB Directory structure: gitextract_7kj8g6mk/ ├── .gitignore ├── .vscode/ │ ├── c_cpp_properties.json │ ├── launch.json │ └── tasks.json ├── BOJ/ │ ├── .swp │ ├── 1002.터렛/ │ │ ├── 6047198844.cpp │ │ └── 6047198844.py │ ├── 10026.적록색약/ │ │ ├── 6047198844.py │ │ ├── rockmiin.py │ │ ├── sangmandu.py │ │ └── 적록색약_10026.py │ ├── 10039.평균 점수/ │ │ └── 6047198844.py │ ├── 1005.ACM Craft/ │ │ └── 6047198844.py │ ├── 1009.분산처리/ │ │ └── 6047198844.cpp │ ├── 1010.다리 놓기/ │ │ └── 6047198844.cpp │ ├── 10101.삼각형 외우기/ │ │ └── 6047198844.py │ ├── 10103.주사위 게임/ │ │ └── 6047198844.py │ ├── 1011.Fly me to the Alpha Centauri/ │ │ └── 6047198844.cpp │ ├── 1012.유기농 배추/ │ │ └── 6047198844.cpp │ ├── 10156.과자/ │ │ └── 6047198844.py │ ├── 10159.저울/ │ │ └── 6047198844.cpp │ ├── 1016.제곱 ㄴㄴ 수/ │ │ └── 6047198844.py │ ├── 10162.전자레인지/ │ │ └── 6047198844.py │ ├── 10170.NFC West vs North/ │ │ └── 6047198844.py │ ├── 1018.체스판 다시 칠하기/ │ │ └── 6047198844.cpp │ ├── 1019.책 페이지/ │ │ └── 6047198844.py │ ├── 1021.회전하는 큐/ │ │ └── 6047198844.cpp │ ├── 1025.제곱수 찾기/ │ │ └── 6047198844.py │ ├── 1027.고층 건물/ │ │ └── sangmandu.py │ ├── 10282.해킹/ │ │ └── 6047198844.py │ ├── 1030.프렉탈 평면/ │ │ └── sAp00n.py │ ├── 1032.명령 프롬프트/ │ │ └── 6047198844.cpp │ ├── 1037.약수/ │ │ └── 6047198844.cpp │ ├── 1038.감소하는 수/ │ │ └── 6047198844.py │ ├── 1043.거짓말/ │ │ └── 6047198844.py │ ├── 10448.유레카 이론/ │ │ └── 6047198844.py │ ├── 10451.순열 사이클/ │ │ └── rockmiin.py │ ├── 1051.숫자 정사각형/ │ │ ├── 6047198844.py │ │ └── sangmandu.py │ ├── 10546.배부른 마라토너/ │ │ └── 6047198844.py │ ├── 1058.친구/ │ │ └── sangmandu.py │ ├── 10610.30/ │ │ └── 6047198844.cpp │ ├── 1062.가르침/ │ │ └── 6047198844.py │ ├── 1068.트리/ │ │ ├── 6047198844.py │ │ ├── sAp00n.py │ │ └── sAp00n_BFS.py │ ├── 1069.DNA/ │ │ └── 6047198844.py │ ├── 10711.모래성/ │ │ └── 6047198844.py │ ├── 1072.게임/ │ │ └── 6047198844.py │ ├── 1074.Z/ │ │ └── 6047198844.py │ ├── 1075,나누기/ │ │ └── 6047198844.py │ ├── 10757.큰 수 A+B/ │ │ └── 6047198844.cpp │ ├── 10766.특별한 날/ │ │ └── 6047198844.py │ ├── 10773.제로/ │ │ └── s2uyeoii.c │ ├── 10775.공항/ │ │ └── 6047198844.py │ ├── 10797.10부제/ │ │ └── 6047198844.py │ ├── 10798.세로읽기/ │ │ └── 6047198844.py │ ├── 1080.행렬/ │ │ └── 6047198844.py │ ├── 10815.숫자 카드/ │ │ ├── 6047198844.py │ │ └── rockmiin.py │ ├── 10816.숫자 카드 2/ │ │ ├── 6047198844.cpp │ │ └── 6047198844.py │ ├── 10819.차이를 최대로/ │ │ └── 6047198844.cpp │ ├── 10826.피보나치 수 4/ │ │ └── sangmandu.py │ ├── 10830.행렬 제곱/ │ │ └── 10830_행렬 제곱.cpp │ ├── 10833.사과/ │ │ └── 6047198844.py │ ├── 10844.쉬운 계단 수/ │ │ └── rockmiin.py │ ├── 1085.직사각형에서 탈출/ │ │ └── 6047198844.cpp │ ├── 10867.중복 뺴고 정렬하기/ │ │ ├── 6047198844.py │ │ └── rockmiin.py │ ├── 10870.피보나치 수 5/ │ │ └── sangmandu.py │ ├── 1092.배/ │ │ └── 6047198844.py │ ├── 10926.??!/ │ │ └── 6047198844.py │ ├── 1094.막대기/ │ │ └── 6047198844.py │ ├── 10942.팰린드롬?/ │ │ └── 6047198844.py │ ├── 10988.팰린드롬인지 확인하기/ │ │ └── 6047198844.py │ ├── 11000.강의실 배정/ │ │ └── 6047198844.py │ ├── 11003.최솟값 찾기/ │ │ └── 6047198844.py │ ├── 11047.동전0/ │ │ └── rockmiin.py │ ├── 11048.이동하기/ │ │ └── 6047198844.cpp │ ├── 11049.행렬 곱셈 순서/ │ │ └── 6047198844.py │ ├── 11050.이항 계수 1/ │ │ └── 6047198844.cpp │ ├── 11051.이항 계수 2/ │ │ ├── 6047198844.cpp │ │ └── ms9849.cpp │ ├── 11052. 카드 구매하기/ │ │ └── 6047198844.cpp │ ├── 11052.카드 구매하기/ │ │ └── rockmiin.py │ ├── 11054.가장 긴 바이토닉 부분 수열/ │ │ └── 6047198844.cpp │ ├── 11055.가장 큰 증가 부분 수열/ │ │ └── 6047198844.cpp │ ├── 11057.오르막 수/ │ │ └── Munang.py │ ├── 1106.호텔/ │ │ ├── sAp00n.py │ │ └── sangmandu.py │ ├── 11066.파일 합치기/ │ │ └── 6047198844.cpp │ ├── 1110.더하기 사이클/ │ │ └── sangmandu.py │ ├── 11170.0의 개수/ │ │ └── 6047198844.py │ ├── 1120.문자열/ │ │ └── 6047198844.py │ ├── 11256.사탕/ │ │ └── 6047198844.py │ ├── 11279.최대 힙/ │ │ └── 6047198844.cpp │ ├── 11286.절댓값 힙/ │ │ └── 6047198844.cpp │ ├── 11365.!밀비 급일/ │ │ └── 6047198844.py │ ├── 1138.한 줄로 서기/ │ │ └── sangmandu.py │ ├── 11382.꼬마 정민/ │ │ └── 6047198844.py │ ├── 11399.ATM/ │ │ ├── 6047198844.cpp │ │ └── rockmiin.py │ ├── 11401.이항계수 3/ │ │ └── 6047198844.cpp │ ├── 11403.경로 찾기/ │ │ ├── 6047198844.py │ │ └── rockmiin.py │ ├── 11404.플로이드/ │ │ └── 6047198844.cpp │ ├── 1141.접두사/ │ │ └── sangmandu.py │ ├── 11437.LCA/ │ │ └── 6047198844.py │ ├── 11438.LCA 2/ │ │ └── 6047198844.py │ ├── 11444.피보나치 수 6/ │ │ └── 11444_피보나치 수 6.cpp │ ├── 11478.서로 다른 부분 문자열의 개수/ │ │ └── 6047198844.py │ ├── 1149. RGB거리/ │ │ └── rockmiin.py │ ├── 11502.세 개의 소수 문제/ │ │ └── 6047198844.py │ ├── 11505.구간 곱 구하기/ │ │ └── 6047198844.py │ ├── 11508.2+1 세일/ │ │ └── 6047198844.py │ ├── 1152.단어의 개수/ │ │ └── 6047198844.py │ ├── 11559.Puyo Puyo/ │ │ └── 6047198844.py │ ├── 11561.징검다리/ │ │ └── 6047198844.py │ ├── 11562.백양로 브레이크/ │ │ └── 6047198844.py │ ├── 1157.단어 공부/ │ │ └── 6047198844.py │ ├── 1159.농구 경기/ │ │ └── 6047198844.py │ ├── 11653.소인수분해/ │ │ ├── 6047198844.cpp │ │ └── 6047198844.py │ ├── 11657.타임머신/ │ │ └── 6047198844.cpp │ ├── 1166.선물/ │ │ └── 6047198844.py │ ├── 11660.구간 합 구하기 5/ │ │ └── 6047198844.py │ ├── 11725.트리의 부모 찾기/ │ │ ├── input_data.md │ │ └── sAp00n.py │ ├── 11728.배열 합치기/ │ │ └── 6047198844.cpp │ ├── 11729.하노이 탑 이동 순서/ │ │ └── 6047198844.py │ ├── 11779.최소비용 구하기 2/ │ │ └── 6047198844.py │ ├── 1181.단어 정렬/ │ │ ├── 6047198844.cpp │ │ └── rockmiin.py │ ├── 1182.부분수열의 합/ │ │ └── 6047198844.py │ ├── 11866.요세푸스 문제 0/ │ │ └── 6047198844.cpp │ ├── 1188.음식 평론가/ │ │ └── 6047198844.py │ ├── 11942.고려대는 사랑입니다/ │ │ └── 6047198844.py │ ├── 11942.고려대는 사랑입니다./ │ │ └── 6047198844.py │ ├── 11943.파일 옮기기/ │ │ └── 6047198844.py │ ├── 11948.과목선택/ │ │ └── 6047198844.py │ ├── 1197.최소 스패닝 트리/ │ │ └── 6047198844.py │ ├── 1199.오일러 회로/ │ │ ├── 6047198844.cpp │ │ └── sAp00n.py │ ├── 12015.가장 긴 증가하는 부분 수열 2/ │ │ └── 6047198844.py │ ├── 1202.보석 도둑/ │ │ └── 6047198844.py │ ├── 1208.부분수열의 합 2/ │ │ └── 6047198844.py │ ├── 12100.2048 (Easy)/ │ │ └── 6047198844.py │ ├── 1213.팰린드롬 만들기/ │ │ └── 6047198844.py │ ├── 1219.오민식의 고민/ │ │ └── 6047198844.cpp │ ├── 1238.파티/ │ │ └── 6047198844.cpp │ ├── 1245.농장관리/ │ │ ├── input_data.md │ │ └── sAp00n.py │ ├── 1247.부호/ │ │ └── 6047198844.py │ ├── 1251.단어 나누기/ │ │ └── 6047198844.py │ ├── 1260.DFS와 BFS/ │ │ ├── input_data.md │ │ ├── rockmiin.py │ │ ├── s2uyeoii.c │ │ └── sAp00n.py │ ├── 1261.알고스팟/ │ │ ├── 6047198844.cpp │ │ └── dosimpact.py │ ├── 1264.모음의 개수/ │ │ └── 6047198844.py │ ├── 1269.대칭 차집합/ │ │ └── 6047198844.py │ ├── 1271.엄청난 부자2/ │ │ └── 6047198844.py │ ├── 1283.단축키 지정/ │ │ └── 6047198844.py │ ├── 12847.꿀 아르바이트/ │ │ └── 6047198844.py │ ├── 12850.본대 산책2/ │ │ └── 6047198844.py │ ├── 12852.1로 만들기 2/ │ │ ├── 6047198844.py │ │ └── ms9849.cpp │ ├── 12865.평범한 배낭/ │ │ └── 6047198844.cpp │ ├── 12886.돌 그룹/ │ │ └── 6047198844.py │ ├── 12904.A와 B/ │ │ └── 6047198844.py │ ├── 1292.쉽게 푸는 문제/ │ │ └── 6047198844.py │ ├── 1300.K번째 수/ │ │ └── 6047198844.py │ ├── 1302.베스트셀러/ │ │ └── 6047198844.py │ ├── 13022.늑대와 올바른 단어/ │ │ └── 6047198844.py │ ├── 1312.소수/ │ │ └── 6047198844.py │ ├── 1316.그룹 단어 체커/ │ │ └── 6047198844.py │ ├── 13241.최소공배수/ │ │ └── 6047198844.py │ ├── 1325.효율적인 해킹/ │ │ └── 효율적인해킹_1325.py │ ├── 13277.큰 수 곱셈/ │ │ └── 6047198844.py │ ├── 13301.타일 장식물/ │ │ └── 6047198844.py │ ├── 13333.Q-인덱스/ │ │ └── 6047198844.py │ ├── 1339.단어 수학/ │ │ └── 6047198844.py │ ├── 13460.구슬 탈출 2/ │ │ └── 6047198844.py │ ├── 13549.숨바꼭질 3/ │ │ └── 6047198844.cpp │ ├── 13565.침투/ │ │ └── 6047198844.py │ ├── 13702.이상한 술집/ │ │ └── 6047198844.py │ ├── 1376.민식우선탐색/ │ │ ├── input_list.md │ │ └── sAp00n.py │ ├── 1389. 케빈 베이컨의 6단계 법칙/ │ │ ├── 6047198844.py │ │ └── rockmiin.py │ ├── 13902.개업 2/ │ │ └── 6047198844.py │ ├── 13985.Equality/ │ │ └── 6047198844.py │ ├── 14002.가장 긴 증가하는 부분 수열 4/ │ │ └── 와일드카드.cpp │ ├── 14003.가장 긴 증가하는 부분 수열 5/ │ │ └── 6047198844.py │ ├── 1417.국회의원 선거/ │ │ └── 6047198844.py │ ├── 14226.이모티콘/ │ │ └── 6047198844.cpp │ ├── 1427.소트인사이드/ │ │ └── 6047198844.cpp │ ├── 1436.영화감독 숌/ │ │ └── 6047198844.cpp │ ├── 1439.뒤집기/ │ │ └── 6047198844.py │ ├── 14395.4연산/ │ │ └── 6047198844.py │ ├── 14405.피카츄/ │ │ └── 6047198844.py │ ├── 14425.문자열 집합/ │ │ └── 6047198844.py │ ├── 1446.지름길/ │ │ └── 6047198844.py │ ├── 14467.소가 길을 건너간 이유 1/ │ │ └── 6047198844.py │ ├── 1449.수리공 항승/ │ │ └── 6047198844.py │ ├── 14490.백대열/ │ │ └── 6047198844.py │ ├── 14500.테트로미노/ │ │ └── 6047198844.cpp │ ├── 14501.퇴사/ │ │ └── 6047198844.py │ ├── 14502.연구소/ │ │ ├── 6047198844.py │ │ ├── rockmiin.py │ │ └── sangmandu.py │ ├── 14503.로봇 청소기/ │ │ └── 6047198844.py │ ├── 14575.뒤풀이/ │ │ └── 6047198844.py │ ├── 14582.오늘도 졌다/ │ │ └── 6047198844.py │ ├── 1463. 1로 만들기/ │ │ └── rockmiin.py │ ├── 14712.넴모넴모 (Easy)/ │ │ └── 6047198844.py │ ├── 14719. 빗물/ │ │ └── sangmandu.py │ ├── 14722.우유 도시/ │ │ └── 6047198844.py │ ├── 14725.개미굴/ │ │ └── 6047198844.py │ ├── 14727.퍼즐 자르기/ │ │ └── 6047198844.cpp │ ├── 14729.칠무해/ │ │ └── 6047198844.py │ ├── 1484.다이어트/ │ │ └── 6047198844.py │ ├── 1487.물건 팔기/ │ │ └── 6047198844.py │ ├── 14888.연산자 끼워넣기/ │ │ ├── 6047198844.cpp │ │ └── ms9849.cpp │ ├── 14889. 스타트와 링크/ │ │ └── ms9849.cpp │ ├── 14890.경사로/ │ │ └── 6047198844.py │ ├── 14912.숫자 빈도수/ │ │ └── 6047198844.py │ ├── 14916.거스름돈/ │ │ └── 6047198844.py │ ├── 14928.큰 수 (BIG)/ │ │ └── 6047198844.py │ ├── 1503.세 수 고르기/ │ │ └── 6047198844.py │ ├── 1504.특정한 최단 경로/ │ │ └── 6047198844.cpp │ ├── 1509.팰린드롬 분할/ │ │ └── 6047198844.py │ ├── 1516.게임 개발/ │ │ └── 6047198844.py │ ├── 1520.내리막길/ │ │ └── 6047198844.cpp │ ├── 15312.이름 궁합/ │ │ └── 6047198844.py │ ├── 1541.잃어버린 괄호/ │ │ ├── 6047198844.cpp │ │ └── ms9849.cpp │ ├── 15439.Vera and Outfits/ │ │ └── 6047198844.py │ ├── 1550.16진수/ │ │ └── 6047198844.py │ ├── 15591.MooTube (Silver)/ │ │ └── 6047198844.cpp │ ├── 1562.계단 수/ │ │ └── 6047198844.py │ ├── 15652.N과 M (4)/ │ │ └── 6047198844.cpp │ ├── 15680.연세대학교/ │ │ └── 6047198844.py │ ├── 15686.치킨 배달/ │ │ └── 6047198844.py │ ├── 15719.중복된 숫자/ │ │ └── 6047198844.py │ ├── 15727.조별과제를 하려는데 조장이 사라졌다/ │ │ └── 6047198844.py │ ├── 15733.나는 누구인가/ │ │ └── 6047198844.py │ ├── 15787.기차가 어둠을 헤치고 은하수를/ │ │ └── sangmandu.py │ ├── 15829.Hashing/ │ │ └── 6047198844.py │ ├── 15873,공백 없는 A+B/ │ │ └── 6047198844.py │ ├── 15904.UCPC는 무엇의 약자일까?/ │ │ └── 6047198844.py │ ├── 15963.CASIO/ │ │ └── 6047198844.py │ ├── 15970.화살표 그리기/ │ │ └── 6047198844.py │ ├── 15993.1, 2, 3 더하기 8/ │ │ └── 6047198844.py │ ├── 1600.말이 되고픈 원숭이/ │ │ └── 6047198844.cpp │ ├── 1613.역사/ │ │ └── 6047198844.cpp │ ├── 16162.가희와 3단 고음/ │ │ └── 6047198844.py │ ├── 16173.점프왕 쪨리 (Small)/ │ │ └── 6047198844.py │ ├── 16197.두 동전/ │ │ └── 6047198844.py │ ├── 16198.에너지 모으기/ │ │ └── 6047198844.py │ ├── 1620.나는야 포켓몬 마스터 이다솜/ │ │ └── 6047198844.py │ ├── 16204.카드 뽑기/ │ │ └── 6047198844.py │ ├── 16208.귀찮음/ │ │ └── 6047198844.py │ ├── 16212.정열적인 정렬/ │ │ └── 6047198844.py │ ├── 16234.인구 이동/ │ │ ├── 6047198844.cpp │ │ └── rockmiin.py │ ├── 16236.아기 상어/ │ │ └── 6047198844.py │ ├── 1629.곱셈/ │ │ └── 6047198844.cpp │ ├── 1633.최고의 팀 만들기/ │ │ └── 6047198844.py │ ├── 16394.홍익대학교/ │ │ └── 6047198844.py │ ├── 16395.파스칼의 삼각형/ │ │ └── 6047198844.py │ ├── 16430.제리와 톰/ │ │ └── 6047198844.py │ ├── 16435.스네이크버드/ │ │ └── 6047198844.py │ ├── 16439.치킨치킨치킨/ │ │ └── 6047198844.py │ ├── 1647.도시 분할 계획/ │ │ └── 6047198844.py │ ├── 16507.어두운 건 무서워/ │ │ └── 6047198844.py │ ├── 16508.전공책/ │ │ └── 6047198844.py │ ├── 1654.랜선 자르기/ │ │ ├── 6047198844.cpp │ │ └── rockmiin_1654.py │ ├── 1655.가운데를 말해요/ │ │ └── 6047198844.cpp │ ├── 16637.괄호 추가하기/ │ │ └── 6047198844.py │ ├── 1668.트로피 진열/ │ │ └── 6047198844.py │ ├── 16724.피리 부는 사나이/ │ │ └── 6047198844.py │ ├── 16918.봄버맨/ │ │ └── 6047198844.py │ ├── 16922.로마 숫자 만들기/ │ │ └── 6047198844.py │ ├── 16928.뱀과 사다리 게임/ │ │ └── 6047198844.py │ ├── 16929.Two Dots/ │ │ └── 6047198844.cpp │ ├── 16937.두 스티커/ │ │ └── 6047198844.py │ ├── 16938.캠프 준비/ │ │ └── 6047198844.py │ ├── 16946.벽 부수고 이동하기 4/ │ │ └── 6047198844.py │ ├── 16948.데스 나이트/ │ │ └── 6047198844.py │ ├── 16951.블록 놀이/ │ │ └── 6047198844.py │ ├── 16954.움직이는 미로 탈출/ │ │ └── 6047198844.py │ ├── 16960.스위치와 램프/ │ │ └── 6047198844.py │ ├── 16987.계란으로 계란치기/ │ │ └── 6047198844.py │ ├── 1699.제곱수의 합/ │ │ ├── 6047198844.py │ │ └── 제곱수의_합_1699.py │ ├── 1707.이분그래프/ │ │ ├── .vscode/ │ │ │ └── launch.json │ │ └── 6047198844.cpp │ ├── 17070.파이프 옮기기1/ │ │ └── 6047198844.cpp │ ├── 17128.소가 정보섬에 올라온 이유/ │ │ └── 6047198844.py │ ├── 17135.캐슬 디펜스/ │ │ └── 6047198844.py │ ├── 17136.색종이 붙이기/ │ │ └── 6047198844.py │ ├── 17141.연구소 2/ │ │ └── 6047198844.py │ ├── 17143.낚시왕/ │ │ └── 6047198844.py │ ├── 1718.암호/ │ │ └── 6047198844.py │ ├── 17219.비밀번호 찾기/ │ │ └── 6047198844.py │ ├── 1725.히스토그램/ │ │ ├── 1725_히스토그램.cpp │ │ └── sAp00n.py │ ├── 17255.N으로 만들기/ │ │ └── 6047198844.py │ ├── 1726.로봇/ │ │ └── 6047198844.py │ ├── 17265.나의 인생에는 수학과 함께/ │ │ └── 6047198844.py │ ├── 17298.오큰수/ │ │ └── 6047198844.cpp │ ├── 1735.분수 합/ │ │ └── 6047198844.py │ ├── 17362.수학은 체육과목 입니다2/ │ │ └── 6047198844.py │ ├── 1738.골목길/ │ │ └── 6047198844.cpp │ ├── 17404.RGB거리 2/ │ │ └── 6047198844.cpp │ ├── 17413.단어 뒤집기2/ │ │ └── 6047198844.py │ ├── 17478.재귀함수가 뭔가요?/ │ │ └── 6047198844.py │ ├── 1753. 최단 경로/ │ │ └── rockmiin.py │ ├── 1753.최단경로/ │ │ └── 6047198844.cpp │ ├── 1755.숫자놀이/ │ │ └── 6047198844.py │ ├── 1758.알바생 강호/ │ │ └── 6047198844.py │ ├── 1759.암호만들기/ │ │ └── 6047198844.cpp │ ├── 1761.정점들의 거리/ │ │ └── 6047198844.py │ ├── 17626.Four Squares/ │ │ └── 6047198844.py │ ├── 1764. 듣보잡/ │ │ └── ms9849.cpp │ ├── 1764.듣보잡/ │ │ ├── 6047198844.py │ │ └── rockmiin.py │ ├── 1766.문제집/ │ │ └── 6047198844.py │ ├── 1769.3의 배수/ │ │ └── 6047198844.py │ ├── 17829.222-풀링/ │ │ └── 6047198844.py │ ├── 1789.수들의 합/ │ │ └── 6047198844.py │ ├── 1799.비숍/ │ │ └── 6047198844.py │ ├── 1806.부분합/ │ │ ├── 6047198844.cpp │ │ └── 6047198844.py │ ├── 18108.1998년생인 내가 태국에서는 2541년생?!/ │ │ └── 6047198844.py │ ├── 18111.마인크래프트/ │ │ └── 6047198844.py │ ├── 1817.짐 챙기는 숌/ │ │ └── 6047198844.py │ ├── 18258.큐 2/ │ │ └── 6047198844.cpp │ ├── 18312.시각/ │ │ └── 6047198844.py │ ├── 1834.나머지와 몫이 같은 수/ │ │ └── 6047198844.py │ ├── 18353.병사 배치하기/ │ │ └── 6047198844.py │ ├── 18512.점프 점프/ │ │ └── 6047198844.py │ ├── 1864.문어 숫자/ │ │ └── 6047198844.py │ ├── 1865.웜홀/ │ │ └── 6047198844.py │ ├── 1874.스택 수열/ │ │ └── 6047198844.py │ ├── 18868.멀티버스 Ⅰ/ │ │ └── 6047198844.py │ ├── 18870.좌표 압축/ │ │ └── 6047198844.cpp │ ├── 1890.점프/ │ │ └── 6047198844.cpp │ ├── 1895.필터/ │ │ └── 6047198844.py │ ├── 1904.01타일/ │ │ └── 6047198844.cpp │ ├── 1916.최소비용 구하기/ │ │ └── 1916_최소비용 구하기.cpp │ ├── 1918.후위 표기식/ │ │ └── 6047198844.py │ ├── 1920.수 찾기/ │ │ └── 6047198844.cpp │ ├── 19238.스타트 택시/ │ │ └── 6047198844.py │ ├── 1926.그림/ │ │ └── 6047198844.py │ ├── 1927.최소 힙/ │ │ └── 6047198844.cpp │ ├── 1929.소수 구하기/ │ │ └── 6047198844.py │ ├── 1931. 회의실 배정/ │ │ └── rockmiin.py │ ├── 1932.정수 삼각형/ │ │ ├── 6047198844.cpp │ │ ├── ms9849.cpp │ │ └── sAp00n.py │ ├── 1937.욕심쟁이 판다/ │ │ └── 6047198844.py │ ├── 1940.주몽/ │ │ └── 6047198844.py │ ├── 1942.디지털시계/ │ │ └── 6047198844.py │ ├── 1946.신입 사원/ │ │ ├── 6047198844.py │ │ └── rockmiin.py │ ├── 19532.수학은 비대면강의입니다/ │ │ └── 6047198844.py │ ├── 19583.싸이버개강총회/ │ │ └── 6047198844.py │ ├── 1963.소수 경로/ │ │ └── 6047198844.py │ ├── 1966.프린터 큐/ │ │ └── 6047198844.cpp │ ├── 19698.헛간 청약/ │ │ └── 6047198844.py │ ├── 1977.완전제곱수/ │ │ └── 6047198844.py │ ├── 1978.소수 찾기/ │ │ └── 6047198844.py │ ├── 19844.단어 개수 세기/ │ │ └── 6047198844.py │ ├── 1987.알파벳/ │ │ ├── 6047198844.py │ │ └── sangmandu.py │ ├── 1990.소수인펠린드롬/ │ │ └── 6047198844.py │ ├── 19939.박 터트리기/ │ │ └── 6047198844.py │ ├── 19942.다이어트/ │ │ └── 6047198844.py │ ├── 19951.태상이의 훈련소 생활/ │ │ └── 6047198844.py │ ├── 20040.사이클 게임/ │ │ └── 6047198844.py │ ├── 20053.최소, 최대 2/ │ │ └── 6047198844.py │ ├── 2014.소수의 곱/ │ │ └── 6047198844.py │ ├── 20154.이 구역의 승자는 누구야?!/ │ │ └── 6047198844.py │ ├── 2018.수들의 합 5/ │ │ └── 6047198844.py │ ├── 2023.신기한 소수/ │ │ └── 6047198844.py │ ├── 2042.구간 합 구하기/ │ │ └── 6047198844.cpp │ ├── 20436.ZOAC 3/ │ │ └── 6047198844.py │ ├── 20499.Darius님 한타 안함?/ │ │ └── 6047198844.py │ ├── 20546.🐜 기적의 매매법 🐜/ │ │ └── 6047198844.py │ ├── 20551.Sort 마스터 배지훈의 후계자/ │ │ └── 6047198844.py │ ├── 20944.팰린드롬 척화비/ │ │ └── 6047198844.py │ ├── 2096.내려가기/ │ │ └── 6047198844.py │ ├── 2098.외판원 순회/ │ │ └── 6047198844.py │ ├── 2104.부분배열/ │ │ └── sAp00n.py │ ├── 2108.통계학/ │ │ └── 6047198844.cpp │ ├── 2110 공유기 설치/ │ │ └── rockmiin.py │ ├── 2110.공유기 설치/ │ │ └── 6047198844.cpp │ ├── 21312.홀짝 칵테일/ │ │ └── 6047198844.py │ ├── 21313.문어/ │ │ └── 6047198844.py │ ├── 2143.두 배열의 합/ │ │ └── 6047198844.py │ ├── 2156.포도주 시식/ │ │ └── rockmiin.py │ ├── 2160.그림 비교/ │ │ └── 6047198844.py │ ├── 2161.카드1/ │ │ └── 6047198844.py │ ├── 21610.마법사 상어와 비바라기/ │ │ └── 6047198844.py │ ├── 2164.카드2/ │ │ ├── 6047198844.cpp │ │ └── 6047198844.py │ ├── 2167.2차원 배열의 합/ │ │ └── 6047198844.py │ ├── 2170.선 긋기/ │ │ └── 6047198844.py │ ├── 2174.로봇 시뮬레이션/ │ │ └── 6047198844.py │ ├── 21756.지우개/ │ │ └── 6047198844.py │ ├── 2178.미로 탐색/ │ │ └── rockmiin.py │ ├── 21918.전구/ │ │ └── 6047198844.py │ ├── 21919.소수 최소 공배수/ │ │ └── 6047198844.py │ ├── 2193.이친수/ │ │ └── rockmiin.py │ ├── 21937.작업/ │ │ └── 6047198844.py │ ├── 2206.벽 부수고 이동하기/ │ │ ├── 6047198844.py │ │ └── rockmiin.py │ ├── 2217.로프/ │ │ ├── 6047198844.cpp │ │ ├── 6047198844.py │ │ └── rockmiin.py │ ├── 2231.분해합/ │ │ └── 6047198844.cpp │ ├── 2239.스도쿠/ │ │ └── 6047198844.py │ ├── 2240.자두나무/ │ │ └── 6047198844.py │ ├── 2243.사탕상자/ │ │ └── 6047198844.py │ ├── 2252.줄 세우기/ │ │ ├── 6047198844.cpp │ │ └── 6047198844.py │ ├── 22864.피로도/ │ │ └── 6047198844.py │ ├── 2293.동전 1/ │ │ └── 6047198844.cpp │ ├── 2303.숫자 게임/ │ │ └── 6047198844.py │ ├── 2338.긴자리 계산/ │ │ └── 6047198844.py │ ├── 2342.Dance Dance Revolution/ │ │ └── 6047198844.py │ ├── 2346.풍선 터트리기/ │ │ └── 6047198844.py │ ├── 2357.최솟값과 최댓값/ │ │ └── 6047198844.py │ ├── 23795.사장님 도박은 재미로 하셔야 합니다/ │ │ └── 6047198844.py │ ├── 23825.SASA 모형을 만들어보자/ │ │ └── 6047198844.py │ ├── 24039.2021은 무엇이 특별할까/ │ │ └── 6047198844.py │ ├── 2407.조합/ │ │ └── 6047198844.py │ ├── 2420.사파리월드/ │ │ └── 6047198844.py │ ├── 2422.한윤정이 이탈리아에 가서 아이스크림을 사먹는데/ │ │ └── 6047198844.py │ ├── 24262.알고리즘 수업 - 알고리즘의 수행 시간 1/ │ │ └── 6047198844.py │ ├── 2437.저울/ │ │ └── 6047198844.cpp │ ├── 2444.별 찍기 - 7/ │ │ └── 6047198844.py │ ├── 2447.별찍기 - 10/ │ │ └── 6047198844.cpp │ ├── 2457.공주님의 정원/ │ │ └── 6047198844.py │ ├── 2467.용액/ │ │ ├── 6047198844.py │ │ └── ms9849.cpp │ ├── 2468.안전 영역/ │ │ ├── 6047198844.cpp │ │ └── rockmiin.py │ ├── 2473.세 용액/ │ │ └── 6047198844.py │ ├── 2475.검증수/ │ │ └── 6047198844.py │ ├── 2476.주사위 게임/ │ │ └── 6047198844.py │ ├── 2480.주사위 세개/ │ │ └── 6047198844.py │ ├── 2485.가로수/ │ │ └── 6047198844.py │ ├── 2490.윷놀이/ │ │ └── 6047198844.py │ ├── 2493.탑/ │ │ └── 6047198844.py │ ├── 2504.괄호의 값/ │ │ └── 6047198844.py │ ├── 25083.새싹/ │ │ └── 6047198844.py │ ├── 2517.달리기/ │ │ └── 6047198844.cpp │ ├── 25191.치킨댄스를 추는 곰곰이를 본 임스/ │ │ └── 6047198844.py │ ├── 2523.별찍기-13/ │ │ └── 6047198844.py │ ├── 2525.오븐 시계/ │ │ └── 6047198844.py │ ├── 2526.전깃줄/ │ │ └── sAp00n.py │ ├── 2529.부등호/ │ │ └── 6047198844.py │ ├── 2533.사회망 서비스(SNS)/ │ │ └── 6047198844.py │ ├── 2553.마지막 펙토리얼 수/ │ │ └── 6047198844.cpp │ ├── 2565.전깃줄/ │ │ └── 6047198844.cpp │ ├── 2568.전깃줄 - 2/ │ │ └── 6047198844.py │ ├── 2576.홀수/ │ │ └── 6047198844.py │ ├── 2580.스도쿠/ │ │ └── 6047198844.cpp │ ├── 2581.소수/ │ │ └── 6047198844.py │ ├── 2583.영역 구하기/ │ │ └── rockmiin.py │ ├── 2589.보물섬/ │ │ └── 6047198844.py │ ├── 2606.바이러스/ │ │ ├── 6047198844.cpp │ │ ├── rockmiin.py │ │ ├── sAp00n.py │ │ └── sangmandu.py │ ├── 2618.경찰차/ │ │ └── 6047198844.py │ ├── 2623.음악프로그램/ │ │ └── 6047198844.py │ ├── 2628.종이자르기/ │ │ └── 6047198844.py │ ├── 2630.색종이 만들기/ │ │ └── 6047198844.cpp │ ├── 2636.치즈/ │ │ ├── 6047198844.py │ │ └── sangmandu.py │ ├── 2638.치즈/ │ │ └── 6047198844.py │ ├── 2644.촌수 계산/ │ │ └── rockmiin.py │ ├── 2644.촌수계산/ │ │ └── 6047198844.cpp │ ├── 2651.자동차경주대회/ │ │ └── 2651_자동차경주대회.cpp │ ├── 2659.십자카드 문제/ │ │ └── 6047198844.cpp │ ├── 2660.회장뽑기/ │ │ └── 6047198844.cpp │ ├── 2667. 단지번호붙이기/ │ │ └── rockmiin.py │ ├── 2668.숫자 고르기/ │ │ └── 6047198844.cpp │ ├── 2669.직사각형 네개의 합집합의 면적 구하기/ │ │ └── 2669_직사각형 네개의 합집합의 면적 구하기.cpp │ ├── 2670.연속부분최대곱/ │ │ └── 6047198844.py │ ├── 2693.N번째 큰 수/ │ │ └── 6047198844.py │ ├── 2729.이진수 덧셈/ │ │ ├── 6047198844.py │ │ └── sangmandu.py │ ├── 2740.행렬곱셈/ │ │ └── sAp00n.py │ ├── 2744.대소문자 바꾸기/ │ │ └── 6047198844.py │ ├── 2745.진법 변환/ │ │ └── 6047198844.py │ ├── 2747.피보나치 수/ │ │ ├── 6047198844.cpp │ │ └── sangmandu.py │ ├── 2748.피보나치 수/ │ │ └── sangmandu.py │ ├── 2752.세수정렬/ │ │ └── 6047198844.py │ ├── 2776.암기왕/ │ │ └── 6047198844.py │ ├── 2792.보석 상자/ │ │ └── 6047198844.py │ ├── 2798.블랙잭/ │ │ ├── 6047198844.cpp │ │ └── 6047198844.java │ ├── 2805.나무 자르기/ │ │ └── 6047198844.cpp │ ├── 2812.크게 만들기/ │ │ └── 6047198844.py │ ├── 2822.점수 계산/ │ │ └── 6047198844.py │ ├── 2828.사과 담기 게임/ │ │ └── 6047198844.py │ ├── 2839.설탕 배달/ │ │ ├── 6047198844.py │ │ ├── pul8219.js │ │ └── rockmiin.py │ ├── 2845.파티가 끝나고 난 뒤/ │ │ └── 6047198844.py │ ├── 2847.게임을 만든 동준이/ │ │ └── 6047198844.py │ ├── 2851.슈퍼마리오/ │ │ └── sAp00n.py │ ├── 2863.이게 분수?/ │ │ └── 6047198844.py │ ├── 2869.달팽이는 올라가고 싶다/ │ │ └── 6047198844.py │ ├── 2887.행성 터널/ │ │ └── 6047198844.py │ ├── 2914.저작권/ │ │ └── 6047198844.py │ ├── 2935.소음/ │ │ └── 6047198844.py │ ├── 2960.에라토스테네스의 체/ │ │ └── 6047198844.py │ ├── 2961.도영이가 만든 맛있는 음식/ │ │ └── sangmandu.py │ ├── 2981.검문/ │ │ └── 6047198844.cpp │ ├── 3009.네 번째 점/ │ │ └── 6047198844.cpp │ ├── 3015.오아시스 재결합/ │ │ └── 6047198844.py │ ├── 3029.경고/ │ │ └── 6047198844.py │ ├── 3036.링/ │ │ └── 6047198844.cpp │ ├── 3040.백설 공주와 일곱 난쟁이/ │ │ └── 6047198844.py │ ├── 3053.택시 기하학/ │ │ └── 6047198844.cpp │ ├── 3055.탈출/ │ │ └── rockmiin.py │ ├── 3085.사탕 게임/ │ │ └── 6047198844.py │ ├── 3135.라디오/ │ │ └── 6047198844.py │ ├── 3176.도로 네트워크/ │ │ └── 6047198844.py │ ├── 3182.한동이는 공부가 하기 싫어!/ │ │ └── sangmandu.py │ ├── 3190.뱀/ │ │ └── rockmiin.py │ ├── 3273.두 수의 합/ │ │ └── 6047198844.py │ ├── 3980.선발 명단/ │ │ └── 6047198844.py │ ├── 3986.좋은 단어/ │ │ └── 6047198844.py │ ├── 4101.크냐?/ │ │ └── 6047198844.py │ ├── 4150.피보나치 수 7/ │ │ └── sangmandu.py │ ├── 4195.친구 네트워크/ │ │ └── 6047198844.py │ ├── 4195.친구네트워크/ │ │ └── dosimpact.py │ ├── 4358.생태학/ │ │ └── 6047198844.py │ ├── 4386.별자리 만들기/ │ │ └── 6047198844.py │ ├── 4485.녹색 옷 입은 애가 젤다지/ │ │ └── 6047198844.cpp │ ├── 4659.비밀번호 발음하기/ │ │ └── 6047198844.py │ ├── 4690.완전 세제곱 / │ │ └── 6047198844.py │ ├── 4796.캠핑/ │ │ └── 6047198844.py │ ├── 4803.트리/ │ │ └── 6047198844.py │ ├── 4948.베르트랑 공준/ │ │ └── 6047198844.cpp │ ├── 4963.섬의 개수/ │ │ └── rockmiin.py │ ├── 5014.스타트 링크/ │ │ └── rockmiin.py │ ├── 5014.스타트링크/ │ │ └── 6047198844.cpp │ ├── 5086.배수와 약수/ │ │ └── 6047198844.cpp │ ├── 5337.웰컴/ │ │ └── 6047198844.py │ ├── 5338.마이크로소프트 로고/ │ │ └── 6047198844.py │ ├── 5430.AC/ │ │ └── 6047198844.cpp │ ├── 5522.카드 게임/ │ │ └── 6047198844.py │ ├── 5532.방학 숙제/ │ │ └── 6047198844.py │ ├── 5535.간판/ │ │ └── 6047198844.py │ ├── 5554.심부름 가는 길/ │ │ └── 6047198844.py │ ├── 5557.1학년/ │ │ └── 6047198844.cpp │ ├── 5585.거스름 돈/ │ │ └── rockmiin_5585.py │ ├── 5596.시험 점수/ │ │ └── 6047198844.py │ ├── 5597.과제 안 내신 분..?/ │ │ └── 6047198844.py │ ├── 5618.공약수/ │ │ └── 6047198844.py │ ├── 5635.생일/ │ │ └── 6047198844.py │ ├── 5639.이진 검색 트리/ │ │ └── 6047198844.cpp │ ├── 5671.호텔 방 번호/ │ │ └── 6047198844.py │ ├── 5710.전기 요금/ │ │ └── sangmandu.py │ ├── 5719.거의 최단 경로/ │ │ └── 6047198844.py │ ├── 5766.할아버지는 유명해!/ │ │ └── 6047198844.py │ ├── 5800.성적 통계/ │ │ └── 6047198844.py │ ├── 5883.아이폰 9S/ │ │ └── 6047198844.py │ ├── 5904.Moo 게임/ │ │ └── 6047198844.py │ ├── 6198.옥상 정원 꾸미기/ │ │ └── ms9849.cpp │ ├── 6549.히스토그램에서 가장 큰 직사각형/ │ │ └── sAp00n.py │ ├── 6550.부분 문자열/ │ │ └── 6047198844.py │ ├── 6800.Huffman Encoding/ │ │ └── 6047198844.cpp │ ├── 7453.합이 0인 네 정수/ │ │ └── 6047198844.py │ ├── 7507.올림픽 경기/ │ │ └── sangmandu.py │ ├── 7562.나이트의 이동/ │ │ ├── rockmiin.py │ │ └── sangmandu.py │ ├── 7568.덩치/ │ │ └── 6047198844.cpp │ ├── 7569.토마토/ │ │ ├── 6047198844.py │ │ ├── ms9849.cpp │ │ └── rockmiin.py │ ├── 7576.토마토/ │ │ └── rockmiin.py │ ├── 7578.공장/ │ │ └── 6047198844.py │ ├── 7579.앱/ │ │ └── 6047198844.py │ ├── 7662.이중 우선순위 큐/ │ │ └── sangmandu.py │ ├── 7785.회사에 있는 사람/ │ │ └── 6047198844.py │ ├── 8979.올림픽/ │ │ └── 6047198844.py │ ├── 9009.피보나치/ │ │ └── sangmandu.py │ ├── 9019.DSLR/ │ │ ├── 6047198844.cpp │ │ └── 6047198844.py │ ├── 9020.골드바흐의 추측/ │ │ └── 6047198844.cpp │ ├── 9024.두 수의 합/ │ │ └── 6047198844.py │ ├── 9081.단어 맞추기/ │ │ └── sangmandu.py │ ├── 9084.동전/ │ │ └── 6047198844.py │ ├── 9085.더하기/ │ │ └── 6047198844.py │ ├── 9094.수학적 호기심/ │ │ └── 607198844.py │ ├── 9095.1,2,3 더하기/ │ │ └── 6047198844.cpp │ ├── 9184.신나는 함수 실행/ │ │ └── 6047198844.cpp │ ├── 9204.체스/ │ │ └── sangmandu.py │ ├── 9205.맥주 마시면서 걸어가기/ │ │ └── 6047198844.py │ ├── 9251.LCS/ │ │ └── 6047198844.cpp │ ├── 9252.LCS 2/ │ │ └── 6047198844.py │ ├── 9316.Hello Judge/ │ │ └── 6047198844.py │ ├── 9324.진짜 메시지/ │ │ └── 6047198844.py │ ├── 9325.얼마?/ │ │ └── 6047198844.py │ ├── 9328.열쇠/ │ │ └── 6047198844.py │ ├── 9375.패션왕 신해빈/ │ │ └── 6047198844.cpp │ ├── 9424.폭탄 해체/ │ │ └── 6047198844.py │ ├── 9461.파도반수열/ │ │ ├── 6047198844.py │ │ └── rockmiin.py │ ├── 9465.스티커/ │ │ ├── Munang.py │ │ └── sAp00n.py │ ├── 9536.여우는 어떻게 울지?/ │ │ └── 6047198844.py │ ├── 9625.BABBA/ │ │ └── 6047198844.py │ ├── 9653.스타워즈 로고/ │ │ └── 6047198844.py │ ├── 9654.나부 함대 데이터/ │ │ └── 6047198844.py │ ├── 9655.돌 게임/ │ │ └── 6047198844.py │ ├── 9663.N-Queen/ │ │ ├── 6047198844.cpp │ │ └── 6047198844.py │ ├── 9933.민균이의 비밀번호/ │ │ └── 6047198844.py │ └── solved.ac_class/ │ ├── Class01/ │ │ ├── 10818. 최소, 최대/ │ │ │ └── sAp00n.py │ │ ├── 10869.사칙연산/ │ │ │ └── sAp00n.py │ │ ├── 10950.A + B - 3/ │ │ │ └── sAp00n.py │ │ ├── 10951.A + B - 4/ │ │ │ └── sAp00n.py │ │ ├── 10952.A + B - 5/ │ │ │ └── sAp00n.py │ │ ├── 11654.아스키 코드/ │ │ │ └── sAp00n.py │ │ ├── 11720.숫자의 합/ │ │ │ └── sAp00n.py │ │ ├── 1330.두 수 비교하기/ │ │ │ └── sAp00n.py │ │ ├── 2438.별 찍기 - 1/ │ │ │ └── sAp00n.py │ │ ├── 2562.최댓값/ │ │ │ └── sAp00n.py │ │ ├── 2675.문자열 반복/ │ │ │ └── sAp00n.py │ │ ├── 2739.구구단/ │ │ │ └── sAp00n.py │ │ ├── 2920.음계/ │ │ │ └── sAp00n.py │ │ └── 8958.OX퀴즈/ │ │ └── sAp00n.py │ ├── Class02/ │ │ ├── 1018.채스판 다시 칠하기/ │ │ │ └── sAp00n.py │ │ ├── 10250.ACM호텔/ │ │ │ └── sAp00n.py │ │ ├── 10814.나이순 정렬/ │ │ │ └── sAp00n.py │ │ ├── 10816.숫자 카드2/ │ │ │ └── sAp00n.py │ │ ├── 10828.스택/ │ │ │ └── sAp00n.py │ │ ├── 10845.큐/ │ │ │ └── sAp00n.py │ │ ├── 1085.직사각형에서 탈출/ │ │ │ └── sAp00n.py │ │ ├── 10866.덱/ │ │ │ └── sAp00n.py │ │ ├── 11050. 이항계수/ │ │ │ └── sAp00n.py │ │ ├── 11650.좌표 정렬하기/ │ │ │ └── sAp00n.py │ │ ├── 1181.단어정렬/ │ │ │ └── sAp00n.py │ │ ├── 11866.요세푸스 문제/ │ │ │ └── sAp00n.py │ │ ├── 1259.팰린드롬수/ │ │ │ └── sAp00n.py │ │ ├── 1920.수 찾기/ │ │ │ └── sAp00n.py │ │ ├── 1978.소수 찾기/ │ │ │ └── sAp00n.py │ │ ├── 2164.카드2/ │ │ │ └── sAp00n.py │ │ ├── 2609. 최대공약수와 최소공배수/ │ │ │ └── sAp00n.py │ │ ├── 2798.블랙잭/ │ │ │ └── sAp00n.py │ │ └── 9023.괄호/ │ │ └── sAp00n.py │ ├── Class03/ │ │ ├── 1003.피보나치 함수/ │ │ │ └── sAp00n.py │ │ ├── 1012.유기농 배추/ │ │ │ └── sAp00n.py │ │ ├── 1074.Z/ │ │ │ ├── sAp00n.md │ │ │ └── sAp00n.py │ │ ├── 11279.최대 힙/ │ │ │ └── sAp00n.py │ │ ├── 11399. ATM/ │ │ │ └── sAp00n.py │ │ ├── 11723.집합/ │ │ │ └── sAp00n.py │ │ ├── 11724.연결 요소의 개수/ │ │ │ └── sAp00n.py │ │ ├── 11726.2xn 타일링/ │ │ │ └── sAp00n.py │ │ ├── 1463.1로 만들기/ │ │ │ ├── sAp00n.md │ │ │ └── sAp00n.py │ │ ├── 1620.나는야 포캣몬 마스터 이다솜/ │ │ │ └── sAp00n.py │ │ ├── 1697.숨바꼭질/ │ │ │ ├── sAp00n.py │ │ │ └── test_case.md │ │ ├── 1764.듣보잡/ │ │ │ └── sAp00n.py │ │ ├── 18870.좌표 압축/ │ │ │ └── sAp00n.py │ │ ├── 1927.최소 힙/ │ │ │ └── sAp00n.py │ │ ├── 1931. 회의실배정/ │ │ │ └── sAp00n.py │ │ ├── 2630.색종이 만들기/ │ │ │ └── sAp00n.py │ │ ├── 7576.토마토/ │ │ │ └── sAp00n.py │ │ ├── 7662.이중 우선순위 큐/ │ │ │ └── sAp00n.py │ │ └── 9095.1, 2, 3 더하기/ │ │ └── sAp00n.py │ └── Class04/ │ ├── 1149.RGB거리/ │ │ └── sAp00n.py │ ├── 1176.트리의 지름/ │ │ └── sAp00n.py │ ├── 1629.곱셈/ │ │ └── sAp00n.py │ ├── 1753.최단경로/ │ │ └── sAp00n.py │ └── 1786.찾기/ │ └── sAp00n.py ├── JSTestModule.js ├── LeetCode/ │ ├── Array/ │ │ ├── 3Sum/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── 3Sum_Closet/ │ │ │ └── 6047198844.py │ │ ├── 4Sum/ │ │ │ └── 6047198844.py │ │ ├── Add_Two_Numbers/ │ │ │ └── wongueShin/ │ │ │ ├── _test.dart │ │ │ └── solution.dart │ │ ├── Arranging_Coins/ │ │ │ └── HyeonJeong.java │ │ ├── Array_Partition_I/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.java │ │ ├── Best_Time_to_Buy_and_Sell_Stock/ │ │ │ └── 6047198844.py │ │ ├── Binary Search/ │ │ │ └── 6047198844.py │ │ ├── Bulb_Switcher_III/ │ │ │ └── HyeonJeong.py │ │ ├── Capacity To Ship Packages Within D Days/ │ │ │ └── 6047198844.cpp │ │ ├── Combination_Sum/ │ │ │ ├── 6047198844.py │ │ │ └── JeongShin.js │ │ ├── Combination_Sum_II/ │ │ │ └── JeongShin.js │ │ ├── Construct Binary Tree from Inorder and Postorder Traversal/ │ │ │ └── 6047198844.cpp │ │ ├── Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal/ │ │ │ ├── 6047198844.cpp │ │ │ └── 6047198844.py │ │ ├── Container_With_Most_Water/ │ │ │ └── 6047198844.py │ │ ├── Contains_Duplicate/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Count_Negative_Numbers_in_a_Sorted_Matrix/ │ │ │ └── 6047198844.cpp │ │ ├── Create_Target_Array_in_the_Given_Order/ │ │ │ └── HyeonJeong.py │ │ ├── Distance_Between_Bus_Stops/ │ │ │ └── 6047198844.py │ │ ├── Fair_Candy_Swap/ │ │ │ └── HyeonJeong.java │ │ ├── Filter_Restaurants_by_Vegan-Friendly,_Price_and_Distance/ │ │ │ └── 6047198844.py │ │ ├── Find Numbers with Even Number of Digits/ │ │ │ └── 6047198844.py │ │ ├── Find the Highest Altitude/ │ │ │ └── 6047198844.py │ │ ├── Find the Town Judge/ │ │ │ └── 6047198844.py │ │ ├── Find_Common_Characters/ │ │ │ └── HyeonJeong.py │ │ ├── Find_First_and_Last_Position_of_Element_in_Sorted_Array/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Find_Pivot_Index/ │ │ │ └── HyeonJeong.java │ │ ├── Find_the_Duplicate_Number/ │ │ │ └── 6047198844.py │ │ ├── First Missing Positive/ │ │ │ └── 6047198844.py │ │ ├── Flipping_an_Image/ │ │ │ └── HyeonJeong.java │ │ ├── Insert Interval/ │ │ │ └── 6047198844.py │ │ ├── Intersection_of_Two_Arrays/ │ │ │ └── HyeonJeong.py │ │ ├── Jump Game/ │ │ │ └── 6047198844.py │ │ ├── Jump Game II/ │ │ │ └── 6047198844.py │ │ ├── Keyboard_Row/ │ │ │ └── HyeonJeong.py │ │ ├── Kth_Missing_Positive_Number/ │ │ │ └── HyeonJeong.py │ │ ├── Largest_Number_At_Least_Twice_of_Others/ │ │ │ └── 6047198844.py │ │ ├── Longest _Palindromic_Substring/ │ │ │ └── 6047198844.py │ │ ├── Longest_Common_Subsequence/ │ │ │ └── JeongShin.js │ │ ├── Lucky Numbers in a Matrix/ │ │ │ └── 6047198844.py │ │ ├── Marjority_Element/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Max_Consecutive_Ones/ │ │ │ └── HyeonJeong.java │ │ ├── Maximum_Ice_Cream_Bars/ │ │ │ └── HyeonJeong.py │ │ ├── Maximum_Subarray/ │ │ │ └── 6047198844.py │ │ ├── Maximum_Swap/ │ │ │ └── HyeonJeong.py │ │ ├── Merge_Intervals/ │ │ │ ├── 6047198844.py │ │ │ ├── HyeonJeong.py │ │ │ └── kth496.kt │ │ ├── Minimum_Number_of_Days_to_Make_m_Bouquets/ │ │ │ └── 6047198844.cpp │ │ ├── Minimum_Path_Sum/ │ │ │ └── 6047198844.cpp │ │ ├── Minimum_Value_to_Get_Positive_Step_by_Step_Sum/ │ │ │ └── 6047198844.cpp │ │ ├── Missing Number/ │ │ │ └── 6047198844.py │ │ ├── Missing_Number/ │ │ │ └── HyeonJeong.py │ │ ├── Move_Zeroes/ │ │ │ └── 6047198844.py │ │ ├── Peak_Index_in_a_Mountain_Array/ │ │ │ └── 6047198844.cpp │ │ ├── Permutations/ │ │ │ └── JeongShin.js │ │ ├── Permutations_II/ │ │ │ └── JeongShin.js │ │ ├── Plus_One/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Product_of_Array_Except_Self/ │ │ │ └── 6047198844.py │ │ ├── Remove Duplicates from Sorted Array II/ │ │ │ └── 6047198844.py │ │ ├── Remove_Duplicates_from_Sorted_Array/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Remove_Element/ │ │ │ └── 6047198844.py │ │ ├── Richest_Customer_Wealth/ │ │ │ └── HyeonJeong.java │ │ ├── Rotate_Array/ │ │ │ └── HyeonJeong.py │ │ ├── Rotate_Image/ │ │ │ └── 604798844.py │ │ ├── Running_Sum_of_1d_Array/ │ │ │ └── HyeonJeong.py │ │ ├── Search a 2D Matrix/ │ │ │ └── 6047198844.py │ │ ├── Search_Insert_Position/ │ │ │ └── HyeonJeong.py │ │ ├── Search_in_Rotated_Sorted_Array/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJoeng.py │ │ ├── Set Matrix Zeroes/ │ │ │ └── 6047198844.py │ │ ├── Single_Number/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.java │ │ ├── Single_Number_III/ │ │ │ └── HyeonJeong.py │ │ ├── Sort Colors/ │ │ │ └── 6047198844.py │ │ ├── Sort_Array_By_Parity_II/ │ │ │ └── HyeonJeong.java │ │ ├── Sort_Colors/ │ │ │ └── HyeonJeong.py │ │ ├── Spiral Matrix/ │ │ │ └── 6047198844.py │ │ ├── Squares_of_a_Sorted_Array/ │ │ │ └── HyeonJeong.java │ │ ├── Summary_Ranges/ │ │ │ └── HyeonJeong.java │ │ ├── The_K_Weakest_Rows_in_a_Matrix/ │ │ │ └── 6047198844.cpp │ │ ├── Third_Maximum_Number/ │ │ │ └── HyeonJeong.java │ │ ├── Three Consecutive Odds/ │ │ │ └── 6047198844.py │ │ ├── TwoSum/ │ │ │ ├── 6047198844.py │ │ │ ├── HyeonJeong.py │ │ │ ├── JeongShin.js │ │ │ └── eyabc.js │ │ ├── Two_Sum_II_-_Input_array_is_sorted/ │ │ │ ├── 6047198844(2).cpp │ │ │ └── 6047198844.cpp │ │ ├── Unique Paths II/ │ │ │ └── 6047198844.py │ │ ├── Unique_Paths/ │ │ │ └── HyeonJeong.py │ │ ├── Word Search/ │ │ │ └── 6047198844.py │ │ └── zigzag_conversion/ │ │ └── wongue_shin.dart │ ├── Backtracking/ │ │ ├── Combination Sum II/ │ │ │ └── 6047198844.cpp │ │ ├── Combination Sum III/ │ │ │ └── 6047198844.cpp │ │ ├── Combination Sum IV/ │ │ │ └── 6047198844.cpp │ │ ├── Combination_Sum/ │ │ │ └── 6047198844.cpp │ │ ├── Combinations/ │ │ │ └── 6047198844.cpp │ │ ├── Letter_Combinations_of_a_Phone_Number/ │ │ │ └── JeongShin.js │ │ ├── N-Queens/ │ │ │ └── 6047198844.cpp │ │ ├── N-Queens_II/ │ │ │ └── 6047198844.cpp │ │ ├── Next Permutation/ │ │ │ └── 6047198844.cpp │ │ ├── Palindrome_Partitioning/ │ │ │ └── JeongShin.js │ │ ├── Path_with_Maximum_Gold/ │ │ │ └── kth496.kt │ │ ├── Permutations/ │ │ │ └── 6047198844.cpp │ │ ├── Permutations II/ │ │ │ └── 6047198844.cpp │ │ ├── Subsets/ │ │ │ └── JeongShin.js │ │ ├── Subsets_II/ │ │ │ └── JeongShin.js │ │ ├── Word_Search/ │ │ │ └── JeongShin.js │ │ └── Word_Search_II/ │ │ └── JeongShin.js │ ├── Binary_Search/ │ │ ├── Find_the_Smallest_Divisor_Given_a_Threshold/ │ │ │ └── 6047198844.cpp │ │ ├── First_Bad_Version/ │ │ │ └── 6047198844.py │ │ ├── Guess_Number_Higher_or_Lower/ │ │ │ └── 6047198844.py │ │ ├── Koko_Eating_Bananas/ │ │ │ └── 6047198844.cpp │ │ ├── Minimum_Size_Subarray_Sum/ │ │ │ ├── JeongShin.js │ │ │ └── eyabc.js │ │ ├── Path With Minimum Effort/ │ │ │ └── 6047198844.py │ │ └── Search-in-Rotated-Sorted-Array/ │ │ └── JeongShin.js │ ├── Breadth-first_Search/ │ │ ├── 01_Matrix/ │ │ │ └── JeongShin.js │ │ ├── Shortest_Path_in_Binary_Matrix/ │ │ │ └── 6047198844.cpp │ │ ├── Word_Ladder/ │ │ │ ├── 6047198844.cpp │ │ │ └── JeongShin.js │ │ └── Word_Ladder_II/ │ │ └── JeongShin.js │ ├── DP/ │ │ ├── Best_Time_to_Buy_and_Sell_Stock/ │ │ │ └── sangmandu.py │ │ ├── Climbing Stairs/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── Coin_Change/ │ │ │ └── JeongShin.js │ │ ├── Count_Sorted_Vowel_Strings/ │ │ │ └── sangmandu.py │ │ ├── Counting_Bits/ │ │ │ └── sangmandu.py │ │ ├── Divisor_Game/ │ │ │ └── sangmandu.py │ │ ├── Edit_Distance/ │ │ │ └── JeongShin.js │ │ ├── House_Robber_III/ │ │ │ └── 6047198844.py │ │ ├── Is Subsequence/ │ │ │ └── sangmandu.py │ │ ├── Longest_Increasing_Subsequence/ │ │ │ └── 6047198844.py │ │ ├── Maximum Subarray/ │ │ │ └── sangmandu.py │ │ ├── Min Cost Climbing Stairs/ │ │ │ └── sangmandu.py │ │ ├── MinimumPathSum/ │ │ │ ├── JeongShin.js │ │ │ └── ReadMe.md │ │ ├── Range Sum Query - Immutable/ │ │ │ └── sangmandu.py │ │ ├── Stone_Game II/ │ │ │ ├── 6047198844.cpp │ │ │ └── 6047198844.py │ │ ├── Unique_Paths/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── ReadMe.md │ │ ├── Word_Break/ │ │ │ └── JeongShin.js │ │ └── Word_Break_II/ │ │ └── 6047198844.cpp │ ├── Database/ │ │ └── Duplicate_Emails/ │ │ └── 6047198844 │ ├── Depth-first_Search/ │ │ ├── Convert_BST_to_Greater_Tree/ │ │ │ └── 6047198844.cpp │ │ ├── Course_Schedule/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── eyabc.js │ │ ├── Course_Schedule_II/ │ │ │ ├── JeongShin.js │ │ │ └── eyabc.js │ │ ├── Flatten Binary Tree to Linked List/ │ │ │ └── 6047198844.cpp │ │ ├── Letter Combinations of a Phone Number/ │ │ │ └── 6047198844.cpp │ │ ├── Maximum_Depth_of_Binary_Tree/ │ │ │ └── 6047198844.java │ │ ├── Maximum_Depth_of_N-ary_Tree/ │ │ │ └── 6047198844.java │ │ ├── Minimum_Depth_of_Binary_Tree/ │ │ │ └── 6047198844.java │ │ ├── Number of Closed Islands/ │ │ │ └── 6047198844.cpp │ │ ├── Number_of_Islands/ │ │ │ ├── 6047198844.cpp │ │ │ ├── 6047198844.py │ │ │ └── JeongShin.js │ │ ├── PathSum_II/ │ │ │ └── JeongShin.js │ │ ├── Reconstruct Itinerary/ │ │ │ └── 6047198844.py │ │ ├── Recover_Binary_Search_Tree/ │ │ │ └── 6047198844.cpp │ │ ├── Symmetric_Tree/ │ │ │ └── 6047198844.java │ │ ├── Target_Sum/ │ │ │ └── JeongShin.js │ │ └── Validate_Binary_Search_Tree/ │ │ └── 6047198844.cpp │ ├── Divide_and_Conquer/ │ │ └── Kth_Largest_Element_in_an_Array/ │ │ ├── 6047198844.py │ │ └── HyeonJeong.java │ ├── Graph/ │ │ ├── 787. Cheapest Flights Within K Stops/ │ │ │ └── wongue.shin/ │ │ │ ├── ._test.dart │ │ │ └── solution.dart │ │ ├── All Paths From Source to Target/ │ │ │ └── sangmandu.py │ │ ├── Find the Town Judge/ │ │ │ └── sangmandu.py │ │ ├── Find_Center_of_Star_Graph/ │ │ │ └── sangmandu.py │ │ ├── Find_the_City_With_the_Smallest_Number_of_Neighbors_at_a_Threshold_Distance/ │ │ │ └── 6047198844.cpp │ │ ├── Minimum Number of Vertices to Reach All Nodes/ │ │ │ └── sangmandu.py │ │ ├── Path_With_Minimum_Effort/ │ │ │ └── 6047198844.cpp │ │ ├── Path_with_Maximum_Probability/ │ │ │ └── 6047198844.cpp │ │ ├── Redundant_Connection/ │ │ │ └── sangmandu.py │ │ ├── Regions Cut By Slashes/ │ │ │ └── sangmandu.py │ │ ├── Sort Integers by The Power Value/ │ │ │ └── sangmandu.py │ │ └── keys-and-rooms/ │ │ └── sangmandu.py │ ├── Greedy/ │ │ ├── Split_a_String_in_Balanced_Strings/ │ │ │ └── eyabc.js │ │ ├── Assign_Cookies/ │ │ │ └── HyeonJeong.java │ │ ├── Can_Place_Flowers/ │ │ │ └── HyeonJeong.java │ │ ├── Car_Pooling/ │ │ │ └── HyeonJeong.py │ │ ├── Group_the_People_Given_the_Group_Size_They_Belong_To/ │ │ │ ├── HyeonJeong.py │ │ │ └── sangmandu.py │ │ ├── Is_Subsequence/ │ │ │ └── HyeonJoeng.py │ │ ├── Jump_Game/ │ │ │ └── JeongShin.js │ │ ├── Maximize_Sum_Of_Array_After_K_Negations/ │ │ │ └── 6047198844.cpp │ │ └── Remove_Covered_Intervals/ │ │ ├── 607198844.py │ │ └── HyeonJeong.py │ ├── Hash_Table/ │ │ ├── Daily Temperatures/ │ │ │ └── 6047198844.py │ │ ├── Find the Difference/ │ │ │ └── 6047198844.py │ │ ├── First_Unique_Character_in_a_String/ │ │ │ └── 6047198844.py │ │ ├── Grid Illumination/ │ │ │ └── 6047198844.cpp │ │ ├── Happy_Number/ │ │ │ └── 6047198844.py │ │ ├── Implement_Trie_(Prefix_Tree)/ │ │ │ └── 6047198844.py │ │ ├── Integer_to_Roman/ │ │ │ └── 6047198844.py │ │ ├── Intersection_of_Two_Arrays/ │ │ │ └── 6047198844.cpp │ │ ├── Isomorphic Strings/ │ │ │ └── 6047198844.py │ │ ├── Linked_List_Cycle/ │ │ │ └── 6047198844.py │ │ ├── Top_K_Frequent_Elements/ │ │ │ └── 6047198844.py │ │ ├── Two_Sum/ │ │ │ └── 6047198844.cpp │ │ ├── Valid_Anagram/ │ │ │ └── 6047198844.py │ │ └── Valid_Sudoku/ │ │ └── 6047198844.py │ ├── Heap/ │ │ └── Network_Delay_Time/ │ │ └── 6047198844.cpp │ ├── Linked_List/ │ │ ├── Add_Two_Numbers/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Convert_Sorted_List_to_Binary_Search_Tree/ │ │ │ └── 6047198844.cpp │ │ ├── Delete_Node_in_a_Linked_List/ │ │ │ └── 6047198844.py │ │ ├── Merge Two Sorted Lists/ │ │ │ └── 6047198844.cpp │ │ ├── Merge k Sorted Lists/ │ │ │ └── 6047198844.py │ │ ├── Odd Even Linked List/ │ │ │ └── 6047198844.py │ │ ├── Palindrome_Linked_List/ │ │ │ └── HyeonJeong.java │ │ ├── Partition List/ │ │ │ └── 6047198844.py │ │ ├── Remove_Duplicates_from_Sorted_List/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Remove_Linked_List_Elements/ │ │ │ └── HyeonJeong.java │ │ ├── Remove_Nth_Node_From_End_of_List/ │ │ │ └── 6047198844.py │ │ ├── Reverse_Linked_List_II/ │ │ │ └── HyeonJeong.py │ │ ├── Rotate List/ │ │ │ └── 6047198844.py │ │ ├── Swap_Nodes_in_Pairs/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.java │ │ └── sangmandu.py │ ├── Math/ │ │ ├── Add_Binary/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Add_Digits/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Check_If_It_Is_a_Straight_Line/ │ │ │ └── HyeonJeong.java │ │ ├── Complement_of_Base_10_Integer/ │ │ │ └── HyeonJeong.py │ │ ├── Day_of_the_Week/ │ │ │ └── 6047198844.py │ │ ├── Day_of_the_Year/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Distribute_Candies_to_People/ │ │ │ └── HyeonJeong.java │ │ ├── Divide_Two_Integers/ │ │ │ └── 6047198844.py │ │ ├── Divisor_Game/ │ │ │ └── HyeonJeong.java │ │ ├── Factorial_Trailing_Zeroes/ │ │ │ └── HyeonJeong.py │ │ ├── Find_Numbers_with_Even_Number_of_Digits/ │ │ │ └── HyeonJeong.py │ │ ├── Happy_Number/ │ │ │ └── HyeonJeong.py │ │ ├── Maximum_Product_of_Three_Numbers/ │ │ │ └── HyeonJeong.java │ │ ├── Multiply Strings/ │ │ │ └── 6047198844.py │ │ ├── Number_of_Steps_to_Reduce_a_Number_to_Zero/ │ │ │ └── HyeonJeong.py │ │ ├── Palindrome Number/ │ │ │ └── 6047198844.cpp │ │ ├── Permutation Sequence/ │ │ │ └── 6047198844.py │ │ ├── Pow(x,_n)/ │ │ │ └── 6047198844.py │ │ ├── Power_of_Four/ │ │ │ └── 6047198844.py │ │ ├── Power_of_Three/ │ │ │ └── HyeonJeong.py │ │ ├── Power_of_Two/ │ │ │ └── 6047198844.py │ │ ├── Powerful_Integers/ │ │ │ └── HyeonJeong.py │ │ ├── Prime Arrangements/ │ │ │ └── 6047198844.py │ │ ├── Reverse_Integer/ │ │ │ ├── 6047198844.py │ │ │ ├── HyeonJeong.py │ │ │ └── SeokBin.java │ │ ├── Roman to Integer/ │ │ │ └── 6047198844.py │ │ ├── Rotate_Image/ │ │ │ └── HyeonJeong.py │ │ ├── Sqrt(x)/ │ │ │ ├── 6047198844.cpp │ │ │ └── HyeonJeong.py │ │ ├── String_to_Integer_(atoi)/ │ │ │ └── 6047198844.py │ │ ├── Ugly Number/ │ │ │ └── 6047198844.py │ │ ├── Unique Binary Search Trees/ │ │ │ └── 6047198844.py │ │ ├── Valid_Perfect_Square/ │ │ │ └── 6047198844.py │ │ └── Water_Bottles/ │ │ └── 6047198844.py │ ├── Queue/ │ │ ├── Design_Circular_Deque/ │ │ │ └── HyeonJeong.py │ │ └── Number_of_Recent_Calls/ │ │ └── HyeonJeong.py │ ├── Sliding_Window/ │ │ ├── Longest_Substring_Without_Repeating_Characters/ │ │ │ └── JeongShin.js │ │ └── Minimum_Window_Substring/ │ │ ├── 6047198844.cpp │ │ └── JeongShin.js │ ├── Sort/ │ │ └── 6047198844.cpp │ ├── Stack/ │ │ ├── 6047198844.py │ │ ├── Backspace-String-Compare/ │ │ │ └── 6047198844.cpp │ │ ├── Binary Tree Inorder Traversal/ │ │ │ └── 6047198844.py │ │ ├── Binary Tree Postorder Traversal/ │ │ │ └── 6047198844.py │ │ └── Implement Stack using Queues/ │ │ └── 6047198844.py │ ├── String/ │ │ ├── Complex_Number_Multiplication/ │ │ │ └── HyeonJeong.py │ │ ├── Count_and_Say/ │ │ │ └── 6047198844.py │ │ ├── Defanging_an_IP_Address/ │ │ │ └── 6047198844.py │ │ ├── Generate_Parentheses/ │ │ │ └── 6047198844.py │ │ ├── Group_Anagrams/ │ │ │ └── JeongShin.js │ │ ├── Implement_strStr()/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Length_of_Last_Word/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Letter_Combinations_of_a_Phone_Number/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ ├── Longest Valid Parentheses/ │ │ │ └── 6047198844.py │ │ ├── Longest_Common_Prefix/ │ │ │ └── 6047198844.cpp │ │ ├── Longest_Palindrome/ │ │ │ └── HyeonJeong.py │ │ ├── Longest_Substring_Without_Repeating_Characters/ │ │ │ └── HyeonJoeng.py │ │ ├── Make_The_String_Great/ │ │ │ └── HyeonJeong.py │ │ ├── Maximum_69_Number/ │ │ │ └── HyeonJeong.py │ │ ├── Number of Strings That Appear as Substrings in Word/ │ │ │ └── 6047198844.py │ │ ├── Palindromic_Substrings/ │ │ │ └── 이준수.py │ │ ├── Ransom_Note/ │ │ │ └── HyeonJeong.java │ │ ├── Rearrange_Words_in_a_Sentence/ │ │ │ └── HyeonJeong.py │ │ ├── Regular_Expression_Matching/ │ │ │ └── 6047198844.py │ │ ├── Restore IP Addresses/ │ │ │ └── 6047198844.py │ │ ├── Reverse_String/ │ │ │ └── HyeonJeong.java │ │ ├── Robot Return to Origin/ │ │ │ └── 6047198844.py │ │ ├── Roman_to_Integer/ │ │ │ └── HyeonJoeng.py │ │ ├── Rotate String/ │ │ │ └── 6047198844.py │ │ ├── Simplify Path/ │ │ │ └── 6047198844.py │ │ ├── String_to_Integer_(atoi)/ │ │ │ └── 6047198844.py │ │ ├── Thousand Separator/ │ │ │ └── 6047198844.py │ │ ├── To_Lower_Case/ │ │ │ └── HyeonJeong.java │ │ ├── Valid_Parentheses/ │ │ │ ├── 6047198844.py │ │ │ └── HyeonJeong.py │ │ └── ZigZag_Conversion/ │ │ ├── 6047198844.py │ │ ├── HyeonJeong.py │ │ └── Seokbin.java │ ├── Tree/ │ │ ├── Balanced_Binary_Tree/ │ │ │ └── 6047198844.py │ │ ├── Binary_Search_Tree_to_Greater_Sum_Tree/ │ │ │ └── 6047198844.py │ │ ├── Binary_Tree_Paths/ │ │ │ └── 6047198844.cpp │ │ ├── Convert Sorted Array to Binary Search Tree/ │ │ │ ├── 6047198844.java │ │ │ └── 6047198844.py │ │ ├── Diameter_of_Binary_Tree/ │ │ │ └── 6047198844.py │ │ ├── Find_Bottom_Left_Tree_Value/ │ │ │ ├── 6047198844.cpp │ │ │ └── val │ │ ├── Increasing_Order_Search_Tree/ │ │ │ └── 6047198844.cpp │ │ ├── Invert_Binary_Tree/ │ │ │ └── 6047198844.py │ │ ├── Leaf-Similar_Trees/ │ │ │ └── 6047198844.cpp │ │ ├── Longest_Univalue_Path/ │ │ │ └── 6047198844.py │ │ ├── Maximum_Depth_of_Binary_Tree/ │ │ │ └── 6047198844.py │ │ ├── Merge_Two_Binary_Trees/ │ │ │ └── 6047198844.py │ │ ├── Minimum_Height_Trees/ │ │ │ └── 6047198844.py │ │ ├── Path_Sum/ │ │ │ └── 6047198844.cpp │ │ ├── Path_Sum_II/ │ │ │ └── 6047198844.cpp │ │ ├── Path_Sum_III/ │ │ │ └── JeongShin.js │ │ ├── Same Tree/ │ │ │ └── 6047198844.cpp │ │ ├── Serialize_and_Deserialize_Binary_Tree/ │ │ │ └── 6047198844.py │ │ └── Unique_Binary_Search_Trees/ │ │ └── JeongShin.js │ ├── Trie/ │ │ ├── Design_Add_and_Search_Words_Data_Structure/ │ │ │ └── JeongShin.js │ │ ├── Palindrome_Pairs/ │ │ │ ├── JeongShin.js │ │ │ └── eyabc.js │ │ ├── Replace_Words/ │ │ │ └── JeongShin.js │ │ ├── Top_K_Frequent_Words/ │ │ │ └── JeongShin.js │ │ └── Word_Break/ │ │ └── 6047198844.py │ ├── Two_Pointers/ │ │ ├── Is Subsequence/ │ │ │ └── 604719844.py │ │ ├── Reverse_String/ │ │ │ └── 6047198844.py │ │ ├── Reverse_Vowels_of_a_String/ │ │ │ └── 6047198844.py │ │ ├── Sort_Colors/ │ │ │ └── JeongShin.js │ │ └── Valid Palindrome/ │ │ └── 6047198844.py │ └── Union_Find/ │ ├── Friend_Circles/ │ │ └── JeongShin.js │ ├── Longest_Consecutive_Sequence/ │ │ └── JeongShin.js │ ├── Redundant_Connection/ │ │ └── JeongShin.js │ ├── Redundant_Connection_II/ │ │ └── JeongShin.js │ └── Surrounded_Regions/ │ ├── JeongShin.js │ └── eyabc.js ├── README.md ├── Tips/ │ ├── BOJ 영업자료.md │ ├── Git 깃.md │ └── Pull-Request.md ├── codility_training/ │ ├── 11st/ │ │ └── 2020/ │ │ ├── 1/ │ │ │ ├── eyabc.js │ │ │ └── junilhwang.js │ │ ├── 2/ │ │ │ └── junilhwang.js │ │ └── 3/ │ │ └── junilhwang.js │ ├── Est2020.07/ │ │ ├── 1.js │ │ ├── 2.js │ │ └── 3.js │ ├── Est2020.Exam01/ │ │ ├── README.md │ │ └── junilhwang.js │ ├── Est2020.Exam02/ │ │ ├── README.md │ │ └── junilhwang.js │ ├── Est2020.Exam03/ │ │ ├── README.md │ │ └── junilhwang.js │ ├── Est2020.Exam04/ │ │ ├── README.md │ │ └── junilhwang.js │ ├── lessons.lesson01.Iterations.BinaryGap/ │ │ ├── JeongShin.js │ │ ├── JunilHwang.java │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── pul8219.java │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson02.Arrays.CyclicRotation/ │ │ ├── JeongShin.js │ │ ├── JunilHwang.java │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── pul8219.java │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson02.Arrays.OddOccurrencesInArray/ │ │ ├── README.md │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── pul8219.java │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson03.TimeComplexity.FrogJmp/ │ │ ├── JeongShin.js │ │ ├── NowonLee.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson03.TimeComplexity.PermMissingElem/ │ │ ├── JeongShin.js │ │ ├── NowonLee.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── pul8219.java │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson03.TimeComplexity.TapeEquilibrium/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson04.CountingElements.FrogRiverOne/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson04.CountingElements.MaxCounters/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson04.CountingElements.MissingInteger/ │ │ ├── JeongShin.js │ │ ├── NowonLee.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson04.CountingElements.PermCheck/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson05.PrefixSum.GenomicRangeQuery/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sangmandu.py │ │ └── test.json │ ├── lessons.lesson05.PrefixSums.CountDiv/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson05.PrefixSums.GenomicRangeQuery/ │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── khw970421.js │ │ └── sjjyy.java │ ├── lessons.lesson05.PrefixSums.MinAvgTwoSlice/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson05.PrefixSums.PassingCars/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson06.Sorting.Distinct/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson06.Sorting.MaxProductOfThree/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson06.Sorting.NumberOfDiscIntersections/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson06.Sorting.Triangle/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── khw970421.js │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson07.StackandQueues.StoneWall/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson07.StacksandQueues.Brackets/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson07.StacksandQueues.Fish/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson07.StacksandQueues.Nesting/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── khw970421.js │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson08.Leader.Dominator/ │ │ ├── JeongShin.js │ │ ├── JunilHwang.java │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson08.Leader.EquiLeader/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── junilhwang.js │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ ├── sjjyy.java │ │ └── test.json │ ├── lessons.lesson09.MaximumSliceProblem.MaxDoubleSliceSum/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc-practice.js │ │ ├── eyabc.js │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson09.MaximumSliceProblem.MaxProfit/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── khw970421.js │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson09.MaximumSliceProblem.MaxSliceSum/ │ │ ├── JeongShin.js │ │ ├── NowonLee.js │ │ ├── eyabc.js │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/ │ │ ├── JeongShin.js │ │ ├── NowonLee.js │ │ ├── PrimeAndCompositeNumber-practice.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── khw970421.js │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson10.PrimeAndCompositeNumbers.Flags/ │ │ ├── Flag.md │ │ ├── JeongShin.js │ │ ├── eyabc.js │ │ ├── sAp00n.py │ │ └── sangmandu.py │ ├── lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle/ │ │ ├── JeongShin.js │ │ ├── NowonLee.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── khw970421.js │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson10.PrimeAndCompositeNumbers.Peaks/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── sAp00n.py │ │ ├── sangmandu.py │ │ └── sjjyy.java │ ├── lessons.lesson11.SieveofEratosthenes.CountNonDivisible/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── sAp00n.py │ │ └── sjjyy.java │ ├── lessons.lesson11.SieveofEratosthenes.CountSemiprimes/ │ │ ├── JeongShin.js │ │ ├── READMD.md │ │ ├── eyabc.js │ │ ├── sAp00n.py │ │ └── sjjyy.java │ ├── lessons.lesson12.EuclideanAlgorithm.ChocolatesByNumbers/ │ │ ├── EuclideanAlgorithm.md │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ ├── sAp00n.py │ │ └── sjjyy.java │ ├── lessons.lesson12.EuclideanAlgorithm.CommonPrimeDivisors/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── eyabc.js │ │ └── sjjyy.java │ ├── lessons.lesson13.FibonacciNumbers.FibFrog/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── sAp00n.py │ │ └── sjjyy.java │ ├── lessons.lesson13.FibonacciNumbers.Ladder/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── sAp00n.py │ │ └── sjjyy.java │ ├── lessons.lesson14.BinarySearchAlgorithm.MinMaxDivision/ │ │ ├── JeongShin.js │ │ ├── sAp00n.py │ │ └── sAp00n_pseudo.md │ ├── lessons.lesson14.BinarySearchAlgorithm.NailingPlanks/ │ │ └── JeongShin.js │ ├── lessons.lesson15.CaterpillarMethod.AbsDistinct/ │ │ ├── JeongShin.js │ │ ├── README.md │ │ ├── sAp00n.py │ │ └── sjjyy.java │ ├── lessons.lesson15.CaterpillarMethod.CountDistinctSlices/ │ │ ├── JeongShin.js │ │ ├── sAp00n.py │ │ └── sjjyy.java │ ├── lessons.lesson15.CaterpillarMethod.CountTriangles/ │ │ ├── JeongShin.js │ │ └── sjjyy.java │ ├── lessons.lesson15.CaterpillarMethod.MinAbsSumOfTwo/ │ │ ├── JeongShin.js │ │ └── sjjyy.java │ ├── lessons.lesson16.GreedyAlgorithms.MaxNonOverLappingSegments/ │ │ ├── JeongShin.js │ │ └── sjjyy.java │ ├── lessons.lesson16.GreedyAlgorithms.TieRopes/ │ │ ├── JeongShin.js │ │ └── sjjyy.java │ ├── lessons.lesson17.DynamicProgramming.MinAbsSum/ │ │ └── JeongShin.js │ ├── lessons.lesson17.DynamicProgramming.NumberSolitaire/ │ │ ├── JeongShin.js │ │ └── sjjyy.java │ ├── lessons.lesson90.TasksFromIndeedPrime2015Challenge.FloodDepth/ │ │ └── JeongShin.js │ ├── lessons.lesson90.TasksFromIndeedPrime2015Challenge.LongestPassword/ │ │ └── JeongShin.js │ ├── lessons.lesson90.TasksFromIndeedPrime2015Challenge.SlalomSkiing/ │ │ └── JeongShin.js │ ├── lessons.lesson91.TaksFromIndeedPrime2016Challenge.DwarfsRafting/ │ │ └── JeongShin.js │ ├── lessons.lesson91.TasksFromIndeedPrime2016Challenge.RectangleBuilderGreaterArea/ │ │ └── JeongShin.js │ ├── lessons.lesson91.TasksFromIndeedPrime2016Challenge.TreeProduct/ │ │ └── JeongShin.js │ ├── lessons.lesson92.TaskFromIndeedPrime2016CollegeCodersChallenge.SocksLaundering/ │ │ └── JeongShin.js │ ├── lessons.lesson92.TasksFromIndeedPrime2016.CollegeCodersChallenge.DiamondsCount/ │ │ └── JeongShin.js │ ├── lessons.lesson99.FutureTraining.ArrayInversionCount/ │ │ └── JeongShin.js │ ├── lessons.lesson99.FutureTraining.StrSymmetryPoint/ │ │ └── JeongShin.js │ └── lessons.lesson99.FutureTraining.TreeHeight/ │ └── JeongShin.js ├── package.json ├── programmers/ │ ├── socar/ │ │ └── 1.js │ ├── 난이도별/ │ │ ├── README.md │ │ ├── level.01.두개_뽑아서_더하기/ │ │ │ └── temp.py │ │ ├── level01.2016년/ │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── Siyoung-Yang.js │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── easyearn77.cpp │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── s2uyeoii.c │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.3진법_뒤집기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── develop-sell.js │ │ │ └── sangmandu.py │ │ ├── level01.K번째수/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ ├── junilhwang.py │ │ │ ├── khw970421.js │ │ │ ├── pul8219.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.[1차]_다트_게임/ │ │ │ └── 6047198844.py │ │ ├── level01.x만큼_간격이_있는_n개의_숫자/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── khw970421.js │ │ │ ├── sangmandu.py │ │ │ ├── sjjyy.java │ │ │ └── x만큼_간격_있는_n개의_숫자.py │ │ ├── level01.가운데_글자_가져오기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── eyabc.js │ │ │ ├── rockmiin.py │ │ │ ├── s2uyeoii.cpp │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.같은_숫자는_싫어/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── Siyoung-Yang.java │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk00.py │ │ │ ├── eyabc.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.나누어_떨어지는_숫자_배열/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.내적/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ └── sangmandu.py │ │ ├── level01.다트_게임/ │ │ │ ├── Go-yj.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.동물의_아이디와_이름/ │ │ │ └── 6047198844.sql │ │ ├── level01.두 정수 사이의 합/ │ │ │ └── 6047198844.py │ │ ├── level01.두_개_뽑아서_더하기/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ ├── develop-sell.js │ │ │ └── sangmandu.py │ │ ├── level01.두_정수_사이의_합/ │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.c │ │ │ ├── Jaewon0702 .py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.로또의_최고_순위와_최저_순위/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ └── sangmandu.py │ │ ├── level01.모든_레코드_조회하기/ │ │ │ └── 6047198844.sql │ │ ├── level01.모의고사/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702 .py │ │ │ ├── JeongShin.js │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.문자열_내_p와_y의_개수/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.java │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ ├── junilhwang.py │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ ├── sjjyy.java │ │ │ └── test.json │ │ ├── level01.문자열_내_마음대로_정렬하기/ │ │ │ ├── 6047198844.txt │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── sangmandu.py │ │ │ ├── sjjyy.java │ │ │ └── turquoiseluv.py │ │ ├── level01.문자열_내림차순으로_배치하기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ ├── junilhwang.py │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ ├── sjjyy.java │ │ │ └── test.json │ │ ├── level01.문자열_다루기_기본/ │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.문자열을_정수로_바꾸기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.비밀지도/ │ │ │ ├── Go-yj.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.상위_n개_레코드/ │ │ │ └── 6047198844.sql │ │ ├── level01.서울에서_김서방_찾기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.java │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.소수_만들기/ │ │ │ └── sangmandu.py │ │ ├── level01.소수찾기/ │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── dosimpact.py │ │ │ ├── eyabc.js │ │ │ ├── junilhwang-01.js │ │ │ ├── junilhwang-02.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.수박수박수박수/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── s2uyeoii.cpp │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.숫자_문자열과_영단어/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level01.시저_암호/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.신규 아이디_추천/ │ │ │ └── dosimpact.py │ │ ├── level01.신규_아이디_추천/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ └── sangmandu.py │ │ ├── level01.실패율/ │ │ │ └── sangmandu.py │ │ ├── level01.아픈_동물_찾기/ │ │ │ └── 6047198844.sql │ │ ├── level01.약수의_개수와_덧셈/ │ │ │ ├── Go-yj.py │ │ │ └── sangmandu.py │ │ ├── level01.약수의_합/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.어린_동물_찾기/ │ │ │ └── 6047198844.sql │ │ ├── level01.없는 숫자 더하기/ │ │ │ └── 6047198844.py │ │ ├── level01.여러_기준으로_정렬하기/ │ │ │ └── 6047198844.sql │ │ ├── level01.역순_정렬하기/ │ │ │ └── 6047198844.sql │ │ ├── level01.예산/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── rockmiin_예산.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.완주하지_못한_선수/ │ │ │ ├── 6047198844.cpp │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── JeongShin.js │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── junilhwang.py │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ ├── sjjyy.java │ │ │ └── test.json │ │ ├── level01.음양_더하기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ └── sangmandu.py │ │ ├── level01.이름이_있는_동물의_아이디/ │ │ │ └── 6047198844.sql │ │ ├── level01.이상한_문자_만들기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── pul8219.java │ │ │ ├── s2uyeoii.cpp │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.자릿수_더하기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.자연수_뒤집어_배열로_만들기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── s2uyeoii.cpp │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.정수_내림차순으로_배치하기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── sangmandu.py │ │ │ ├── sjjyy.java │ │ │ └── 정수_내림순으로_배치하기.py │ │ ├── level01.정수_제곱근_판별/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.제일_작은_수_제거하기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── JunilHwang.java │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.직사각혁_별찍기/ │ │ │ └── Go-yj.py │ │ ├── level01.직사각형_별찍기/ │ │ │ ├── 6047198844.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.짝수와_홀수/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.체육복/ │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.최대공약수와_최소공배수/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.콜라츠_추측/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── s2uyeoii.cpp │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.크레인_인형뽑기_게임/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ ├── sjjyy.java │ │ │ └── turquoiseluv.py │ │ ├── level01.키패드_누르기/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ ├── eyabc.js │ │ │ └── sangmandu.py │ │ ├── level01.평균_구하기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.java │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.폰켓몬/ │ │ │ └── sangmandu.py │ │ ├── level01.하샤드_수/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── s2uyeoii.cpp │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.핸드폰_번호_가리기/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── s2uyeoii.cpp │ │ │ ├── s2uyeoii_c.cpp │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level01.행렬의_덧셈/ │ │ │ ├── 6047198844.py │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── develop-sell.js │ │ │ ├── dkdlelk99.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.124_나라의_숫자/ │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── sangmandu.py │ │ │ ├── sjjyy.java │ │ │ └── turquoiseluv.py │ │ ├── level02.2개_이하로_다른_비트/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level02.H-Index/ │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ ├── khw970421.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.JadenCase_문자열_만들기/ │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ └── sangmandu.py │ │ ├── level02.N개의_최소공배수/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level02.[1차]_프렌즈4블록/ │ │ │ └── 6047198844.cpp │ │ ├── level02.[3차]_방금_그곡/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.[3차]_압축/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.[3차]파일명_정렬/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.n진수_게임/ │ │ │ ├── Go-yj.py │ │ │ └── sangmandu.py │ │ ├── level02.가장_큰_수/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Jaewon0702.py │ │ │ ├── JeongShin.js │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ ├── rockmiin_가장큰수.py │ │ │ ├── s2uyeoii.cpp │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.가장_큰_정사각형_찾기/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ └── sangmandu.py │ │ ├── level02.거리두기_확인하기/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level02.게임_맵_최단거리/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level02.고양이와_개는_몇_마리_있을까/ │ │ │ └── 6047198844.sql │ │ ├── level02.괄호_회전하기/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level02.괄호변환/ │ │ │ ├── README.md │ │ │ ├── eyabc.js │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level02.구명보트/ │ │ │ ├── 6047198844.cpp │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ ├── rockmiin_구명보트.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.기능개발/ │ │ │ ├── 6047198844.cpp │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── dkdlelk99_v2.py │ │ │ ├── eyabc.js │ │ │ ├── junilhwang.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.뉴스_클러스터링/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.다리를_지나는_트럭/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── junilhwang.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.다음_큰_숫자/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── rockmiin.py │ │ │ ├── rockmiin_다음큰숫자.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.단체사진_찍기/ │ │ │ └── 6047198844.cpp │ │ ├── level02.더_맵게/ │ │ │ ├── 6047198844.cpp │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang-01.py │ │ │ ├── junilhwang-02.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.동명_동물_수_찾기/ │ │ │ └── 6047198844.sql │ │ ├── level02.땅따먹기/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ └── sangmandu.py │ │ ├── level02.루시와_엘라_찾기/ │ │ │ └── 6047198844.sql │ │ ├── level02.멀리_뛰기/ │ │ │ └── 6047198844.py │ │ ├── level02.멀쩡한_사각형/ │ │ │ ├── 12eon.py │ │ │ ├── 6047198844.cpp │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── s2uyeoii.cpp │ │ │ └── sangmandu.py │ │ ├── level02.메뉴_리뉴얼/ │ │ │ ├── 6047198844.cpp │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level02.모음사전/ │ │ │ └── 6047198844.py │ │ ├── level02.문자열압축/ │ │ │ ├── README.md │ │ │ ├── eyabc.js │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level02.방문_길이/ │ │ │ └── 6047198844.py │ │ ├── level02.배달/ │ │ │ └── 6047198844.py │ │ ├── level02.삼각_달팽이/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.소수_만들기/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ ├── s2uyeoii.cpp │ │ │ └── sangmandu.py │ │ ├── level02.소수_찾기/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Jaewon0702.py │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level02.쇠막대기/ │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ └── junilhwang.js │ │ ├── level02.수식_최대화/ │ │ │ ├── 6047198844.cpp │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level02.순위_검색/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level02.숫자의_표현/ │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── khw970421.js │ │ │ └── sangmandu.py │ │ ├── level02.스킬트리/ │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── desktop.ini │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level02.압축/ │ │ │ └── Go-yj.py │ │ ├── level02.영어_끝말잇기/ │ │ │ ├── 6047198844.cpp │ │ │ ├── HyeonJeong.py │ │ │ ├── junilhwang.py │ │ │ └── sangmandu.py │ │ ├── level02.예상_대진표/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.오픈채팅방/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.올바른_괄호/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── JeongShin.js │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── khw970421.js │ │ │ ├── s2uyeoii.c │ │ │ └── sangmandu.py │ │ ├── level02.위장/ │ │ │ ├── 6047198844.cpp │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── JeongShin.js │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.이름에_el이_들어가는_동물_찾기/ │ │ │ └── 6047198844.sql │ │ ├── level02.이름이_없는_동물의_아이디/ │ │ │ └── 6047198844_.sql │ │ ├── level02.이진_변환_반복하기/ │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ └── sangmandu.py │ │ ├── level02.저울/ │ │ │ └── JeongShin.js │ │ ├── level02.전화번호_목록/ │ │ │ ├── 6047198844.cpp │ │ │ ├── HyeonJeong.py │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.점프와_순간이동/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.조이스틱/ │ │ │ ├── 6047198844.cpp │ │ │ ├── HyeonJeong.py │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level02.주식가격/ │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── junilhwang.js │ │ │ ├── rockmiin.py │ │ │ ├── s2uyeoii.cpp │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.짝지어_제거하기/ │ │ │ ├── 6047198844.cpp │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── eyabc.js │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.최댓값과 최솟값/ │ │ │ ├── README.md │ │ │ └── dkdlelk99.py │ │ ├── level02.최댓값과_최솟값/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── rockmiin_최댓값과최솟값.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.최솟값_만들기/ │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── rockmiin.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.최솟값만들기/ │ │ │ └── 6047198844.cpp │ │ ├── level02.카펫/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── eyabc.js │ │ │ ├── junilhwang.js │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.캐시/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.쿼드압축_후_개수_세기/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level02.큰_수_만들기/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Jaewon0702(1).py │ │ │ ├── Jaewon0702.py │ │ │ ├── JeongShin.js │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang-01.js │ │ │ ├── junilhwang-02.js │ │ │ ├── sangmandu.py │ │ │ ├── sjjyy.java │ │ │ └── turquoiseluv.py │ │ ├── level02.타겟 넘버/ │ │ │ └── rockmiin.py │ │ ├── level02.타겟_넘버/ │ │ │ ├── 6047198844.cpp │ │ │ ├── JeongShin.js │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.탑/ │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ └── rockmiin.py │ │ ├── level02.튜플/ │ │ │ ├── 6047198844.cpp │ │ │ ├── JeongShin.js │ │ │ ├── eyabc.js │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.파일명_정렬/ │ │ │ └── Go-yj.py │ │ ├── level02.폰켓몬/ │ │ │ ├── 6047198844.cpp │ │ │ ├── khw.js │ │ │ ├── sangmandu.py │ │ │ └── sjjyy.java │ │ ├── level02.프렌즈4블록/ │ │ │ └── sangmandu.py │ │ ├── level02.프린터/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Jaewon0702.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── junilhwang.js │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level02.피보나치_수/ │ │ │ ├── Go-yj.py │ │ │ ├── HyeonJeong.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level02.행렬_테두리_회전하기/ │ │ │ └── sangmandu.py │ │ ├── level02.행렬_테투리_회전하기/ │ │ │ └── 6047198844.py │ │ ├── level02.행렬의곱셈/ │ │ │ ├── 6047198844.cpp │ │ │ ├── Go-yj.py │ │ │ ├── README.md │ │ │ ├── dkdlelk99.py │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level02.후보키/ │ │ │ ├── 6047198844.cpp │ │ │ └── sangmandu.py │ │ ├── level03.110 옮기기/ │ │ │ └── sangmandu.py │ │ ├── level03.110_옮기기/ │ │ │ └── 6047198844.py │ │ ├── level03.2xn타일링/ │ │ │ ├── .vscode/ │ │ │ │ └── launch.json │ │ │ ├── 6047198844.cpp │ │ │ ├── JeongShin.js │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level03.N_Queen/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.N으로_표현/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.[1차]_셔틀버스/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.[1차]_추석_트래픽/ │ │ │ └── 6047198844.py │ │ ├── level03.가사검색/ │ │ │ ├── README.md │ │ │ └── junilhwang.js │ │ ├── level03.가장_긴_팰린드롬/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.가장_먼_노드/ │ │ │ ├── JeongShin.js │ │ │ ├── sangmandu.py │ │ │ └── turquoiseluv.py │ │ ├── level03.가장먼노드/ │ │ │ └── 6047198844.py │ │ ├── level03.거스름돈/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.경주로_건설/ │ │ │ ├── 6047198844.py │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level03.광고_삽입/ │ │ │ └── 6047198844.py │ │ ├── level03.광고_제거/ │ │ │ └── sangmandu.py │ │ ├── level03.기둥과보/ │ │ │ ├── 6047198844.py │ │ │ ├── README.md │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level03.기지국_설치/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.길_찾기_게임/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.네트워크/ │ │ │ ├── 6047198844.cpp │ │ │ ├── JeongShin.js │ │ │ ├── rockmiin_네트워크.py │ │ │ └── sangmandu.py │ │ ├── level03.다단계_칫솔_판매/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.단속카메라/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level03.단어_변환/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.등굣길/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.디스크_컨트롤러/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level03.매칭_점수/ │ │ │ └── 6047198844.py │ │ ├── level03.멀리뛰기/ │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.모두_0으로_만들기/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.방문_길이/ │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.배달/ │ │ │ └── sangmandu.py │ │ ├── level03.베스트앨범/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.보석_쇼핑/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.불량_사용자/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.java │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.블록_이동하기/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.섬_연결하기/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level03.순위/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.숫자_게임/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.스타_수열/ │ │ │ └── 6047198844.py │ │ ├── level03.스티커_모으기(2)/ │ │ │ └── 6047198844.py │ │ ├── level03.야근_지수/ │ │ │ └── khw970421.js │ │ ├── level03.야근지수/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.여행경로/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.예산/ │ │ │ └── JeongShin.js │ │ ├── level03.외벽점검/ │ │ │ ├── 6047198844.py │ │ │ ├── README.md │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level03.이중우선순위큐/ │ │ │ ├── JeongShin.js │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level03.입국심사/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level03.자물쇠와열쇠/ │ │ │ ├── 6047198844.py │ │ │ ├── README.md │ │ │ ├── junilhwang.js │ │ │ └── sangmandu.py │ │ ├── level03.저울/ │ │ │ └── JeongShin.js │ │ ├── level03.정수_삼각형/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ ├── rockmiin.py │ │ │ └── sangmandu.py │ │ ├── level03.종이접기/ │ │ │ └── JeongShin.js │ │ ├── level03.줄_서는_방법/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.징검다리_건너기/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.최고의_집합/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.카드_짝_맞추기/ │ │ │ └── 6047198844.py │ │ ├── level03.타일_장식물/ │ │ │ └── JeongShin.js │ │ ├── level03.표 편집/ │ │ │ └── sangmandu.py │ │ ├── level03.표_편집/ │ │ │ └── 6047198844.py │ │ ├── level03.풍선_터트리기/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.하노이의_탑/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.js │ │ │ └── sangmandu.py │ │ ├── level03.합승_택시_요금/ │ │ │ ├── 6047198844.py │ │ │ └── sangmandu.py │ │ ├── level03.헤비 유저가 소유한 장소/ │ │ │ └── 6047198844.sql │ │ ├── level04.가사_검색/ │ │ │ └── JeongShin.js │ │ ├── level04.단어_퍼즐/ │ │ │ └── JeongShin.js │ │ ├── level04.무지의_먹방_라이브/ │ │ │ └── JeongShin.js │ │ ├── level04.사칙연산/ │ │ │ └── sangmandu.py │ │ ├── level04.스티커_모으기/ │ │ │ └── JeongShin.js │ │ ├── level04.올바른_괄호의_갯수/ │ │ │ ├── 6047198844.py │ │ │ └── JeongShin.js │ │ ├── level04.지형_이동/ │ │ │ ├── 6047198844.py │ │ │ └── JeongShin.js │ │ ├── level04.징검다리/ │ │ │ ├── 6047198844.py │ │ │ ├── JeongShin.java │ │ │ └── JeongShin.js │ │ ├── level04.호텔_방_배정/ │ │ │ ├── JeongShin.java │ │ │ └── JeongShin.js │ │ └── remove_spacebar.py │ ├── 네이버_2020_아폴로_챌린지/ │ │ └── junilhwang/ │ │ ├── 1.js │ │ ├── 2.js │ │ ├── 3.js │ │ └── report.20200920.150349.9360.0.001.json │ ├── 부스트캠프/ │ │ ├── boost1.py │ │ ├── boost2.py │ │ ├── eyabc_1_1.js │ │ ├── eyabc_1_2.js │ │ ├── eyabc_2_1.js │ │ └── eyabc_2_2.js │ ├── 썸머코딩_2020/ │ │ └── 아름다운연도/ │ │ ├── JunilHwang.java │ │ └── pul8219.java │ ├── 쏘카/ │ │ ├── 2.js │ │ └── 3.js │ ├── 우아한캠프 2020 상반기/ │ │ ├── eyabc_01.js │ │ ├── eyabc_02.js │ │ └── eyabc_03.js │ ├── 위메프202006/ │ │ ├── 1/ │ │ │ └── eyabc.js │ │ ├── 2/ │ │ │ └── eyabc.js │ │ ├── 3/ │ │ │ └── eyabc.js │ │ └── 4/ │ │ └── eyabc.js │ ├── 위클리 챌린지/ │ │ ├── 1주차/ │ │ │ └── 6047198844.py │ │ └── 2주차/ │ │ └── 6047198844.py │ ├── 카카오 개발자 겨울 인턴십 2019/ │ │ ├── 불량사용자/ │ │ │ └── 불량사용자.py │ │ ├── 크레인 인형뽑기 게임/ │ │ │ └── 크레인 인형뽑기 게임.py │ │ └── 튜플/ │ │ └── 튜플.py │ ├── 카카오_2020_상반기_인턴_코딩테스트/ │ │ ├── README.md │ │ ├── junilhwang-01.js │ │ ├── junilhwang-02.js │ │ ├── junilhwang-03.js │ │ └── junilhwang-04.js │ ├── 카카오_2020_상반기_인턴_코딩테스트_2/ │ │ ├── 1.js │ │ ├── 2.js │ │ ├── 3.js │ │ └── 4.js │ ├── 카카오_프런트엔드_경력직_챌린지/ │ │ └── junilhwang/ │ │ ├── 1.js │ │ ├── 2.js │ │ └── 3.js │ ├── 쿠팡/ │ │ └── junilhwang/ │ │ ├── 2.js │ │ ├── 3.js │ │ └── 4.js │ ├── 토스/ │ │ ├── 1.js │ │ ├── 2.js │ │ └── 3.js │ ├── 프로그래머스_챌린지/ │ │ ├── 2020_상반기_백엔드개발자_코딩테스트.01/ │ │ │ ├── README.md │ │ │ └── junilhwang.js │ │ ├── 2020_상반기_백엔드개발자_코딩테스트.02/ │ │ │ ├── README.md │ │ │ └── junilhwang.js │ │ ├── 2020_상반기_백엔드개발자_코딩테스트.03/ │ │ │ ├── README.md │ │ │ └── junilhwang.js │ │ ├── 2020_하반기_겨울방학인턴십_코딩테스트/ │ │ │ ├── JeongShin1.js │ │ │ └── JeongShin3.js │ │ ├── README.md │ │ ├── est/ │ │ │ ├── 2.js │ │ │ └── 3.js │ │ └── 카카오_커머스/ │ │ └── junilhwang/ │ │ ├── 1.js │ │ ├── 2.js │ │ └── 3.js │ └── 학점연계인턴십_2020_하반기/ │ ├── 1.js │ ├── 2.js │ ├── 3.js │ ├── 4.js │ └── 5.js ├── 라이브러리/ │ ├── Trie.js │ ├── lowerBound.js │ ├── prefixSum.js │ └── topology.js ├── 모든경우의수/ │ ├── all.java │ ├── all.js │ └── all.py └── 알고스팟/ ├── Mismatched Brackets/ │ └── 6047198844.cpp ├── QUANTIZE/ │ └── 6047198844.cpp ├── 고대어 사전/ │ └── 6047198844.cpp ├── 너드인가, 너드가 아닌가 2/ │ └── 6047198844.cpp ├── 단어 제한 끝말잇기/ │ └── 6047198844.cpp ├── 두니발 박사의 탈옥/ │ └── 6047198844.cpp ├── 변화하는 중간 값/ │ └── 6047198844.cpp ├── 비대칭 타일링/ │ └── 6047198844.cpp ├── 삼각형 위의 최대 경로/ │ ├── 6047198844.cpp │ └── 삼각형 위의 최대 경로.py ├── 삼각형 위의 최대 경로수 세기/ │ └── 6047198844.cpp ├── 삽입 정렬 뒤집기/ │ └── 6047198844.cpp ├── 시계맞추기/ │ └── dkdlelk99.cpp ├── 와일드카드/ │ ├── 6047198844.cpp │ └── 와일드카드.py ├── 외계 신호 분석/ │ └── 6047198844.cpp ├── 외발뛰기/ │ ├── 6047198844.cpp │ └── 외발뛰기.py ├── 요새/ │ └── 6047198844.cpp ├── 울타리 잘라내기/ │ ├── 6047198844.cpp │ └── sAp00n.py ├── 울타리 잘라내기 2/ │ └── 6047198844.cpp ├── 원주율 외우기/ │ └── 6047198844.cpp ├── 장마가 찾아왔다/ │ └── 6047198844.cpp ├── 조세푸스 문제/ │ └── 6047198844.cpp ├── 최대 증가 부분 수열/ │ └── 6047198844.cpp ├── 쿼드트리/ │ ├── 6047198844.cpp │ └── sAp00n.py ├── 타일링 방법의 수 세기/ │ └── 6047198844.cpp ├── 트리 순회 순서 변경/ │ └── 6047198844.cpp ├── 팬미팅/ │ ├── 6047198844.cpp │ └── sAp00n.py ├── 폴리오미노/ │ └── 6047198844.cpp ├── 피크닉/ │ └── dkdlelk99.cpp └── 합친 LIS/ └── 6047198844.cpp ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .idea *.iml out node_modules .DS_Store ================================================ FILE: .vscode/c_cpp_properties.json ================================================ { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "windowsSdkVersion": "10.0.19041.0", "compilerPath": "D:\\tool\\x86_64-8.1.0-release-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe", "cStandard": "gnu11", "cppStandard": "gnu++14", "intelliSenseMode": "windows-gcc-x64" } ], "version": 4 } ================================================ FILE: .vscode/launch.json ================================================ { // IntelliSense를 사용하여 가능한 특성에 대해 알아보세요. // 기존 특성에 대한 설명을 보려면 가리킵니다. // 자세한 내용을 보려면 https://go.microsoft.com/fwlink/?linkid=830387을(를) 방문하세요. "version": "0.2.0", "configurations": [ { "name": "g++.exe - 활성 파일 빌드 및 디버그", "type": "cppdbg", "request": "launch", "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "D:\\tool\\x86_64-8.1.0-release-posix-seh-rt_v6-rev0\\mingw64\\bin", "environment": [], "externalConsole": false, "MIMode": "gdb", "miDebuggerPath": "D:\\tool\\x86_64-8.1.0-release-posix-seh-rt_v6-rev0\\mingw64\\bin\\gdb.exe", "setupCommands": [ { "description": "gdb에 자동 서식 지정 사용", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "C/C++: g++.exe 활성 파일 빌드" } ] } ================================================ FILE: .vscode/tasks.json ================================================ { "version": "2.0.0", "runner": "terminal", "type": "shell", "echoCommand": true, "presentation" : { "reveal": "always" }, "tasks": [ { "label": "save and compile for C++", "command": "g++", "args": [ "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "group": "build", "problemMatcher": { "fileLocation": [ "relative", "${workspaceRoot}" ], "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5 } } }, { "label": "save and compile for C", "command": "gcc", "args": [ "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "group": "build", "problemMatcher": { "fileLocation": [ "relative", "${workspaceRoot}" ], "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5 } } }, { "label": "execute", "command": "cmd", "group": "test", "args": [ "/C", "${fileDirname}\\${fileBasenameNoExtension}" ] }, { "type": "cppbuild", "label": "C/C++: g++.exe 활성 파일 빌드", "command": "D:\\tool\\x86_64-8.1.0-release-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe", "args": [ "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "D:\\tool\\x86_64-8.1.0-release-posix-seh-rt_v6-rev0\\mingw64\\bin" }, "problemMatcher": [ "$gcc" ], "group": "build", "detail": "컴파일러: D:\\tool\\x86_64-8.1.0-release-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe" }, { "type": "cppbuild", "label": "C/C++: g++.exe 활성 파일 빌드", "command": "D:\\tool\\x86_64-8.1.0-release-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe", "args": [ "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "D:\\tool\\x86_64-8.1.0-release-posix-seh-rt_v6-rev0\\mingw64\\bin" }, "problemMatcher": [ "$gcc" ], "group": "build", "detail": "컴파일러: D:\\tool\\x86_64-8.1.0-release-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe" } ] } ================================================ FILE: BOJ/1002.터렛/6047198844.cpp ================================================ #include #include using namespace std; int main() { int T; int x1, y1, r1, x2, y2, r2; long long d; cin >> T; while (T--) { cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2; d = pow(x1 - x2, 2) + pow(y1 - y2, 2); if (pow(r1 - r2,2) < d && d < pow(r1 + r2,2)) { cout << "2\n"; continue; } else if (x1 == x2 && y1 == y2 && r1 == r2) { cout << "-1\n"; continue; } else if (pow(r1 - r2,2) == d || d == pow(r1 + r2,2)) { cout << "1\n"; continue; } else { cout << "0\n"; } } } ================================================ FILE: BOJ/1002.터렛/6047198844.py ================================================ T = int(input()) for _ in range(T): x1, y1, r1, x2, y2, r2 = map(int, input().split()) d = ((x1-x2) ** 2 + (y1-y2) ** 2) ** 0.5 rd = abs(r1+r2) if r1 > r2: r1, r2 = r2, r1 if x1 == x2 and y1 == y2 and r1 == r2: print(-1) elif d == rd or r1 + d == r2: print(1) elif d > rd or r1 + d < r2: print(0) else: print(2) ================================================ FILE: BOJ/10026.적록색약/6047198844.py ================================================ import re import collections def bfs(i, j, board): color = board[i][j] board[i][j] = 'Z' Q = collections.deque() Q.append((i, j)) while Q: y, x = Q.popleft() for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny = y + dy nx = x + dx if 0 <= ny < N and 0 <= nx < N and board[ny][nx] == color: board[ny][nx] = 'Z' Q.append((ny, nx)) N = int(input()) able_board = [list(input()) for _ in range(N)] disabled_board = [list(re.sub('G', 'R', ''.join(row))) for row in able_board] able_res = 0 for y in range(N): for x in range(N): if able_board[y][x] != 'Z': bfs(y, x, able_board) able_res += 1 disabled_res = 0 for y in range(N): for x in range(N): if disabled_board[y][x] != 'Z': bfs(y, x, disabled_board) disabled_res += 1 print(able_res, disabled_res) ================================================ FILE: BOJ/10026.적록색약/rockmiin.py ================================================ from collections import deque def bfs(v): q= deque([v]) visited[v[0]][v[1]]= 1 while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+dx, y+dy if 0<= tmp_x< n and 0<= tmp_y< n and adj[x][y]==adj[tmp_x][tmp_y] and visited[tmp_x][tmp_y]==0: q.append([tmp_x, tmp_y]) visited[tmp_x][tmp_y]=1 def bfs_rg(v): q= deque([v]) visited_rg[v[0]][v[1]]= 1 while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+dx, y+dy if 0 <= tmp_x < n and 0 <= tmp_y < n and visited_rg[tmp_x][tmp_y]==0: if adj[x][y]== adj[tmp_x][tmp_y]: q.append([tmp_x, tmp_y]) visited_rg[tmp_x][tmp_y] = 1 elif adj[tmp_x][tmp_y] in rg and adj[x][y] in rg: q.append([tmp_x, tmp_y]) visited_rg[tmp_x][tmp_y] = 1 n= int(input()) rg= ['R', 'G'] adj= [] visited= [[0 for _ in range(n)] for _ in range(n)] visited_rg= [[0 for _ in range(n)] for _ in range(n)] cnt= 0 cnt_rg= 0 for i in range(n): adj.append(list(input())) # for i in adj: # print(i) # print() for i in range(n): for j in range(n): if visited[i][j]== 0: bfs([i, j]) cnt+=1 if visited_rg[i][j]== 0: bfs_rg([i, j]) cnt_rg+=1 print(cnt, cnt_rg) # 일반인의 경우에는 기존에 사용하던 BFS 방식으로 구현을 하였으며, # 색약인 사람의 경우 인접한 color가 red, green인 경우에는 같은 구역의 q로 append 해줌으로써 구현 # 예제 입력 # 5 # RRRBB # GGBBB # BBBRR # BBRRR # RRRRR # # 예제 출력 # 4 3 ================================================ FILE: BOJ/10026.적록색약/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/10026 적록색약 [풀이] 1. 동일한 작업을 2번해야 한다 => 전체 반복문을 2번 설정 => cnt도 크기가 2인 배열로 설정 => boards도 기존 board와 G또는 R중에 하나로 합쳐진 board 하나 선언 2. 상하좌우를 살피며 방문여부와 기준점과의 색 비교를 통해 cnt ''' n = int(input()) board = [input() for _ in range(n)] boards = [board, [color.replace('G', 'R') for color in board]] cnt = [0, 0] for idx in range(2): visited = [[0] * n for _ in range(n)] for y in range(n): for x in range(n): if visited[y][x]: continue stack = [(y, x)] cnt[idx] += 1 while stack: b, a = stack.pop() for db, da in [(1, 0), (-1, 0), (0, 1), (0, -1)]: nb, na = b+db, a+da if 0 <= nb < n and 0 <= na < n: if not visited[nb][na] and boards[idx][nb][na] == boards[idx][b][a]: visited[nb][na] = 1 stack.append((nb, na)) print(*cnt) ================================================ FILE: BOJ/10026.적록색약/적록색약_10026.py ================================================ from collections import deque def bfs(v): q= deque([v]) visited[v[0]][v[1]]= 1 while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+dx, y+dy if 0<= tmp_x< n and 0<= tmp_y< n and adj[x][y]==adj[tmp_x][tmp_y] and visited[tmp_x][tmp_y]==0: q.append([tmp_x, tmp_y]) visited[tmp_x][tmp_y]=1 def bfs_rg(v): q= deque([v]) visited_rg[v[0]][v[1]]= 1 while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+dx, y+dy if 0 <= tmp_x < n and 0 <= tmp_y < n and visited_rg[tmp_x][tmp_y]==0: if adj[x][y]== adj[tmp_x][tmp_y]: q.append([tmp_x, tmp_y]) visited_rg[tmp_x][tmp_y] = 1 elif adj[tmp_x][tmp_y] in rg and adj[x][y] in rg: q.append([tmp_x, tmp_y]) visited_rg[tmp_x][tmp_y] = 1 n= int(input()) rg= ['R', 'G'] adj= [] visited= [[0 for _ in range(n)] for _ in range(n)] visited_rg= [[0 for _ in range(n)] for _ in range(n)] cnt= 0 cnt_rg= 0 for i in range(n): adj.append(list(input())) # for i in adj: # print(i) # print() for i in range(n): for j in range(n): if visited[i][j]== 0: bfs([i, j]) cnt+=1 if visited_rg[i][j]== 0: bfs_rg([i, j]) cnt_rg+=1 print(cnt, cnt_rg) # 일반인의 경우에는 기존에 사용하던 BFS 방식으로 구현을 하였으며, # 색약인 사람의 경우 인접한 color가 red, green인 경우에는 같은 구역의 q로 append 해줌으로써 구현 # 예제 입력 # 5 # RRRBB # GGBBB # BBBRR # BBRRR # RRRRR # # 예제 출력 # 4 3 ================================================ FILE: BOJ/10039.평균 점수/6047198844.py ================================================ import sys res = 0 scores = [int(sys.stdin.readline()) for _ in range(5)] for score in scores: res += 40 if score < 40 else score print(res//5) ================================================ FILE: BOJ/1005.ACM Craft/6047198844.py ================================================ import heapq import math import sys from collections import defaultdict, deque T = int(sys.stdin.readline()) for _ in range(T): N, K = map(int, sys.stdin.readline().split()) D = [0] + list(map(lambda i: -int(i), sys.stdin.readline().split())) # edge 를 반대로. edges = defaultdict(list) for _ in range(K): X, Y = map(int, sys.stdin.readline().split()) edges[Y].append(X) # 거리를 음수로. dist = [math.inf for _ in range(N + 1)] Q = deque([]) W = int(sys.stdin.readline()) # 시작점이 시작점으로 부터 가장 최소거리이다. Q.append((D[W], W)) # heapq.heappush(Q, (D[W], W)) dist[W] = D[W] while Q: # V 까지 오는데 최소 비용. # C, V = heapq.heappop(Q) C, V = Q.popleft() # 이미 최소비용이 갱신됨. if dist[V] < C: continue # 최소비용을 가지고 갱신을 해보자. for U in edges[V]: # C 는 V까지오는데 최소비용. D[U] 는 U까지 가는 간선의 가중치. # 따라서 그 합은 출발점에서 U 까지 가는 비용이다. if dist[U] > C + D[U]: dist[U] = dist[V] + D[U] Q.append((dist[U], U)) print(-min(dist)) ================================================ FILE: BOJ/1009.분산처리/6047198844.cpp ================================================ #include #include #include using namespace std; int com_num(int a, int b) { bool check[11]; vector vt; memset(check, false, sizeof(check)); int res = 1; for (int i = 0; i < 9; i++) { res *= a; res %= 10; if (check[res]) { int size = vt.size(); if (b % size) return vt[b % size - 1]; else return vt[size - 1]; } check[res] = true; vt.push_back(res); } } int main() { int T; cin >> T; int a, b; int res; while (T--) { cin >> a >> b; res = com_num(a, b); if (res) cout << res; else cout << 10; cout << "\n"; } } ================================================ FILE: BOJ/1010.다리 놓기/6047198844.cpp ================================================ #include #include using namespace std; //̾ƾϴ : n / ü : c int memo[31][31]; int combi(int n, int c) { int& res = memo[n][c]; if (res) return res; if (n==0 || n == c) return res = 1; return res = combi(n - 1, c - 1) + combi(n, c - 1); } int main() { int T; cin >> T; while (T--) { int n, c; cin >> n >> c; cout << combi(n, c) << "\n"; } } ================================================ FILE: BOJ/10101.삼각형 외우기/6047198844.py ================================================ A = int(input()) B = int(input()) C = int(input()) if A == B == C == 60: print('Equilateral') elif A + B + C == 180: if (A == B) or (B == C) or (A == C): print('Isosceles') else: print('Scalene') else: print('Error') ================================================ FILE: BOJ/10103.주사위 게임/6047198844.py ================================================ N = int(input()) x = 100 y = 100 for _ in range(N): a, b = map(int, input().split()) if a > b: y -= a elif a < b: x -= b print(x) print(y) ================================================ FILE: BOJ/1011.Fly me to the Alpha Centauri/6047198844.cpp ================================================ #include using namespace std; #define fastio cin.sync_with_stdio(false); cin.tie(nullptr) /* => 이전 단계에서 k광년 이동시 k-1 , k , k + 1 , 즉 처음엔 -1 , 0 , 1 => 도착 지점 바로 직전의 거리는 1광년 거리 이동거리 공간 이동장치 이동 횟수 1 1 1 2 11 2 3 111 3 4 121 3 5 1211 4 6 1221 4 7 12211 5 8 12221 5 9 12321 5 10 123211 6 11 123221 6 12 123321 6 13 1233211 7 14 1233221 7 15 1233321 7 16 1234321 7 17 12343211 8 18 12343221 8 ... 이동횟수 개수 누적합 1 1 1 2 1 2 3 2 4 4 2 6 5 3 9 6 3 12 7 4 16 8 4 20 9 5 25 10 5 30 개수의 쌍을 한묶음으로 보았을때 n(n+1)은 두번째 값의 뒤경계값이 됩니다. 이전쌍의 두번째 값의 뒤에 있는 누적합 + 1이 됩니다. = n^2-n+1 따라서 n에 따른 경계는 다음과 같습니다. n^2-n+1 <= <= n^2+n 2를 대입해보면 2개를 가지고 있는 이동횟수 3과 4의 경계를 구할수있습니다. 3 <= <= 6 3를 대입해보면 3개를 가지고 있는 이동횟수 5과 6의 경계를 구할수있습니다. 7 <= <= 12 즉 만든 경계식에 n을 1부터 증가시키면서 주어진 거리에 포함되는지 여부를 판단하고 해당 경계에서 또 세분화된 경계를 구할수있습니다. n^2-n+1 <= <= n^2 은 첫번째 값의 경계일것이고, n^2+1 <= <= n^2+n은 두번째 값의 경계일것입니다. 큰 범위를 구하고 세부 범위에 속하는지 판단하면 됩니다. 제곱에 있어서 범위를 조심해야겠습니다. */ int range(int distance) { //distance의 범위는 1~2^31-1 입니다. //distance가 2^31-1때 범위구하는 연산에서 overflow를 주의해야할것입니다. long long N = 0; long long begin; long long end; long long powN; while (1) { N++; long long powN = N * N; begin = powN - N + 1; end = powN + N; if (begin <= distance && distance <= end) { begin = powN + 1; //뒤에 위치하는 경우 if (begin <= distance && distance <= end) return N << 1; //앞에 위치하는 경우 else return (N << 1) - 1; } } } int main() { fastio; int _; cin >> _; int x, y; while (_--) { cin >> x >> y; cout << range(y - x) << "\n"; } } ================================================ FILE: BOJ/1012.유기농 배추/6047198844.cpp ================================================ #include #include using namespace std; //상 하 좌 우 int dy[4] = { -1,+1, 0, 0 }; int dx[4] = { 0, 0,-1,+1 }; void dfs(int x,int y, int xSize, int ySize , vector> &arr) { --arr[y][x]; int y_size = arr.size(); int x_size = arr[0].size(); for (int d = 0; d < 4; d++) { int y_ = y + dy[d]; int x_ = x + dx[d]; if ((0 <= y_ && y_ < y_size) && (0 <= x_ && x_ < x_size) && arr[y_][x_]) dfs(x_, y_, xSize, ySize, arr); } return; } int dfs_all(vector> &arr) { int res = 0; int ySize = arr.size(); int xSize = arr[0].size(); for (int y = 0; y < ySize; y++) for (int x = 0; x < xSize; x++) if (arr[y][x]) { dfs(x, y, xSize, ySize, arr); res++; } return res; } int main() { int C; cin >> C; while (C--) { int M, N; cin >> M >> N; vector> arr(N, vector(M, 0)); int K; cin >> K; int x, y; while (K--) { cin >> x >> y; arr[y][x] = 1; } cout << dfs_all(arr) << "\n"; } } ================================================ FILE: BOJ/10156.과자/6047198844.py ================================================ import sys K, N, M = map(int, sys.stdin.readline().split()) print(max(0, K * N - M)) ================================================ FILE: BOJ/10159.저울/6047198844.cpp ================================================ #include #include #include #include #define INF INT_MAX using namespace std; void floyd(vector < vector > &vt,int N){ for (int k = 1; k <= N; k++) { for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if (i != j && vt[i][k] != INF && vt[k][j] != INF) { vt[i][j] = 1; } } } } } int main() { int N; cin >> N; vector < vector > vt(N + 1, vector(N + 1, INF)); for (int i = 1; i <= N; i++) vt[i][i] = 0; int M; cin >> M; int i, j; while (M--) { cin >> i >> j; vt[i][j] = 1; } floyd(vt, N); for (int i = 1; i <= N; i++) { int res = 0; for (int j = 1; j <= N; j++) { if (vt[i][j] == INF&& vt[j][i] == INF) { res++; } } cout << res << "\n"; } } ================================================ FILE: BOJ/1016.제곱 ㄴㄴ 수/6047198844.py ================================================ import sys min_num, max_num = map(int, sys.stdin.readline().split()) squared_range = max_num - min_num + 1 sieve = [False] * squared_range i = 2 while i ** 2 <= max_num: # 최소 root num 을 찾는다. root_num = min_num // (i ** 2) if min_num % (i ** 2) != 0: root_num += 1 # root num 을 증가시키면서 체로 거른다. while root_num * (i ** 2) <= max_num: if not sieve[root_num * (i ** 2) - min_num]: sieve[root_num * (i ** 2) - min_num] = True squared_range -= 1 root_num += 1 i += 1 print(squared_range) ================================================ FILE: BOJ/10162.전자레인지/6047198844.py ================================================ T = int(input()) if T % 10 != 0: print(-1) else: A = B = C = 0 A = T // 300 B = (T % 300) // 60 C = (T % 300) % 60 // 10 print(A, B, C) ================================================ FILE: BOJ/10170.NFC West vs North/6047198844.py ================================================ print('NFC West W L T') print('-----------------------') print('Seattle 13 3 0') print('San Francisco 12 4 0') print('Arizona 10 6 0') print('St. Louis 7 9 0') print() print('NFC North W L T') print('-----------------------') print('Green Bay 8 7 1') print('Chicago 8 8 0') print('Detroit 7 9 0') print('Minnesota 5 10 1') ================================================ FILE: BOJ/1018.체스판 다시 칠하기/6047198844.cpp ================================================ /* 문제 지민이는 자신의 저택에서 MN개의 단위 정사각형으로 나누어져 있는 M*N 크기의 보드를 찾았다. 어떤 정사각형은 검은색으로 칠해져 있고, 나머지는 흰색으로 칠해져 있다. 지민이는 이 보드를 잘라서 8*8 크기의 체스판으로 만들려고 한다. 체스판은 검은색과 흰색이 번갈아서 칠해져 있어야 한다. 구체적으로, 각 칸이 검은색과 흰색 중 하나로 색칠되어 있고, 변을 공유하는 두 개의 사각형은 다른 색으로 칠해져 있어야 한다. 따라서 이 정의를 따르면 체스판을 색칠하는 경우는 두 가지뿐이다. 하나는 맨 왼쪽 위 칸이 흰색인 경우, 하나는 검은색인 경우이다. 보드가 체스판처럼 칠해져 있다는 보장이 없어서, 지민이는 8*8 크기의 체스판으로 잘라낸 후에 몇 개의 정사각형을 다시 칠해야겠다고 생각했다. 당연히 8*8 크기는 아무데서나 골라도 된다. 지민이가 다시 칠해야 하는 정사각형의 최소 개수를 구하는 프로그램을 작성하시오. 입력 첫째 줄에 N과 M이 주어진다. N과 M은 8보다 크거나 같고, 50보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에는 보드의 각 행의 상태가 주어진다. B는 검은색이며, W는 흰색이다. 출력 첫째 줄에 지민이가 다시 칠해야 하는 정사각형 개수의 최솟값을 출력한다. */ #include #include using namespace std; char board[50][50]; int N; int M; int brute_force(int y, int x,bool flag) { int res = 0; //black 이면 false, white면 true for (int dy = 0; dy < 8; dy++) { for (int dx = 0; dx < 8; dx++) { if (flag) { if (board[y + dy][x + dx] != 'W') res++; } else { if (board[y + dy][x + dx] != 'B') res++; } flag = !flag; } flag = !flag; } if(flag) res = min(res, brute_force(y, x, false)); return res; } int main() { cin >> N >> M; for (int y = 0; y < N; y++) for (int x = 0; x < M; x++) cin >> board[y][x]; int res = 100000; for (int y = 0; y + 7 < N; y++) for (int x = 0; x + 7 < M; x++) res = min(res,brute_force(y,x,true)); cout << res; } ================================================ FILE: BOJ/1019.책 페이지/6047198844.py ================================================ page = int(input()) res = [0 for i in range(10)] point = 1 while page != 0: while page % 10 != 9: for i in str(page): res[int(i)] += point page -= 1 if page < 10: for i in range(page + 1): res[i] += point res[0] -= point break else: for i in range(10): res[i] += (page // 10 + 1) * point res[0] -= point point *= 10 page //= 10 for i in res: print(i, end=' ') ================================================ FILE: BOJ/1021.회전하는 큐/6047198844.cpp ================================================ #include #include #include #include using namespace std; int second(int n, deque &dq) { int res = 0; while (dq.front()!=n) { res++; dq.push_back(dq.front()); dq.pop_front(); } dq.pop_front(); return res; } int third(int n, deque &dq) { int res = 0; while (dq.front()!=n) { res++; dq.push_front(dq.back()); dq.pop_back(); } dq.pop_front(); return res; } int main() { queue q; deque dq; int N; cin >> N; for (int i = 1; i <= N; i++) { dq.push_back(i); } int M; cin >> M; for (int i = 0; i < M; i++) { int _; cin >> _; q.push(_); } int res = 0; while (!q.empty()) { deque sq = dq; deque tq = dq; int i = second(q.front(), sq); int j = third(q.front(), tq); if (i > j) { dq = tq; res += j; } else { dq = sq; res += i; } q.pop(); } cout << res; } ================================================ FILE: BOJ/1025.제곱수 찾기/6047198844.py ================================================ from itertools import product N, M = map(int, input().split()) table = [list(input()) for _ in range(N)] square = set(root ** 2 for root in range(0, 31622 + 1)) ans = -1 for y in range(N): for x in range(M): for dy, dx in product(range(-8, 8 + 1), repeat=2): num = '' ny, nx = y, x if dy == 0 and dx == 0: continue while 0 <= ny < N and 0 <= nx < M: num += table[ny][nx] ny += dy nx += dx if int(num) in square: ans = max(ans, int(num)) print(ans) ================================================ FILE: BOJ/1027.고층 건물/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/1027 고층 건물 [풀이] 1. 빌딩은 기본적으로 양 옆 건물을 반드시 볼 수 있다 => 따라서 기본적으로 2의 카운트를 가지고 시작 => 양쪽 끝 건물은 1의 카운트를 가지고 시작 => 만약 n=1 이라면 0을 출력 2. 탐색은 왼쪽과 오른쪽 방향으로 2만큼부터 시작 => 양옆 건물은 반드시 볼 수 있기때문 3. 탐색 시작시 기준이 되는 기울기는 이웃한 빌딩과의 기울기로 설정 4. 오른쪽 기준, 기울기가 이전에 나온 최대기울기보다 커야 볼 수있음 5. 왼쪽 기준, 기울기가 이전에 나온 최소기울기보다 작아야 볼 수 있음 => 4번과 5번을 통일해주기 위해 왼쪽일 때는 -1을 곱해준다 => 따라서 똑같이 최대로 비교해줄 수 있음 ''' n = int(input()) lst = list(map(int, input().split())) cnt = [1] + [2] * (n-2) + [1] for src in range(n): for i, drt in enumerate([range(src-2, -1, -1), range(src+2, n, 1)]): sign = 2*i-1 if not drt: continue max_grad = -(lst[src]-lst[src+sign]) for dst in drt: if max_grad < sign * (lst[src]-lst[dst])/(src-dst): max_grad = sign * (lst[src]-lst[dst])/(src-dst) cnt[src] += 1 print(max(cnt) if n > 1 else 0) ================================================ FILE: BOJ/10282.해킹/6047198844.py ================================================ # 현시점 import heapq import sys from collections import defaultdict T = int(sys.stdin.readline()) for _ in range(T): # 컴퓨터 대수 / 의존성 개수 / 해킹당한 컴퓨터 번호 n, d, c = map(int, sys.stdin.readline().split()) edges = defaultdict(list) for __ in range(d): # b가 감염시 s초 후에 a가 감염된다. a, b, s = map(int, sys.stdin.readline().split()) edges[b].append((s, a)) PQ = [] for s, pc in edges[c]: heapq.heappush(PQ, (s, pc)) # 현재 시각 cur = 0 hacked_pc_num = 1 visited_pc = set() visited_pc.add(c) while PQ: s, hacked_pc = heapq.heappop(PQ) if hacked_pc in visited_pc: continue hacked_pc_num += 1 cur = s visited_pc.add(hacked_pc) for s, pc in edges[hacked_pc]: heapq.heappush(PQ, (s + cur, pc)) print(hacked_pc_num, cur) ================================================ FILE: BOJ/1030.프렉탈 평면/sAp00n.py ================================================ from sys import stdin def recursion_fractal(s, N, K, last_result): # base case 01 if last_result == 0: plane = [[0] * N for _ in range(N)] mid_idx = N // 2 mid_idx -= K // 2 for j in range(K): plane[mid_idx + j][mid_idx:mid_idx + K] = [1] * K # base case 02 elif last_result == 1: plane = [[1] * N for _ in range(N)] if s == 1: return plane return_plane = [[0]*N for _ in range(N)] for i in range(N): for j in range(N): return_plane[j] = recursion_fractal(s - 1, N, K, plane[i][j]) print(return_plane) return plane # [C1,R1] ~ [C2,R2] s, N, K, R_1, R_2, C_1, C_2 = map(int, stdin.readline().split()) fractal_plane = [0] * pow(N, s) return_mat = recursion_fractal(s, N, K, 0) for row in return_mat: print(row) ================================================ FILE: BOJ/1032.명령 프롬프트/6047198844.cpp ================================================ #include #include #include using namespace std; int main() { int N; cin >> N; vector vt; string temp; while (N--) { cin >> temp; vt.push_back(temp); } int size = vt[0].size(); string res; //O(n^2) n 50 bool flag = true; for (int idx = 0; idx < size; idx++) { flag = true; for (string s : vt) { if (s[idx] != vt[0][idx]) { flag = false; res.push_back('?'); break; } } if (flag) res.push_back(vt[0][idx]); } cout << res; } ================================================ FILE: BOJ/1037.약수/6047198844.cpp ================================================ #include #include #include using namespace std; int main() { int N; cin >> N; vector arr(N); for (int i = 0; i < N; i++) cin >> arr[i]; sort(arr.begin(), arr.end()); cout << arr.front() * arr.back(); } ================================================ FILE: BOJ/1038.감소하는 수/6047198844.py ================================================ import sys from itertools import combinations N = int(sys.stdin.readline()) arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numbers = [] for i in range(1, 10 + 1): for j in combinations(arr, i): numbers.append(int(''.join(list(map(str,j)))[::-1])) numbers.sort() if N >= len(numbers): print(-1) else: print(numbers[N]) ================================================ FILE: BOJ/1043.거짓말/6047198844.py ================================================ # 문제 # 진실을 아는 사람이 있을때는 거짓말을 못한다. # 거짓말을 들었던 사람이 있을때는 거짓말을 못한다. # 거짓말을 할 수 있는 파티 개수의 최댓값을 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 사람의 수 N과 파티의 수 M이 주어진다. # 둘째 줄에는 이야기의 진실을 아는 사람의 수와 번호가 주어진다. 진실을 아는 사람의 수가 먼저 주어지고 그 개수만큼 사람들의 번호가 주어진다. 사람들의 번호는 1부터 N까지의 수로 주어진다. # 셋째 줄부터 M개의 줄에는 각 파티마다 오는 사람의 수와 번호가 같은 방식으로 주어진다. # # N, M은 50 이하의 자연수이고, 진실을 아는 사람의 수는 0 이상 50 이하의 정수, 각 파티마다 오는 사람의 수는 1 이상 50 이하의 정수이다. # # 출력 # 첫째 줄에 문제의 정답을 출력한다. # 루트를 찾는다. def find(n): # 자신이 루트인가 if P[n] < 0: # 자신을 반환한다. return n # 자기 부모로 이동, 루트를 찾는다. P[n] = find(P[n]) return P[n] # a와 b를 합친다. def union(a, b): ra = find(a) rb = find(b) # 루트가 같은지 확인한다. if ra == rb: return # rb의 부모가 ra가 된다. -> rb의 루트가 ra가 된다. P[rb] = ra # N : 사람의 수 M : 파티의 수 # 1 <= N, M <= 50 # 입력 N, M = map(int, input().split()) _, *known_people = map(int, input().split()) parties = [] for _ in range(M): _, *party = map(int, input().split()) parties.append(party) P = [-1 for _ in range(N + 2)] # union. 같은 파티에 있다면, 같은 소속이다. 같은 소속은 같이 진실을 알거나, 같이 진실을 몰라야한다. # 소속 : 진실을 아는 사람의 집합 / 진실을 알수없는 사람들의 집합 for i in range(len(parties)): # 각 파티마다 오는 사람의 수는 1 이상 50 이하의 정수이다. root = find(parties[i][0]) for j in range(1, len(parties[i])): union(root, parties[i][j]) # find. # 현재 파티에 참가한사람이 진실을 아는 사람의 집합에 속해 있는지 확인한다. # 속해 있다면 거짓말을 칠수없다. res = 0 for i in range(len(parties)): # 한명이라도 진실을 알면 True, 모두 진실을 모르면 False flag = False for j in range(len(parties[i])): for known_person in known_people: # 루트가 같다면, 같은 집합 소속이다. if find(parties[i][j]) == find(known_person): flag = True break if flag: break if not flag: res += 1 print(res) ================================================ FILE: BOJ/10448.유레카 이론/6047198844.py ================================================ # 문제 # 자연수 n에 대해 n ≥ 1의 삼각수 Tn는 명백한 공식이 있다. # Tn = 1 + 2 + 3 + ... + n = n(n+1)/2 # 1796년, 가우스는 모든 자연수가 최대 3개의 삼각수의 합으로 표현될 수 있다고 증명하였다. 예를 들어, # # 4 = T1 + T2 # 5 = T1 + T1 + T2 # 6 = T2 + T2 or 6 = T3 # 10 = T1 + T2 + T3 or 10 = T4 # 이 결과는 증명을 기념하기 위해 그의 다이어리에 “Eureka! num = Δ + Δ + Δ” 라고 적은것에서 유레카 이론으로 알려졌다. # 꿍은 몇몇 자연수가 정확히 3개의 삼각수의 합으로 표현될 수 있는지 궁금해졌다. 위의 예시에서, 5와 10은 정확히 3개의 삼각수의 합으로 표현될 수 있지만 4와 6은 그렇지 않다. # # 자연수가 주어졌을 때, 그 정수가 정확히 3개의 삼각수의 합으로 표현될 수 있는지 없는지를 판단해주는 프로그램을 만들어라. 단, 3개의 삼각수가 모두 달라야 할 필요는 없다. # # 입력 # 프로그램은 표준입력을 사용한다. 테스트케이스의 개수는 입력의 첫 번째 줄에 주어진다. 각 테스트케이스는 한 줄에 자연수 K (3 ≤ K ≤ 1,000)가 하나씩 포함되어있는 T개의 라인으로 구성되어있다. # # 출력 # 프로그램은 표준출력을 사용한다. 각 테스트케이스에대해 정확히 한 라인을 출력한다. 만약 K가 정확히 3개의 삼각수의 합으로 표현될수 있다면 1을, 그렇지 않다면 0을 출력한다. import sys from itertools import combinations_with_replacement nums = [n * (n + 1) // 2 for n in range(1, 44 + 1)] T = int(sys.stdin.readline().rstrip()) for _ in range(T): K = int(sys.stdin.readline().rstrip()) for combi in combinations_with_replacement(nums, 3): if sum(combi) == K: print(1) break else: print(0) ================================================ FILE: BOJ/10451.순열 사이클/rockmiin.py ================================================ ================================================ FILE: BOJ/1051.숫자 정사각형/6047198844.py ================================================ N, M = map(int, input().split()) arr = [list(input()) for _ in range(N)] max_width = min(N, M) def get_square(max_width): for width in range(max_width, 0, -1): for y in range(N - width + 1): for x in range(M - width + 1): # 좌상 / 우상 / 좌하 / 우하 left_top = arr[y][x] right_top = arr[y][x + width - 1] left_bottom = arr[y + width - 1][x] right_bottom = arr[y + width - 1][x + width - 1] if left_top == right_top == left_bottom == right_bottom: return width * width return 1 print(get_square(max_width)) ================================================ FILE: BOJ/1051.숫자 정사각형/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/1051 숫자 정사각형 [풀이] 1. 가장 큰 정사각형을 찾는것이 목표이므로 큰 변부터 작아지는 방향으로 찾는다 => 이 때 큰 변은 가로, 세로 두 개의 길이 중 최솟값이다 2. 계산을 편하게 하기 위해 min(n, m)-1을 edge로 지정 => -1을 하지 않으면 이후 코드의 모든 edge에 -1 을 해줘야 함 => 나중에 다시 edge+1로 복귀 3. 반복문으로 각 꼭지점 비교 => 같다면 바로 edge 출력 => 다르면 edge 값 1 감소 => 못찾았다면 크기가 1인 정사각형이므로 1 출력 ''' n, m = map(int, input().split()) edge = min(n, m)-1 board = [input() for _ in range(n)] while edge > 0: for y in range(n-edge): for x in range(m-edge): if board[y][x] == board[y+edge][x] == board[y][x+edge] == board[y+edge][x+edge]: print((edge+1)**2) exit() edge -= 1 print(1) ================================================ FILE: BOJ/10546.배부른 마라토너/6047198844.py ================================================ # 문제 # ㅂㅐㄱ준 마라톤 대회에 참가해 놓고 완주하지 못한 배부른 참가자 한 명은 누굴까? # # 입력 # 첫째 줄에는 참가자 수 N이 주어진다. (1 ≤ N ≤ 10^5) # N개의 줄에는 참가자의 이름이 주어진다. # 추가적으로 주어지는 N-1개의 줄에는 완주한 참가자의 이름이 쓰여져 있다. # 참가자들의 이름은 길이가 1보다 크거나 같고, 20보다 작거나 같은 문자열이고, 알파벳 소문자로만 이루어져 있다. # 참가자들 중엔 동명이인이 있을 수도 있다. # # 출력 # 마라톤을 완주하지 못한 참가자의 이름을 출력한다. import sys from collections import Counter N = int(input()) players = [sys.stdin.readline().rstrip() for _ in range(N + N - 1)] for player, count in Counter(players).items(): if count % 2 == 1: print(player) break ================================================ FILE: BOJ/1058.친구/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/1058 친구 [풀이] 1. 현재 상태가 친구인지 아닌지를 나타내는 friends 선언 2. 현재 2-친구인지 아닌지를 나타내는 board 선언 => 처음에는 모든 원소가 초기값 0을 가진다. 3. friends 를 확인해 친구라면 1을 할당 => 친구가 아니라면, 나와 친구인 친구가 그와도 친구인지 확인하고 친구라면 1을 할당 => 친구가 아니라면 : board[y][x] == "N" => 나외 친구인 친구가 : board[y][z] == "Y" => 그와도 친구인지 : board[x][z] == "y" 4. 각 y축마다 2-친구 값을 모두 합친 값 중 최대를 출력 ''' n = int(input()) friends = [input() for _ in range(n)] board = [[0] * n for _ in range(n)] for y in range(n): for x in range(y+1, n): if friends[y][x] == "Y": board[y][x] = board[x][y] = 1 continue for z in range(n): if friends[y][z] == friends[x][z] == "Y": board[y][x] = board[x][y] = 1 break print(max([sum(b) for b in board])) ================================================ FILE: BOJ/10610.30/6047198844.cpp ================================================ #include #include using namespace std; int s, k, n[10]; int main() { while (~scanf("%1d", &k)) n[k]++, s += k; if (s % 3 || !n[0]) printf("-1"); else for (int i = 9; i >= 0; i--) while (n[i]--) printf("%d", i); } ================================================ FILE: BOJ/1062.가르침/6047198844.py ================================================ import re def count_bit(n): return n % 2 + count_bit(n // 2) if n >= 2 else n N, K = map(int, input().split()) words = [set(re.findall(r'[^acnit]',input())) for _ in range(N)] union_words = set() for word in words: union_words |= word if K < 5: print(0) exit() K = K - 5 word_n = len(union_words) union_words = list(union_words) #K는 최대로 배울수있는 단어수이다. 만약에 배워야하는 단어의수가 K보다 같거나 작으면 모든 단어를 배울수있다는뜻이다. if K >= word_n: print(len(words)) exit() #최대로 배울수있는 단어의 수만큼 배운다. res = 0 for i in range(1 << word_n): if count_bit(i) == K: choosen_alpha = set() for j in range(word_n): if i & 1 << j: choosen_alpha.add(union_words[j]) cnt = 0 for word in words: if word == word & choosen_alpha: cnt += 1 res = max(res, cnt) print(res) ================================================ FILE: BOJ/1068.트리/6047198844.py ================================================ N = int(input()) parents = list(map(int, input().split())) edges = [[] for _ in range(N)] for j in range(N): # j의 부모는 i 이다. i = parents[j] if i != -1: # 부모 -> 자식 edges[i].append(j) else: root = j def dfs(V): global res visited.add(V) cnt = 0 # 방문할곳 있으면 방문 for W in edges[V]: if W not in visited: cnt += 1 dfs(W) # 방문을 하지 않았다면 리프노드 if cnt == 0: res += 1 # 삭제 노드 di = int(input()) res = 0 # 루트 삭제의 경우 예외 if root != di: visited = set() visited.add(di) dfs(root) print(res) ================================================ FILE: BOJ/1068.트리/sAp00n.py ================================================ from sys import stdin def dfs(root): global cnt isTrue = False visit[root] = 1 for i in range(n): if connection_list[root][i] == 1 and visit[i] == 0: isTrue = True dfs(i) if not isTrue: cnt += 1 n = int(stdin.readline()) input_list = list(map(int, stdin.readline().split())) delete_node = int(stdin.readline()) connection_list = [[0] * n for i in range(n)] visit = [0] * n list_len = len(input_list) cnt = 0 for i in range(list_len): if input_list[i] != -1: connection_list[i][input_list[i]] = 1 connection_list[input_list[i]][i] = 1 else: root = i # print(connection_list) for i in range(n): connection_list[delete_node][i] = 0 connection_list[i][delete_node] = 0 # print(connection_list) dfs(root) if delete_node == root: print(0) else: print(cnt) ''' 5 -1 0 0 1 1 2 ''' ================================================ FILE: BOJ/1068.트리/sAp00n_BFS.py ================================================ from sys import stdin from collections import deque def BFS(connection_list, n): leaf_node_num = 0 stack = deque() visit = {} stack.append(0) while len(stack) > 0: temp = stack.popleft() for i in range(n): if connection_list[temp][i] == 1: connection_list[i][temp] = 0 # print(f'temp : {temp}') visit[temp] = None if 1 not in connection_list[temp]: leaf_node_num += 1 else: for i in range(len(connection_list[temp])): if connection_list[temp][i] == 1 and i not in visit: stack.append(i) # print(stack) return leaf_node_num def solution(n, input_list, del_node): if del_node == 0: return 0 connection_list = [[0] * n for _ in range(n)] visit = [0] * n for i in range(n): if input_list[i] == -1: pass else: connection_list[input_list[i]][i] = 1 connection_list[i][input_list[i]] = 1 for i in range(n): if connection_list[del_node][i] == 1: connection_list[del_node][i] = 0 connection_list[i][del_node] = 0 # print(f'connection_list: {connection_list}') leaf_num = BFS(connection_list, n) return leaf_num n = int(stdin.readline()) input_list = list(map(int, stdin.readline().split())) del_node = int(stdin.readline()) print(solution(n, input_list, del_node)) ================================================ FILE: BOJ/1069.DNA/6047198844.py ================================================ from collections import Counter N, M = map(int, input().split()) arr = [input() for _ in range(N)] res_dna = '' for i in list(zip(*arr)): k = Counter(i).items() res_dna += sorted(k, key=lambda i:(-i[1], i[0]))[0][0] res_diff = 0 for i in arr: for j in range(M): if i[j] != res_dna[j]: res_diff += 1 print(res_dna) print(res_diff) ================================================ FILE: BOJ/10711.모래성/6047198844.py ================================================ # 문제 # 그가 만든 모래성을 2차원 격자단위로 만들었으며, 각 격자마다 튼튼함의 정도를 다르게 해서 성을 만들었다. # 1부터 9 사이의 숫자로 표현될 수 있다. # 자기 격자 주변의 8방향 (위 아래 왼쪽 오른쪽, 그리고 대각선) 을 봐서 모래성이 쌓여있지 않은 부분의 개수가 자기 모래성의 튼튼함보다 많거나 같은 경우 파도에 의해서 무너질 수 있음을 의미한다. # 그 이외의 경우는 파도가 쳐도 무너지지 않는다. 모래성이 무너진 경우, 그 격자는 모래성이 쌓여있지 않은 것으로 취급한다. # # 이 모래성은 언젠가는 파도에 의해서 깎이고 깎여서, 결국 한가지 형태로 수렴할 것이다. 모래성을 완성한 명우는 문득 자신이 만든 예술품의 수명이 궁금해졌다. # 모래성은 위에 서술한 바와 같이 파도가 한번 칠 때마다 특정 부분이 무너저내리는 방식으로 모양이 변화된다. 모래성이 더이상 모양이 변하지 않게 되려면 (모양이 수렴되려면) 파도가 몇번 쳐야하는지 구해보자. # # 입력 # 첫째 줄에는 모래성의 가로세로 격자 크기 H, W가 주어진다. (1 ≤ H, W ≤ 1,000) # # 그 다음 H줄에 걸쳐 W개의 문자로 모래성의 상태를 나타내는 문자가 들어온다. # # 각 문자는 1~9 사이의 숫자, 또는 '.' 이다. 1~9는 그 격자의 모래의 강도를 나타내며, '.'는 모래가 없다는 뜻이다. # # 모래성은 격자의 가장자리와 접해 있지 않다. # # 출력 # 몇번의 파도가 몰려오고나서야 모래성의 상태가 수렴하는지를 구한다. import sys from collections import deque H, W = map(int, sys.stdin.readline().split()) # 전처리 board = [list(map(int, sys.stdin.readline().rstrip().replace('.', '0'))) for _ in range(H)] # 무너진 구역 Q = deque([]) for y in range(H): for x in range(W): if board[y][x] == 0: Q.append((y, x)) res = 0 while True: for _ in range(len(Q)): y, x = Q.popleft() # 8방향 확인. for ny, nx in (y - 1, x - 1), (y - 1, x), (y - 1, x + 1), (y, x - 1), (y, x + 1), (y + 1, x - 1), (y + 1, x), ( y + 1, x + 1): # 범위 확인 if not (0 <= ny < H and 0 <= nx < W): continue if board[ny][nx] != 0: board[ny][nx] -= 1 if board[ny][nx] == 0: Q.append((ny, nx)) if Q: res += 1 else: break print(res) ================================================ FILE: BOJ/1072.게임/6047198844.py ================================================ X, Y = map(int, input().split()) target = 100 * Y // X # 판수 범위. begin = 1 end = 1000000000 + 1 # lower_bound while begin < end: mid = (begin + end) // 2 win_rate = 100 * (Y + mid) // (X + mid) if win_rate <= target: begin = mid + 1 else: end = mid if target == 100 * (Y + begin) // (X + begin): print(-1) else: print(begin) # float을 int()형변환하는건 위험하다. ================================================ FILE: BOJ/1074.Z/6047198844.py ================================================ import sys sys.setrecursionlimit(10 ** 9) # 가로/세로 크기, 현재 위치, 답 위치, 몇번째 방문인가. def func(N, cy, cx, ty, tx, cnt): # 기저 if N == 2: return cnt + 2 * (ty - cy) + (tx - cx) # 상 if cy + N // 2 > ty: # 좌 if cx + N // 2 > tx: return func(N // 2, cy, cx, ty, tx, cnt) # 우 else: return func(N // 2, cy, cx + N // 2, ty, tx, cnt + (N // 2) * (N // 2)) # 하 else: # 좌 if cx + N // 2 > tx: return func(N // 2, cy + N // 2, cx, ty, tx, cnt + 2 * (N // 2) * (N // 2)) # 우 else: return func(N // 2, cy + N // 2, cx + N // 2, ty, tx, cnt + 3 * (N // 2) * (N // 2)) N, r, c = map(int, sys.stdin.readline().split()) print(func(2 ** N, 0, 0, r, c, 0)) ================================================ FILE: BOJ/1075,나누기/6047198844.py ================================================ N = input()[:-2] F = int(input()) for i in range(100): if int(N + str(i).zfill(2)) % F == 0: print(str(i).zfill(2)) break ================================================ FILE: BOJ/10757.큰 수 A+B/6047198844.cpp ================================================ #include #include using namespace std; int main() { string a; string b; cin >> a >> b; while (a.length() != b.length()) { if (a.length() > b.length()) b = '0' + b; else if (a.length() < b.length()) a = '0' + a; } string res = ""; int temp = 0; int aIdx = a.length() - 1, bIdx = b.length() - 1; for (; aIdx >= 0 && bIdx >= 0; aIdx--, bIdx--) { int digit = temp + a[aIdx] + b[bIdx] - 2*'0'; temp = digit / 10; digit %= 10; res = char(digit + '0') + res; } if(temp) res = char(temp + '0') + res; cout << res; } ================================================ FILE: BOJ/10766.특별한 날/6047198844.py ================================================ month = int(input()) day = int(input()) if month < 2 or (month == 2 and day < 18): print("Before") elif month == 2 and day == 18: print('Special') else: print('After') ================================================ FILE: BOJ/10773.제로/s2uyeoii.c ================================================ #include #define MAX 100000 int stack[MAX]; int top = -1; void push(int data) { if (top >= MAX - 1) return; stack[++top] = data; } void pop() { if (top < 0) return; stack[top--] = 0; } int main() { int inputnum, data, sum = 0; scanf("%d", &inputnum); for(int i=0; i #include #include using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int N; cin >> N; vector arr(N); for (int i = 0; i < N; i++) cin >> arr[i]; sort(arr.begin(), arr.end()); int M; cin >> M; while (M--) { int _; cin >> _; int idx = lower_bound(arr.begin(), arr.end(), _) - arr.begin(); int res = 0; if (idx != arr.size()&&arr[idx]==_) { int eIdx = upper_bound(arr.begin(), arr.end(), _) - arr.begin(); res = eIdx - idx; } cout << res << " "; } } ================================================ FILE: BOJ/10816.숫자 카드 2/6047198844.py ================================================ # 문제 # 숫자 카드는 정수 하나가 적혀져 있는 카드이다. 상근이는 숫자 카드 N개를 가지고 있다. 정수 M개가 주어졌을 때, 이 수가 적혀있는 숫자 카드를 상근이가 몇 개 가지고 있는지 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. # 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다. # # 셋째 줄에는 M(1 ≤ M ≤ 500,000)이 주어진다. # 넷째 줄에는 상근이가 몇 개 가지고 있는 숫자 카드인지 구해야 할 M개의 정수가 주어지며, 이 수는 공백으로 구분되어져 있다. 이 수도 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다. # # 출력 # 첫째 줄에 입력으로 주어진 M개의 수에 대해서, 각 수가 적힌 숫자 카드를 상근이가 몇 개 가지고 있는지를 공백으로 구분해 출력한다. from collections import Counter N = int(input()) numbers_frequency = Counter(input().split()) M = int(input()) for number in input().split(): print(numbers_frequency[number], end=' ') ================================================ FILE: BOJ/10819.차이를 최대로/6047198844.cpp ================================================ #include #include #include #include using namespace std; int absolute_function(deque &dq, int n, int cnt) { int sum = 0; for (int i = 1; i < n; i++) sum += abs(dq.at(i - 1) - dq.at(i)); if (cnt == 1) return sum; int temp = dq.front(); dq.pop_front(); dq.push_back(temp); return max(sum, absolute_function(dq, n, cnt - 1)); } int main() { int N; cin >> N; deque dq; int num; for (int i = 0; i < N; i++) { cin >> num; dq.push_back(num); } cout << absolute_function(dq, N, N); } ================================================ FILE: BOJ/10826.피보나치 수 4/sangmandu.py ================================================ n = int(input()) a, b = 0, 1 for _ in range(n): a, b = b, a+b print(a) ================================================ FILE: BOJ/10830.행렬 제곱/10830_행렬 제곱.cpp ================================================ #include #include using namespace std; // A1 A2 vector > multiplyMatrix(vector > A1, vector > A2) { int N = A1.size(); vector > multiply_res; for (int y = 0; y < N; y++) { vector temp; for (int x = 0; x < N; x++) { int element = 0; for (int a = 0; a < N; a++) { element += ((A1[y][a] % 1000) * (A2[a][x] % 1000)) % 1000; element %= 1000; } temp.push_back(element); } multiply_res.push_back(temp); } return multiply_res; } //ߺ ι. // //ڷ vector > divide_and_conquer(vector > &A, long long B) { if (B == 1) return A; vector > temp = divide_and_conquer(A, B / 2); if (B % 2) return multiplyMatrix(multiplyMatrix(temp, temp), A); else return multiplyMatrix(temp, temp); } int main() { int N; cin >> N; long long B; cin >> B; vector > A; int num; for (int i = 0; i < N; i++) { vector row; for (int j = 0; j < N; j++) { cin >> num; row.push_back(num); } A.push_back(row); } vector > res = divide_and_conquer(A, B); for (int y = 0; y < N; y++) { for (int x = 0; x < N; x++) { cout << res[y][x] % 1000 << " "; } cout << "\n"; } } ================================================ FILE: BOJ/10833.사과/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) res = 0 for _ in range(N): A, B = map(int, sys.stdin.readline().split()) res += B % A print(res) ================================================ FILE: BOJ/10844.쉬운 계단 수/rockmiin.py ================================================ n= int(input()) dp=[[0]*10 for _ in range(n+1)] dp[1]= [0]+[1]*9 for i in range(1, n+1): for j in range(1, 9): dp[i][j]+= (dp[i-1][j-1]+ dp[i-1][j+1]) dp[i][0]+= dp[i-1][1] dp[i][9]+= dp[i-1][8] print(sum(dp[-1])%1000000000) ================================================ FILE: BOJ/1085.직사각형에서 탈출/6047198844.cpp ================================================ #include #include using namespace std; int minDistance(int x, int y, int w, int h) { int yDiff = min(h - y, y); int xDiff = min(w - x, x); return min(yDiff, xDiff); } int main() { int x, y, w, h; cin >> x >> y >> w >> h; cout << minDistance(x, y, w, h); } ================================================ FILE: BOJ/10867.중복 뺴고 정렬하기/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) arr = set(map(int, sys.stdin.readline().split())) for i in sorted(arr): print(i, end=' ') ================================================ FILE: BOJ/10867.중복 뺴고 정렬하기/rockmiin.py ================================================ n= int(input()) arr= sorted(list(map(int, input().split()))) res= [] for i in arr: if i not in res: res.append(i) print(i, end=" ") ================================================ FILE: BOJ/10870.피보나치 수 5/sangmandu.py ================================================ n = int(input()) a, b = 0, 1 for _ in range(n): a, b = b, a+b print(a) ================================================ FILE: BOJ/1092.배/6047198844.py ================================================ # 크레인이 N 대 있고, 1분에 박스를 하나씩 배에 실을 수 있다. # 모든 크레인은 동시에 움직인다. # 각 크레인은 무게 제한이 있다. 무게 제한 보다 무거운 박스는 크레인으로 움직일 수 없다. # 모든 박스를 배로 옮기는데 드는 시간의 최솟값을 구하는 프로그램을 작성하시오. import heapq import sys crains_N = int(sys.stdin.readline()) crains = list(map(int, sys.stdin.readline().split())) boxes_N = int(sys.stdin.readline()) boxes = list(map(lambda i: -int(i), sys.stdin.readline().split())) heapq.heapify(boxes) crains.sort(reverse=True) res = 0 # 가장 무거운 박스를 가장 많이 드는 크레인이 못드는 경우 if -boxes[0] > crains[0]: print(-1) exit() # 모든 박스를 시간이 오래걸려도 들을수있다. while boxes: for crain in crains: if boxes: box = -heapq.heappop(boxes) if crain >= box: pass else: break else: break res += 1 print(res) ================================================ FILE: BOJ/10926.??!/6047198844.py ================================================ print(input()+"??!") ================================================ FILE: BOJ/1094.막대기/6047198844.py ================================================ import heapq import sys X = int(sys.stdin.readline()) S = 64 sticks = [64] while S > X: if S > X: stick = heapq.heappop(sticks) heapq.heappush(sticks, stick // 2) heapq.heappush(sticks, stick // 2) if S - sticks[0] >= X: heapq.heappop(sticks) S -= sticks[0] print(len(sticks)) ================================================ FILE: BOJ/10942.팰린드롬?/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) numbers = list(map(int, sys.stdin.readline().split())) M = int(sys.stdin.readline()) # True 인 경우 펠린드롬이다. memo = [[False for _ in range(N)] for _ in range(N)] # 팰린드롬을 만들자. # 기저는 2개가 존재. # 구간의 길이가 1일때 -> 무조건 True # 구간의 길이가 2일때 -> 둘이 같으면 True # 구간이 3이상일때 # 3은 기저가 1이고, 4는 기저가 2이다. # 5는 3, 6은 4 ... 따라서 구간 1, 구간 2이 기저가된다. # 구간의 길이는 3에서 N - 1 이다. for k in range(N): for i in range(N - k): j = i + k if numbers[i] == numbers[j] and (k < 2 or memo[i + 1][j - 1]): memo[i][j] = True for _ in range(M): S, E = map(lambda i: int(i) - 1, sys.stdin.readline().split()) print(int(memo[S][E])) ================================================ FILE: BOJ/10988.팰린드롬인지 확인하기/6047198844.py ================================================ s = input() print(int(s==s[::-1])) ================================================ FILE: BOJ/11000.강의실 배정/6047198844.py ================================================ import heapq import sys PQ = [] # 종료시간을 저장. 각각은 하나의 강의실을 의미한다. PQF = [] N = int(sys.stdin.readline()) for _ in range(N): S, T = map(int, sys.stdin.readline().split()) heapq.heappush(PQ, (S, T)) while PQ: S, T = heapq.heappop(PQ) if not PQF: heapq.heappush(PQF, T) continue # 종료시간이 가장 빠른 강의실의 종료시간이 새로 추가하려는 강의시간보다 같거나 빠른 경우 # 해당 강의실에서 이어 강의할수있다. 따라서 해당 강의실을 POP하고 추가한다. if PQF[0] <= S: heapq.heappop(PQF) heapq.heappush(PQF, T) print(len(PQF)) ================================================ FILE: BOJ/11003.최솟값 찾기/6047198844.py ================================================ # 문제 # N개의 수 A1, A2, ..., AN과 L이 주어진다. # # Di = Ai-L+1 ~ Ai 중의 최솟값이라고 할 때, D에 저장된 수를 출력하는 프로그램을 작성하시오. 이때, i ≤ 0 인 Ai는 무시하고 D를 구해야 한다. # # 입력 # 첫째 줄에 N과 L이 주어진다. (1 ≤ L ≤ N ≤ 5,000,000) # # 둘째 줄에는 N개의 수 Ai가 주어진다. (-109 ≤ Ai ≤ 109) # # 출력 # 첫째 줄에 Di를 공백으로 구분하여 순서대로 출력한다. # 최소값 / 최소값 후보 from collections import deque N, L = map(int, input().split()) arr = list(map(int, input().split())) res = deque() for i, num in enumerate(arr): # res 최적화. 현재 범위에 맞지 않는 경우 없엔다. if res and not (i-L+1 <= res[0][0] <= i): res.popleft() # res가 없으면 삽입 -> 무조건 최소값임. while res and res[-1][1] >= num: res.pop() res.append((i, num)) print(res[0][1], end=' ') ================================================ FILE: BOJ/11047.동전0/rockmiin.py ================================================ n, k= map(int, input().split()) coin= [] cnt= 0 for i in range(n): coin.append(int(input())) coin.reverse() for i in coin: if k #include using namespace std; int miro[1001][1001]; int memo[1001][1001]; int max_x; int max_y; int dx[3] = { -1,0,-1 }; int dy[3] = { 0,-1,-1 }; bool check(int y, int x) { if (y<1 || y>max_y) return false; if (x<1 || x>max_x) return false; return true; } int dp(int y, int x) { if (memo[y][x]) return memo[y][x]; int &res = memo[y][x]; for (int i = 0; i < 3; i++) { int check_y = y + dy[i]; int check_x = x + dx[i]; if (check(check_y, check_x)) { res = max(dp(check_y, check_x) + miro[y][x], res); //이부분에서 실수 //문제 잘못읽음 } } return res; } int main() { cin >> max_y >> max_x; for (int i = 1; i <= max_y; i++) for (int j = 1; j <= max_x; j++) cin >> miro[i][j]; memo[1][1] = miro[1][1]; cout << dp(max_y, max_x); } ================================================ FILE: BOJ/11049.행렬 곱셈 순서/6047198844.py ================================================ # 문제 # 크기가 N×M인 행렬 A와 M×K인 B를 곱할 때 필요한 곱셈 연산의 수는 총 N×M×K번이다. 행렬 N개를 곱하는데 필요한 곱셈 연산의 수는 행렬을 곱하는 순서에 따라 달라지게 된다. # # 예를 들어, A의 크기가 5×3이고, B의 크기가 3×2, C의 크기가 2×6인 경우에 행렬의 곱 ABC를 구하는 경우를 생각해보자. # # AB를 먼저 곱하고 C를 곱하는 경우 (AB)C에 필요한 곱셈 연산의 수는 5×3×2 + 5×2×6 = 30 + 60 = 90번이다. # BC를 먼저 곱하고 A를 곱하는 경우 A(BC)에 필요한 곱셈 연산의 수는 3×2×6 + 5×3×6 = 36 + 90 = 126번이다. # 같은 곱셈이지만, 곱셈을 하는 순서에 따라서 곱셈 연산의 수가 달라진다. # # 행렬 N개의 크기가 주어졌을 때, 모든 행렬을 곱하는데 필요한 곱셈 연산 횟수의 최솟값을 구하는 프로그램을 작성하시오. 입력으로 주어진 행렬의 순서를 바꾸면 안 된다. # # 입력 # 첫째 줄에 행렬의 개수 N(1 ≤ N ≤ 500)이 주어진다. # # 둘째 줄부터 N개 줄에는 행렬의 크기 r과 c가 주어진다. (1 ≤ r, c ≤ 500) # # 항상 순서대로 곱셈을 할 수 있는 크기만 입력으로 주어진다. # # 출력 # 첫째 줄에 입력으로 주어진 행렬을 곱하는데 필요한 곱셈 연산의 최솟값을 출력한다. 정답은 231-1 보다 작거나 같은 자연수이다. 또한, 최악의 순서로 연산해도 연산 횟수가 231-1보다 작거나 같다. import math import sys N = int(sys.stdin.readline()) matrices = [tuple(map(int, sys.stdin.readline().split())) for _ in range(N)] memo = [[math.inf for _ in range(N)] for _ in range(N)] for i in range(N): memo[i][i] = 0 for j in range(N): for i in range(N - j): for k in range(i, i + j): s = memo[i][k] + memo[k + 1][i + j] + matrices[i][0] * matrices[k][1] * matrices[i + j][1] if memo[i][i + j] > s: memo[i][i + j] = s print(memo[0][N - 1]) ================================================ FILE: BOJ/11050.이항 계수 1/6047198844.cpp ================================================ #include using namespace std; int combi(int N, int K) { if (K == 0) return 1; if (N == K) return 1; return combi(N - 1, K) + combi(N - 1, K - 1); } int main() { int N; int K; cin >> N >> K; cout << combi(N, K); } ================================================ FILE: BOJ/11051.이항 계수 2/6047198844.cpp ================================================ #include using namespace std; long long memo[1001][1001]; long long combi(int n, int k) { if (k == 0 || n == k) return 1; long long& res = memo[n][k]; if (res) return res; return res = (combi(n - 1, k - 1) % 10007 + combi(n - 1, k) % 10007) % 10007; } int main() { int N; int K; cin >> N >> K; cout << combi(N, K); } ================================================ FILE: BOJ/11051.이항 계수 2/ms9849.cpp ================================================ #include using namespace std; long long dp[1001][1001]; //파스칼의 삼각형을 이용했습니다. 따라서 2차원 dp배열을 선언했습니다. int N,K; int main(void) { cin >> N >> K; for(int i=1; i<=N; i++) { //nC0, nC1은 1이므로 미리 1을 입력합니다. dp[i][0]=1; dp[i][i]=1; } for(int i=2; i<=N; i++) { // 문제에서 10007로 나눈 나머지를 출력하라고 제시했으므로, %10007 연산을 추가해줍니다. for(int j=1; j<=N-1; j++) { dp[i][j] = (dp[i-1][j-1] + dp[i-1][j])%10007; } } cout << dp[N][K]; return 0; } ================================================ FILE: BOJ/11052. 카드 구매하기/6047198844.cpp ================================================ #include #include #include #include using namespace std; int input[1001]; int memo[1001] = {}; //int mod = 1000000; int bottomup_dp(int n) { memo[0] = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) if(memo[i] < input[j] + memo[i - j]) memo[i] = input[j] + memo[i - j]; return memo[n]; } int main() { int N; cin >> N; for (int i = 1; i <= N; i++) cin >> input[i]; cout << bottomup_dp(N); } ================================================ FILE: BOJ/11052.카드 구매하기/rockmiin.py ================================================ n= int(input()) p= [0] + list(map(int, input().split())) dp= [0 for _ in range(n+1)] dp[1]= p[1] for i in range(1, n+1): for j in range(1, i+1): # print(i, j, dp) dp[i]= max(dp[i], dp[i-j]+ p[j]) print(dp[-1]) ================================================ FILE: BOJ/11054.가장 긴 바이토닉 부분 수열/6047198844.cpp ================================================ #include #include using namespace std; int arr[1001] = {}; int memo_a[1001] = {}; int memo_d[1001] = {}; int bottomup_dp(int n) { int ans = 0; fill(&memo_a[1], &memo_a[n+1], 1); fill(&memo_d[1], &memo_d[n+1], 1); for (int i = 2; i <= n; i++) for (int j = 1; j < i; j++) if (arr[i] > arr[j]) memo_a[i] = max(memo_a[i], memo_a[j] + 1); for (int i = n - 1; i > 1; i--) for (int j = n; j > i; j--) if (arr[i] > arr[j]) memo_d[i] = max(memo_d[i], memo_d[j] + 1); for (int i = 1; i <= n; i++) ans = max(ans, memo_a[i] + memo_d[i] - 1); return ans; } int main() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> arr[i]; cout << bottomup_dp(n) << "\n"; } ================================================ FILE: BOJ/11055.가장 큰 증가 부분 수열/6047198844.cpp ================================================ #include #include using namespace std; int arr[1001] = {}; int memo[1001] = {}; int bottomup_dp(int n) { int ans = 0; //memo[1] = arr[1]; for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) if (arr[i] > arr[j]) memo[i] = max(memo[i], memo[j] + arr[i]); } ans = *max_element(&memo[1], &memo[1] + n); return ans; } int main() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> arr[i]; cout << bottomup_dp(n); } ================================================ FILE: BOJ/11057.오르막 수/Munang.py ================================================ n = int(input()) dp = [[0 for i in range(10)]for _ in range(0,n+1)] for i in range(0,n+1): for j in range(10): if(i==1): dp[i][j] =1 else: for k in range(10): if(k<=j): dp[i][j] = dp[i-1][j-k]+dp[i][j] print(sum(dp[n][0:10])%10007) ================================================ FILE: BOJ/1106.호텔/sAp00n.py ================================================ """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 2 초 128 MB 1379 346 262 27.843% 문제 세계적인 호텔인 형택 호텔의 사장인 김형택은 이번에 수입을 조금 늘리기 위해서 홍보를 하려고 한다. 형택이가 홍보를 할 수 있는 도시가 주어지고, 각 도시별로 홍보하는데 드는 비용과, 그 때 몇 명의 호텔 고객이 늘어나는지에 대한 정보가 있다. 예를 들어, “어떤 도시에서 9원을 들여서 홍보하면 3명의 고객이 늘어난다.”와 같은 정보이다. 이때, 이러한 정보에 나타난 돈에 정수배 만큼을 투자할 수 있다. 즉, 9원을 들여서 3명의 고객, 18원을 들여서 6명의 고객, 27원을 들여서 9명의 고객을 늘어나게 할 수 있지만, 3원을 들여서 홍보해서 1명의 고객, 12원을 들여서 4명의 고객을 늘어나게 할 수는 없다. 각 도시에는 무한 명의 잠재적인 고객이 있다. 이때, 호텔의 고객을 적어도 C명 늘이기 위해 형택이가 투자해야 하는 돈의 최솟값을 구하는 프로그램을 작성하시오. 입력 첫째 줄에 C와 형택이가 홍보할 수 있는 도시의 개수 N이 주어진다. C는 1,000보다 작거나 같은 자연수이고, N은 20보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에는 각 도시에서 홍보할 때 대는 비용과 그 비용으로 얻을 수 있는 고객의 수가 주어진다. 이 값은 100보다 작거나 같은 자연수이다. 출력 첫째 줄에 문제의 정답을 출력한다. """ from sys import stdin C, N = map(int, stdin.readline().split()) cost_list = [] dp = [0] * 1101 max_output = 0 for _ in range(N): cost, output = map(int, stdin.readline().split()) cost_list.append((cost, output)) for idx in range(1, C + 1): possible_case_list = [] for case in cost_list: if case[1] > idx: possible_case_list.append(case[0]) continue possible_case_list.append(dp[idx - case[1]] + case[0]) if len(possible_case_list) > 0: dp[idx] = min(possible_case_list) print(dp[C]) ================================================ FILE: BOJ/1106.호텔/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/1106 호텔 DP : Knapsack 풀이방법 이용 ''' from sys import stdin def solution(target, cities): graph = [[0] + [100000] * target for i in range(len(cities)+1)] for idx, b in enumerate(cities): for i in range(1, target+1): graph[idx+1][i] = min(graph[idx][i], graph[idx+1][i-b[1] if i-b[1] >=0 else 0]+b[0]) print(graph[len(cities)][target]) target, city = map(int, stdin.readline().split()) cities = [list(map(int, stdin.readline().split())) for _ in range(city)] solution(target, cities) ''' ''' ================================================ FILE: BOJ/11066.파일 합치기/6047198844.cpp ================================================ #include #include #include using namespace std; int cache[500][500]; int page[500]; //i j "" ߻ϴ int dp(int i, int j) { //ĥ -> 0 ߻Ѵ, ĥ. if (i == j) return 0; int& res = cache[i][j]; if (res != -1) return res; int sum = 0; //i j  Ѵ. ̶ sum dp(i,k) dp(k+1,j) ̴. for (int k = i; k <= j; k++) sum += page[k]; int tmp; for (int k = i; k+1 <= j; k++) { tmp = (dp(i, k) + dp(k + 1, j) + sum); if (res == -1 || tmp < res) res = tmp; } return res; } int main() { int T, K, temp; cin >> T; while (T--) { memset(cache, -1, sizeof(cache)); memset(page, 0, sizeof(page)); cin >> K; for (int i = 0; i < K; i++) cin >> page[i]; cout << dp(0, K - 1) << "\n"; } } ================================================ FILE: BOJ/1110.더하기 사이클/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/1110 더하기 사이클 [풀이] 1. n이 한자리수면 앞에 '0' 을 추가한다. 2. 계속 변해가는 숫자 tmp, 사이클 횟수 cnt 선언 3. 제시된 방법대로 사이클 구성 ''' n = input() if len(n) == 1: n = '0' + n tmp, cnt = n, 0 while True: a, b = tmp c = str(int(a) + int(b)) d = c[-1] tmp = b + d cnt += 1 if tmp == n: break print(cnt) ================================================ FILE: BOJ/11170.0의 개수/6047198844.py ================================================ T = int(input()) for _ in range(T): N, M = map(int, input().split()) print(sum([str(i).count("0") for i in range(N, M + 1)])) ================================================ FILE: BOJ/1120.문자열/6047198844.py ================================================ import math A, B = input().split() res = math.inf for i in range(len(B) - len(A) + 1): cnt = 0 for j in range(len(A)): if A[j] != B[i+j]: cnt += 1 res = min(cnt, res) print(res) ================================================ FILE: BOJ/11256.사탕/6047198844.py ================================================ #사탕들을 포장할 공간은 충분하다. T = int(input()) for _ in range(T): J, N = map(int, input().split()) boxs = list() for _ in range(N): R, C = map(int, input().split()) boxs.append(R*C) boxs.sort(reverse=True) cnt = 0 for box in boxs: J -= box cnt += 1 if J <= 0: print(cnt) break ================================================ FILE: BOJ/11279.최대 힙/6047198844.cpp ================================================ #include #include using namespace std; //삽입 조정 //기저 사례 : 부모가 없는 경우 //부모보다 큰경우 부모와 자신을 바꾼다. void insert_adj(vector& arr, int idx) { if (idx == 0) return; int parent_idx = (idx - 1) / 2; if (arr[parent_idx] < arr[idx]) { swap(arr[parent_idx], arr[idx]); insert_adj(arr, parent_idx); } return; } //삽입 //배열의 맨 끝에 원소를 삽입하고 조정한다. void insert(vector& arr, int element) { arr.push_back(element); insert_adj(arr, arr.size() - 1); } //삭제 조정 //기저 사례 : 자식의 인덱스가 끝 인덱스(N-1)보다 큰 경우 void del_adj(vector& arr, int idx, int end_idx) { //자식이 둘다 없는 경우 if (idx * 2 + 1 > end_idx) return; //자식이 하나인 경우 if (idx * 2 + 1 == end_idx) { if (arr[idx * 2 + 1] > arr[idx]) swap(arr[idx * 2 + 1], arr[idx]); return; } //자식이 둘인 경우 //큰 자식 보다 작을경우. int big_idx = arr[idx * 2 + 1] < arr[idx * 2 + 2] ? idx * 2 + 2 : idx * 2 + 1; if (arr[idx] < arr[big_idx]) { swap(arr[idx], arr[big_idx]); del_adj(arr, big_idx, end_idx); } //자식 보다 클경우. return; } //삭제 //배열의 루트에 원소를 삽입하고 조정한다. 삭제한값을 반환한다. int del(vector& arr) { if (arr.empty()) return 0; int res = arr[0]; arr[0] = arr.back(); arr.pop_back(); del_adj(arr, 0, arr.size() - 1); return res; } int main() { int N; scanf("%d", &N); vectorarr; int element; while (N--) { scanf("%d", &element); if (element) insert(arr, element); else printf("%d\n", del(arr)); } } ================================================ FILE: BOJ/11286.절댓값 힙/6047198844.cpp ================================================ /* 문제 절댓값 힙은 다음과 같은 연산을 지원하는 자료구조이다. 배열에 정수 x (x ≠ 0)를 넣는다. 배열에서 절댓값이 가장 작은 값을 출력하고, 그 값을 배열에서 제거한다. 절댓값이 가장 작은 값이 여러개일 때는, 가장 작은 수를 출력하고, 그 값을 배열에서 제거한다. 프로그램은 처음에 비어있는 배열에서 시작하게 된다. 입력 첫째 줄에 연산의 개수 N(1≤N≤100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 0이 아니라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0이라면 배열에서 절댓값이 가장 작은 값을 출력하고 그 값을 배열에서 제거하는 경우이다. 입력되는 정수는 -2^31보다 크고, 2^31보다 작다. 출력 입력에서 0이 주어진 회수만큼 답을 출력한다. 만약 배열이 비어 있는 경우인데 절댓값이 가장 작은 값을 출력하라고 한 경우에는 0을 출력하면 된다. */ #include #include #include using namespace std; //최대힙 (음수) class maxHeap { private: vector maxHeap; public: //힙 추가후 조정 연산 //부모보다 크면 올라간다. void push_adj(int idx) { //부모가 없는 경우 if (idx == 0) return; //부모가 있는 경우 int parentIdx = (idx - 1) / 2; if (maxHeap[idx] > maxHeap[parentIdx]) { swap(maxHeap[idx], maxHeap[parentIdx]); push_adj(parentIdx); } return; } //힙 추가 연산 , N을 추가한다. void push(int N) { maxHeap.push_back(N); push_adj(maxHeap.size() - 1); return; } //힙 삭제후 조정 연산 void del_adj(int idx) { int leftIdx = idx * 2 + 1; int rightIdx = idx * 2 + 2; int maxIdx = maxHeap.size() - 1; //자식이 없는 경우 //자식 둘(왼쪽 자식)이 없는 경우 if (leftIdx > maxIdx) return; //자식 둘중 큰 자식을 고른다. int maxChildIdx; //자식 하나(오른쪽 자식)이 없는 경우 if (leftIdx == maxIdx) maxChildIdx = leftIdx; //자식이 둘있는 경우 else maxChildIdx = maxHeap[leftIdx] >= maxHeap[rightIdx] ? leftIdx : rightIdx; if (maxHeap[maxChildIdx] > maxHeap[idx]) { swap(maxHeap[maxChildIdx], maxHeap[idx]); del_adj(maxChildIdx); } return; } //힙 삭제 연산 -> 삭제값 반환 int del() { int res = maxHeap[0]; maxHeap[0] = maxHeap.back(); maxHeap.pop_back(); del_adj(0); return res; } //empty 체크도함. int getMaxValue() { return maxHeap.empty() ? 0 : maxHeap[0]; } }; //최소힙 (양수) class minHeap { private: vector minHeap; public: //힙 추가후 조정 연산 //부모보다 작으면 올라간다. void push_adj(int idx) { //부모가 없는 경우 if (idx == 0) return; //부모가 있는 경우 int parentIdx = (idx - 1) / 2; if (minHeap[idx] < minHeap[parentIdx]) { swap(minHeap[idx], minHeap[parentIdx]); push_adj(parentIdx); } return; } //힙 추가 연산 , N을 추가한다. void push(int N) { minHeap.push_back(N); push_adj(minHeap.size() - 1); return; } //힙 삭제후 조정 연산 void del_adj(int idx) { int leftIdx = idx * 2 + 1; int rightIdx = idx * 2 + 2; int maxIdx = minHeap.size() - 1; //자식이 없는 경우 //자식 둘(왼쪽 자식)이 없는 경우 if (leftIdx > maxIdx) return; //자식 둘중 큰 자식을 고른다. int minChildIdx; //자식 하나(오른쪽 자식)이 없는 경우 if (leftIdx == maxIdx) minChildIdx = leftIdx; //자식이 둘있는 경우 else minChildIdx = minHeap[leftIdx] <= minHeap[rightIdx] ? leftIdx : rightIdx; if (minHeap[minChildIdx] < minHeap[idx]) { swap(minHeap[minChildIdx], minHeap[idx]); del_adj(minChildIdx); } return; } //힙 삭제 연산 -> 삭제값 반환 int del() { int res = minHeap[0]; minHeap[0] = minHeap.back(); minHeap.pop_back(); del_adj(0); return res; } //empty 체크도함. int getMinValue() { return minHeap.empty() ? 0 : minHeap[0]; } }; int main() { int N; cin >> N; minHeap *minH = new minHeap(); maxHeap *maxH = new maxHeap(); int cmd; while (N--) { cin >> cmd; if (cmd == 0) { int positive = minH->getMinValue(); int negative = maxH->getMaxValue(); int res = !positive && !negative ? 0 : !positive ? maxH->del() : !negative ? minH->del() : positive == -negative ? maxH->del() : positive > -negative ? maxH->del() : minH->del(); cout << res << "\n"; } else if (cmd < 0) maxH->push(cmd); else minH->push(cmd); } }s ================================================ FILE: BOJ/11365.!밀비 급일/6047198844.py ================================================ # 문제 # 당신은 길을 가다가 이상한 쪽지를 발견했다. 그 쪽지에는 암호가 적혀 있었는데, 똑똑한 당신은 암호가 뒤집으면 해독된다는 것을 발견했다. # # 이 암호를 해독하는 프로그램을 작성하시오. # # 입력 # 한 줄에 하나의 암호가 주어진다. 암호의 길이는 500을 넘지 않는다. # # 마지막 줄에는 "END"가 주어진다. (END는 해독하지 않는다.) import sys while True: plain = sys.stdin.readline().rstrip() if plain == 'END': break print(plain[::-1]) ================================================ FILE: BOJ/1138.한 줄로 서기/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/1138 한 줄로 서기 [풀이] 1. 키가 큰 순으로 자리를 배치시킨다. => 키가 큰 사람들을 고려하기 때문에 앞사람 만을 고려하면 된다. => 뒷 사람은 다 작으므로 고려할 필요 없음 2. 각 사람은 배치중인 자리를 기준으로 자신의 값만큼의 인덱스에 추가한다 => 만약 현재 3명이 줄을 서있고 (이 사람들은 모두 자신보다 키가 큼) => 자신 왼쪽으로 1명이 있다면 1 ... (여기) ... 2 로 배치하면 된다 3. 문자열 꼴로 출력 ''' n = int(input()) lst = map(int, input()[::-1].split()) ret = [] for idx, val in enumerate(lst): ret = ret[:val]+[str(n-idx)]+ret[val:] print(' '.join(ret)) ================================================ FILE: BOJ/11382.꼬마 정민/6047198844.py ================================================ A, B, C = map(int, input().split()) print(A + B + C) ================================================ FILE: BOJ/11399.ATM/6047198844.cpp ================================================ #include #include #include using namespace std; int main() { int N, input; int sum = 0; cin >> N; vector vt; for (int i = 0; i < N; i++) { cin >> input; vt.push_back(input); } sort(vt.begin(),vt.end()); for (int i = 0; i < N; i++) sum += (N - i) * vt[i]; cout << sum; } ================================================ FILE: BOJ/11399.ATM/rockmiin.py ================================================ n= int(input()) p=sorted(list(map(int, input().split()))) time=0 for i in range(n): time+=p[i]*(n-i) print(time) ================================================ FILE: BOJ/11401.이항계수 3/6047198844.cpp ================================================ #include #include #define LL long long using namespace std; LL Factorial(int N,vector &memo) { if (memo[N]) return memo[N]; return memo[N] = N * Factorial(N - 1, memo) % 1000000007; } LL divide_and_conquer(int A, int P) { if (P == 1) return A; LL half = divide_and_conquer(A, P / 2) % 1000000007; if (P % 2) return ((half * half) % 1000000007 * A) % 1000000007; return half * half % 1000000007; } int main() { int N; int K; cin >> N >> K; vector memo(N + 1, 0); memo[0] = memo[1] = 1; LL N_fact = Factorial(N, memo); LL K_fact = Factorial(K, memo); LL N_minus_K_fact = Factorial(N - K, memo); LL res = (N_fact * divide_and_conquer(K_fact, 1000000007 - 2) % 1000000007 * divide_and_conquer(N_minus_K_fact, 1000000007 - 2)) % 1000000007; cout << res; } ================================================ FILE: BOJ/11403.경로 찾기/6047198844.py ================================================ import math import sys N = int(sys.stdin.readline()) distance = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] # 초기화 for y in range(N): for x in range(N): if distance[y][x] == 0: distance[y][x] = math.inf # 최단거리 계산 for k in range(N): for i in range(N): for j in range(N): if distance[i][j] > distance[i][k] + distance[k][j]: distance[i][j] = distance[i][k] + distance[k][j] for y in range(N): for x in range(N): if distance[y][x] != math.inf: print(1, end=' ') else: print(0, end=' ') print() ================================================ FILE: BOJ/11403.경로 찾기/rockmiin.py ================================================ from collections import deque def bfs(start, end): visited= [0]*n if start== end: q= deque(adj[start]) for i in adj[start]: visited[i]= 1 else: q= deque([start]) visited[start]= 1 while q: v= q.popleft() if v== end: arr2[start][end]= 1; break; for val in adj[v]: if not visited[val]: q.append(val) visited[val]= 1 n= int(input()) arr= [] arr2= [[0]*n for _ in range(n)] adj=[[] for _ in range(n)] for i in range(n): arr.append(list(map(int, input().split()))) for i in range(n): for j in range(n): if arr[i][j]== 1: adj[i].append(j) # print(adj) for i in range(n): for j in range(n): bfs(i, j) for i in arr2: for j in i: print(j, end= " ") print() # for i in arr2: # print(i) ================================================ FILE: BOJ/11404.플로이드/6047198844.cpp ================================================ #include #include #include #include #define INF INT_MAX using namespace std; void floyd(vector> &vt,int n) { for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (vt[i][k] != INF && vt[k][j] != INF && i != j) vt[i][j] = min(vt[i][j], vt[i][k] + vt[k][j]); } return; } int main() { int n,m; cin >> n; vector > vt(n + 1, vector(n + 1, INF)); cin >> m; int a, b, c; while (m--) { cin >> a >> b >> c; vt[a][b] = min(vt[a][b], c); } floyd(vt, n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (vt[i][j] == INF) cout << 0; else cout << vt[i][j]; cout << " "; } cout << "\n"; } } ================================================ FILE: BOJ/1141.접두사/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/1141 접두사 [풀이] 1. A단어가 B단어의 접두사가 되려면 두 단어는 사전순으로 가까이에 위치해있다. 2. 사전순으로 정렬된(오름차순) 세 단어 A, B, C가 있다고 하자 => A가 B의 접두사가 아니고 B는 C의 접두사가 아닐 때 A는 C의 접두사가 될 수 없다. => 사전순으로 정렬된다는 가정에 위배되기 때문 => 따라서 사전 순으로 전에 위치한 단어가 후에 위치한 단어의 접두사가 아니라면 이후에 어떠한 단어의 접두사도 아니다. 3. startswith를 사용하여 조사한다. => 또는 find == 0 으로도 조사할 수 있다. ''' n = int(input()) words = sorted([input() for _ in range(n)]) print(n-[words[i+1].startswith(words[i]) for i in range(n-1)].count(True)) ================================================ FILE: BOJ/11437.LCA/6047198844.py ================================================ import sys from collections import defaultdict, deque sys.setrecursionlimit(10**9) LOG = 15 N = int(sys.stdin.readline()) edges = defaultdict(list) for _ in range(N-1): V, W = map(int, sys.stdin.readline().split()) edges[V].append(W) edges[W].append(V) D = [0 for _ in range(N + 1)] P = [[-1 for _ in range(LOG+1)]for _ in range(N + 1)] visited = set() def make_tree(V, depth): visited.add(V) D[V] = depth for W in edges[V]: if W not in visited: make_tree(W, depth + 1) P[W][0] = V make_tree(1, 0) for i in range(1, LOG+1): for j in range(N+1): P[j][i] = P[P[j][i-1]][i-1] def LCA(A, B): if D[B] < D[A]: A, B = B, A for i in range(LOG, -1, -1): if D[B] - D[A] >= 1 << i: B = P[B][i] if A == B: return A for i in range(LOG, -1, -1): if P[A][i] != P[B][i]: A = P[A][i] B = P[B][i] return P[A][0] M = int(sys.stdin.readline()) for _ in range(M): V, W = map(int, sys.stdin.readline().split()) print(LCA(V,W)) ================================================ FILE: BOJ/11438.LCA 2/6047198844.py ================================================ import sys input = sys.stdin.readline sys.setrecursionlimit(int(1e5)) # 최대 로그 깊이 LOG = 16 N = int(input()) edge = [[] for _ in range(N + 1)] # 트리 만들기 for _ in range(N - 1): i, j = map(int, input().split()) edge[i].append(j) edge[j].append(i) # 부모 노드 정보 # P[i][k] = i의 2^k 번째 조상. # P[i][k] = P[P[i][k-1]][k-1] P = [[0] * (LOG + 1) for _ in range(N + 1)] # 노드 방문 정보 visited = set() # 노드의 깊이 정보 depth = [0] * (N + 1) # 깊이 탐색하면서 단방향 그래프로 만든다. def dfs(parent, d): visited.add(parent) depth[parent] = d for child in edge[parent]: if child in visited: continue # 부모 노드 정보 갱신 P[child][0] = parent dfs(child, d + 1) # 전체 부모 관계를 갱신한다. def set_parent(): # 위에서 부터 깊이를 더한다. # 0 번째 깊이는 이미 단방향 그래프 제작과정에서 만들어짐 for i in range(1, LOG + 1): for j in range(1, N + 1): P[j][i] = P[P[j][i - 1]][i - 1] # A, B 의 공통조상을 찾는다. def LCA(A, B): # 항상 B가 깊도록 설정한다. if depth[A] > depth[B]: A, B = B, A # 깊이를 조정한다. # 이때 P를 사용해서 로그 탐색이 이루어진다. # 비트 연산을 이용한다. for i in range(LOG, -1, -1): # 깊이 차이가 i 보다 같거나 크면 i 만큼 점프 할 수 있다. if depth[B] - depth[A] >= (1 << i): B = P[B][i] # 둘이 같으면 종료한다. if A == B: return A # 조상을 향해 거슬러올라간다. 로그만큼 거슬러 올라간다. # 최소 공통 조상의 직전 자식을 찾을것이다. for i in range(LOG, -1, -1): # 같으면 최소 공통 조상의 직전 자식의 조건이 되지 않는다. # 같지않다면 최소 공통 조상의 직전 자식의 조건이 된다. if P[A][i] != P[B][i]: A = P[A][i] B = P[B][i] # 최소 공통 조상의 직전 자식의 부모가 정답이다. return P[A][0] # 루트는 1번이다. 부모관계 설정. 간선을 만든다. dfs(1, 0) set_parent() M = int(input()) for _ in range(M): i, j = map(int, input().split()) print(LCA(i, j)) ================================================ FILE: BOJ/11444.피보나치 수 6/11444_피보나치 수 6.cpp ================================================ #include #include #define LL vector using namespace std; vector vt({ LL({1,1}),LL({1,0}) }); vector multiply_matrix(vector A, vector B) { vector res({ LL({ (A[0][0] % 1000000007 * B[0][0] % 1000000007 + A[0][1] % 1000000007 * B[1][0] % 1000000007) % 1000000007, (A[0][0] % 1000000007 * B[0][1] % 1000000007 + A[0][1] % 1000000007 * B[1][1] % 1000000007) % 1000000007}), LL({ (A[1][0] % 1000000007 * B[0][0] % 1000000007 + A[1][1] % 1000000007 * B[1][0] % 1000000007) % 1000000007, (A[1][0] % 1000000007 * B[0][1] % 1000000007 + A[1][1] % 1000000007 * B[1][1] % 1000000007) % 1000000007}) }); return res; } vector divide_and_conquer(long long n) { if (n == 1) return vt; vector res = divide_and_conquer(n / 2); vector square_res = multiply_matrix(res, res); //n 2 ȳ, Ȧ϶ if (n % 2) return multiply_matrix(square_res, vt); return square_res; } int main() { long long n; cin >> n; if (n == 0) { cout << "0"; return 0; } vector res = divide_and_conquer(n); cout << res[0][1] % 1000000007; } ================================================ FILE: BOJ/11478.서로 다른 부분 문자열의 개수/6047198844.py ================================================ from itertools import combinations S = input() result = set() for i in range(1, len(S) + 1): for j in range(len(S)-i+1): result.add(S[j:j+i]) print(len(result)) ================================================ FILE: BOJ/1149. RGB거리/rockmiin.py ================================================ n= int(input()) cost= [] for i in range(n): cost.append(list(map(int, input().split()))) dp= [[0]* 3 for _ in range(n)] dp[0][0]= cost[0][0] dp[0][1]= cost[0][1] dp[0][2]= cost[0][2] for i in range(1, n): dp[i][0]= cost[i][0]+ min(dp[i-1][1], dp[i-1][2]) dp[i][1]= cost[i][1]+ min(dp[i-1][0], dp[i-1][2]) dp[i][2]= cost[i][2]+ min(dp[i-1][0], dp[i-1][1]) print(min(dp[n-1])) ================================================ FILE: BOJ/11502.세 개의 소수 문제/6047198844.py ================================================ import sys from itertools import combinations_with_replacement def get_primes(): is_prime = [True for _ in range(1001)] is_prime[0] = is_prime[1] = False for i in range(1001): if is_prime[i]: for j in range(i + i, 1001, i): is_prime[j] = False primes = [i for i in range(1001) if is_prime[i]] return primes T = int(sys.stdin.readline().rstrip()) tests = [int(sys.stdin.readline().rstrip()) for _ in range(T)] sols = dict() primes = get_primes() for s in ç(primes, 3): acc = sum(s) if acc in tests: sols[acc] = s for test in tests: if test in sols: print(' '.join(map(str, sols[test]))) else: print(0) ================================================ FILE: BOJ/11505.구간 곱 구하기/6047198844.py ================================================ import sys def init(sgi, left, right): # 리프 노드인가 if left == right: segment_tree[sgi] = arr[left] # 부모노드는 자식 노드의 곱이다. else: mid = (left + right) // 2 segment_tree[sgi] = init(sgi * 2, left, mid) * init(sgi * 2 + 1, mid + 1, right) % 1000000007 return segment_tree[sgi] def update(sgi, left, right, i, new_value): # 범위를 벗어남 if i < left or right < i: return # 리프노드 if left == right: segment_tree[sgi] = new_value return # 현재 노드는 left ~ right 의 범위를 가진다. # 중간을 기준으로, i가 mid 보다 작거나 같으면 왼쪽 크면 오른쪽 자식이다. mid = (left + right) // 2 update(2 * sgi, left, mid, i, new_value) update(2 * sgi + 1, mid + 1, right, i, new_value) segment_tree[sgi] = segment_tree[sgi*2] * segment_tree[sgi*2+1] % 1000000007 # 현재 sgi(세그먼트 인덱스) 의 범위는 left, right 이다. 우리는 begin, end 범위의 인덱스의 곱을 찾고 싶다. def multiply(sgi, left, right, begin, end): # 현재 범위가 속하지 않는 범위라면? if left > end or right < begin: return 1 # 현재 범위가 완전히 속해 있다면? if begin <= left and right <= end: return segment_tree[sgi] # 현재 범위가 걸쳐있다면? # 왼쪽 / 오른쪽 곱을 리턴한다. mid = (left + right) // 2 return (multiply(2 * sgi, left, mid, begin, end) * multiply(2 * sgi + 1, mid + 1, right, begin, end)) % 1000000007 N, M, K = map(int, sys.stdin.readline().split()) segment_tree = [0 for _ in range(N * 4 + 1)] arr = [0] + [int(sys.stdin.readline()) for _ in range(N)] init(1, 1, N) for _ in range(M + K): a, b, c = map(int, sys.stdin.readline().split()) if a == 1: update(1, 1, N, b, c) else: print(multiply(1, 1, N, b, c)) ================================================ FILE: BOJ/11508.2+1 세일/6047198844.py ================================================ N = int(input()) milks = list() for _ in range(N): milks.append(int(input())) milks.sort(reverse=True) print(sum([milk for idx, milk in enumerate(milks) if idx % 3 != 2])) ================================================ FILE: BOJ/1152.단어의 개수/6047198844.py ================================================ # 문제 # 영어 대소문자와 공백으로 이루어진 문자열이 주어진다. 이 문자열에는 몇 개의 단어가 있을까? 이를 구하는 프로그램을 작성하시오. 단, 한 단어가 여러 번 등장하면 등장한 횟수만큼 모두 세어야 한다. # # 입력 # 첫 줄에 영어 대소문자와 공백으로 이루어진 문자열이 주어진다. 이 문자열의 길이는 1,000,000을 넘지 않는다. 단어는 공백 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다. 또한 문자열은 공백으로 시작하거나 끝날 수 있다. # # 출력 # 첫째 줄에 단어의 개수를 출력한다. import sys print(len(sys.stdin.readline().strip().split())) ================================================ FILE: BOJ/11559.Puyo Puyo/6047198844.py ================================================ # 문제 # 뿌요뿌요의 룰은 다음과 같다. # 필드에 여러 가지 색깔의 뿌요를 놓는다. 뿌요는 중력의 영향을 받아 아래에 바닥이나 다른 뿌요가 나올 때까지 아래로 떨어진다. # 뿌요를 놓고 난 후, 같은 색 뿌요가 4개 이상 상하좌우로 연결되어 있으면 연결된 같은 색 뿌요들이 한꺼번에 없어진다. 이때 1연쇄가 시작된다. # 뿌요들이 없어지고 나서 위에 다른 뿌요들이 있다면, 역시 중력의 영향을 받아 차례대로 아래로 떨어지게 된다. # 아래로 떨어지고 나서 다시 같은 색의 뿌요들이 4개 이상 모이게 되면 또 터지게 되는데, 터진 후 뿌요들이 내려오고 다시 터짐을 반복할 때마다 1연쇄씩 늘어난다. # 터질 수 있는 뿌요가 여러 그룹이 있다면 동시에 터져야 하고 여러 그룹이 터지더라도 한번의 연쇄가 추가된다. # 이 게임은 1:1로 붙는 대전게임이라 잘 쌓는 것도 중요하지만, 상대방이 터뜨린다면 연쇄가 몇 번이 될지 바로 파악할 수 있는 능력도 필요하다. # 상대방의 필드가 주어졌을 때, 연쇄가 몇 번 연속으로 일어날지 계산하여 남규를 도와주자! # # 입력 # 총 12개의 줄에 필드의 정보가 주어지며, 각 줄에는 6개의 문자가 있다. # 이때 .은 빈공간이고 .이 아닌것은 각각의 색깔의 뿌요를 나타낸다. # R은 빨강, G는 초록, B는 파랑, P는 보라, Y는 노랑이다. # # 입력으로 주어지는 필드는 뿌요들이 전부 아래로 떨어진 뒤의 상태이다. 즉, 뿌요 아래에 빈 칸이 있는 경우는 없다. # # 출력 # 현재 주어진 상황에서 몇연쇄가 되는지 출력한다. 하나도 터지지 않는다면 0을 출력한다. from collections import deque board = [list(input()) for _ in range(12)] res = 0 while True: # 연속이 있는지 검사. visited = set() # 연쇄가 있어서 pop 했는지 여부 is_pop = False for iy in range(12): for ix in range(6): if board[iy][ix] != '.' and (iy, ix) not in visited: group = list() Q = deque() group.append((iy, ix)) Q.append((iy, ix)) visited.add((iy, ix)) # iy, ix 와 연결되어있는 색깔을 모두 찾는다. while Q: y, x = Q.popleft() for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny = y + dy nx = x + dx if 0 <= ny < 12 and 0 <= nx < 6 and (ny, nx) not in visited and board[ny][nx] == board[iy][ix]: group.append((ny, nx)) Q.append((ny, nx)) visited.add((ny, nx)) # 연결된 뿌요의 숫자가 4개 이상이면 터트린다. (점으로 만든다.) # 터트렸으므로 flag 값을 True 로 한다. if len(group) >= 4: while group: pop_y, pop_x = group.pop() board[pop_y][pop_x] = '.' is_pop = True if not is_pop: break # 내린다. for x, column in enumerate(zip(*board)): new_column = list(filter(lambda i: i != '.', column))[::-1] if new_column: for y in range(len(new_column)): board[11 - y][x] = new_column[y] for y in range(len(new_column), len(column)): board[11 - y][x] = '.' res += 1 print(res) ================================================ FILE: BOJ/11561.징검다리/6047198844.py ================================================ import sys T = int(sys.stdin.readline()) def sol(N): # N에 도달할수있는가. # lower_bound를 찾는다. l = 1 r = 10 ** 10 while l < r: mid = (l + r) // 2 if (mid ** 2 + mid) // 2 <= N: l = mid + 1 else: r = mid return r - 1 for _ in range(T): print(sol(int(sys.stdin.readline()))) ================================================ FILE: BOJ/11562.백양로 브레이크/6047198844.py ================================================ import sys n, m = map(int, sys.stdin.readline().split()) roads = [tuple(map(int, sys.stdin.readline().split())) for _ in range(m)] buildings = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): for j in range(n): if i != j: buildings[i][j] = 987654321 for u, v, b in roads: buildings[u - 1][v - 1] = 0 buildings[v - 1][u - 1] = int(b == 0) for k in range(n): for i in range(n): for j in range(n): buildings[i][j] = min(buildings[i][j], buildings[i][k] + buildings[k][j]) k = int(sys.stdin.readline()) for _ in range(k): s, e = map(int, sys.stdin.readline().split()) print(buildings[s-1][e-1]) ================================================ FILE: BOJ/1157.단어 공부/6047198844.py ================================================ frequency = [0]*26 s = input().upper() res = [] for _ in range(26): res.append(s.count(chr(_+ord('A')))) print(chr(res.index(max(res))+ord('A'))) if res.count(max(res)) == 1 else print('?') ================================================ FILE: BOJ/1159.농구 경기/6047198844.py ================================================ # 문제 # # 상근이는 내일 경기에 나설 선발 명단을 작성해야 한다. # 누가 선발인지 기억하기 쉽게 하기 위해 성의 첫 글자가 같은 선수 5명을 선발하려고 한다. 만약, 성의 첫 글자가 같은 선수가 5명보다 적다면, 상근이는 내일 있을 친선 경기를 기권하려고 한다. # 상근이는 내일 경기를 위해 뽑을 수 있는 성의 첫 글자를 모두 구해보려고 한다. # # 입력 # 첫째 줄에 선수의 수 N (1 ≤ N ≤ 150)이 주어진다. 다음 N개 줄에는 각 선수의 성이 주어진다. (성은 알파벳 소문자로만 이루어져 있고, 최대 30글자이다) # # 출력 # 상근이가 선수 다섯 명을 선발할 수 없는 경우에는 "PREDAJA" (따옴표 없이)를 출력한다. # 선발할 수 있는 경우에는 가능한 성의 첫 글자를 사전순으로 공백없이 모두 출력한다. from collections import Counter N = int(input()) player_first_names = Counter([input()[0] for _ in range(N)]) players = sorted([name for name in player_first_names if player_first_names[name] >= 5]) print(''.join(players)) if players else print("PREDAJA") ================================================ FILE: BOJ/11653.소인수분해/6047198844.cpp ================================================ #include #include #include using namespace std; int main() { int N; vector v(10000001); cin >> N; v[1] = 1; for (int i = 2; i <= 3162; i++) { if (!v[i]) for (int j = i + i; j <= N; j += i) v[j] = 1; } int prime; do { for (int i = 2;i<=N; i++) { if (!v[i]) if (!(N % i)) { cout << i << "\n"; prime = i; break; } } } while (N /= prime); } ================================================ FILE: BOJ/11653.소인수분해/6047198844.py ================================================ prime = [True] * 10000001 # 소수이면 True def sieve(): prime[1] = False for n in range(2, 10000001): if prime[n]: # n 가 소수인경우 for m in range(n + n, 10000001, n): prime[m] = False sieve() N = int(input()) for i in range(2, N+1): if(N == 1): break if prime[i]: while not N % i: N /= i print(i) ================================================ FILE: BOJ/11657.타임머신/6047198844.cpp ================================================ #include #include #include #define P pair #define INF INT_MAX #define LL long long using namespace std; void Bellman_ford(int N,vector > &adj) { vector dist(N, INF); dist[0] = 0; bool infinite_loop = false; for (int i = 0; i < N; i++) { for (int u = 0; u < N; u++) { for (auto p : adj[u]) { int v = p.first; LL cost = p.second; if (dist[u] != INF && dist[v] > dist[u] + cost) { dist[v] = dist[u] + cost; if (i == N - 1) infinite_loop = true; } } } } if (infinite_loop) { cout << -1; return; } for (int i = 1; i < N; i++) { if (dist[i] == INF) cout << "-1"; else cout << dist[i]; cout << "\n"; } } int main() { int N, M; cin >> N >> M; vector > adj(N); int A, B, C; for (int i = 0; i < M; i++) { cin >> A >> B >> C; // -> -> adj[A - 1].push_back({ B - 1,C }); } Bellman_ford(N, adj); } ================================================ FILE: BOJ/1166.선물/6047198844.py ================================================ # 민식이는 아이들에게 선물할 같은 크기의 작은 박스를 N개 가지고 있다. # 모든 작은 박스는 "정육면체"이고, 크기는 A × A × A 이다. # 민식이는 이 작은 박스를 크기가 L × W × H 인 직육면체 박스에 모두 넣으려고 한다. # 모든 작은 박스는 큰 박스 안에 있어야 하고, 작은 박스의 변은 큰 박스의 변과 평행해야 한다. # # N, L, W, H가 주어질 때, "가능한 A의 최댓값을 찾는 프로그램"을 작성하시오. N, L, W, H = map(int, input().split()) # 최소값? begin = 0 # 최대값 / min 아닌가?....... end = min(L, W, H) for _ in range(10000): mid = (begin + end) / 2 box_N = (L // mid) * (W // mid) * (H // mid) if N <= box_N: begin = mid else: end = mid print("%.10f" %(end)) ================================================ FILE: BOJ/11660.구간 합 구하기 5/6047198844.py ================================================ import sys N, M = map(int, sys.stdin.readline().split()) table = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] prefix_sum = [0] for y in range(N): for x in range(N): prefix_sum.append(table[y][x] + prefix_sum[-1]) for i in range(len(prefix_sum)): print(i, prefix_sum[i]) print() for _ in range(M): i, j, y, x = map(lambda i: int(i) - 1, sys.stdin.readline().split()) k = prefix_sum[y * N + x] - prefix_sum[i * N + j] + table[j-1][i-1] print(prefix_sum[y * N + x]) print(prefix_sum[i * N + j]) print(table[j-1][i-1]) print(k) print() ================================================ FILE: BOJ/11725.트리의 부모 찾기/input_data.md ================================================ ex 01 7 1 6 6 3 3 5 4 1 2 4 4 7 out 4 6 1 3 1 4 ex 02 12 1 2 1 3 2 4 3 5 3 6 4 7 4 8 5 9 5 10 6 11 6 12 minimum 2 1 2 out 1 루트에만 10 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 out 1 1 1 1 1 1 1 1 1 10 1 1 2 3 3 4 4 5 5 6 6 7 7 8 9 10 10 9 ex 03 5 1 4 4 5 5 3 3 2 out 3 5 1 4 ================================================ FILE: BOJ/11725.트리의 부모 찾기/sAp00n.py ================================================ from sys import stdin from collections import deque def bfs_searching(graph): stack = deque() visit = {} memo = {1: None} for node in graph[1]: stack.append(node) memo[node] = 1 while len(stack) > 0: searching_node = stack.popleft() #print(f'searching_node : {searching_node}\nvisit : {visit}\nstack: {stack}') if searching_node in visit: continue visit[searching_node] = True for node in graph[searching_node]: if node not in memo: memo[node] = searching_node #print(f'searching_node : {searching_node}\nnode: {node}\nmemo : {memo}') if node in visit: continue stack.append(node) return memo number_of_nodes = int(stdin.readline()) graph = {1: []} for connection in range(number_of_nodes - 1): node01, node02 = list(map(int, stdin.readline().split())) if node01 not in graph: graph[node01] = [] if node02 not in graph: graph[node02] = [] graph[node01].append(node02) graph[node02].append(node01) #print(f'graph : {graph}') parent_node = bfs_searching(graph) #print(parent_node) for i in range(2, number_of_nodes + 1): print(parent_node[i]) ================================================ FILE: BOJ/11728.배열 합치기/6047198844.cpp ================================================ #include using namespace std; int main() { int N, M; cin >> N >> M; int* A = new int[N]; int* B = new int[M]; int* C = new int[N + M]; for (int i = 0; i < N; i++) scanf("%d", &A[i]); for (int i = 0; i < M; i++) scanf("%d", &B[i]); int a = 0, b = 0, c = 0; while (a < N && b < M) if (A[a] >= B[b]) C[c++] = B[b++]; else C[c++] = A[a++]; while (a < N) C[c++] = A[a++]; while (b < M) C[c++] = B[b++]; for (int i = 0; i < N + M; i++) printf("%d ", C[i]); } ================================================ FILE: BOJ/11729.하노이 탑 이동 순서/6047198844.py ================================================ # 1에 있는 맨밑을 제외한 모든것들을 2에 옮긴다. # 1에 있는 하나를 3에 옮긴다. # 2에 있는 모든것들을 3에 옮긴다. # n개의 ring을 FROM에서 TO로 옮긴다. FROM / TO / OTHERS # from : 1 to : 3 others : 2 route = [] def move_ring(n: int, source: int, destination: int, other: int): if n==0: return 0 res = 0 res += move_ring(n - 1, source, other, destination) route.append((source, destination)) res += 1 res += move_ring(n - 1, other, destination, source) return res n = int(input()) print(move_ring(n, 1, 3, 2)) for i in route: print(i[0], i[1]) ================================================ FILE: BOJ/11779.최소비용 구하기 2/6047198844.py ================================================ # 문제 # n(1≤n≤1,000)개의 도시가 있다. # 한 도시에서 출발하여 다른 도시에 도착하는 m(1≤m≤100,000)개의 버스가 있다. -> 다익스트라 알고리즘 # 우리는 A번째 도시에서 B번째 도시까지 가는데 드는 버스 비용을 최소화 시키려고 한다. 그러면 A번째 도시에서 B번째 도시 까지 가는데 드는 최소비용과 경로를 출력하여라. 항상 시작점에서 도착점으로의 경로가 존재한다. # # 입력 # 첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. # 먼저 처음에는 그 버스의 출발 도시의 번호가 주어진다. 그리고 그 다음에는 도착지의 도시 번호가 주어지고 또 그 버스 비용이 주어진다. 버스 비용은 0보다 크거나 같고, 100,000보다 작은 정수이다. # # 그리고 m+3째 줄에는 우리가 구하고자 하는 구간 출발점의 도시번호와 도착점의 도시번호가 주어진다. # # 출력 # 첫째 줄에 출발 도시에서 도착 도시까지 가는데 드는 최소 비용을 출력한다. # # 둘째 줄에는 그러한 최소 비용을 갖는 경로에 포함되어있는 도시의 개수를 출력한다. 출발 도시와 도착 도시도 포함한다. # # 셋째 줄에는 최소 비용을 갖는 경로를 방문하는 도시 순서대로 출력한다. # # 풀이 # 한 정점에서 다른 정점까지가는데 드는 최소비용을 구할때도 다익스트라 알고리즘을 이용한다. import heapq import sys from collections import defaultdict n = int(sys.stdin.readline()) m = int(sys.stdin.readline()) edges = defaultdict(list) INF = 987654321 # 간선 입력 for _ in range(m): i, j, cost = map(int, input().split()) edges[i].append((cost, j)) depart, arrive = map(int, input().split()) # 초기화. 출발 정점을 제외한 곳은 알수가 없다 -> 무한 distances = [INF for _ in range(n + 1)] distances[depart] = 0 routes = [-1 for _ in range(n + 1)] PQ = [] # cost , 정점 heapq.heappush(PQ, (0, depart)) # heap 이 종료될때까지 while PQ: cost, v = heapq.heappop(PQ) # 갱신되었는지? 현재값이 최적인지? if distances[v] != cost: continue # 최적값으로 갱신이 가능한지 확인한다. # 갱신 가능하다면. 경로와 갱신값을 PQ에 넣는다. for c, w in edges[v]: if distances[w] > cost + c: distances[w] = cost + c routes[w] = v heapq.heappush(PQ, (distances[w], w)) print(distances[arrive]) res = [] root = arrive while root != -1: res.append(root) root = routes[root] print(len(res)) for i in res[::-1]: print(i, end=' ') ================================================ FILE: BOJ/1181.단어 정렬/6047198844.cpp ================================================ #include #include #include #include using namespace std; bool cmp(const string a, const string b) { if (a.size() != b.size()) return a.size() < b.size(); return a < b; } int main() { int N; cin >> N; vector arr; string s; for (int i = 0; i < N; i++) { cin >> s; arr.push_back(s); } sort(arr.begin(), arr.end(), cmp); arr.erase(unique(arr.begin(), arr.end()), arr.end()); for (int i = 0; i < arr.size(); i++) cout << arr[i] << "\n"; } ================================================ FILE: BOJ/1181.단어 정렬/rockmiin.py ================================================ n= int(input()) arr=[] for i in range(n): arr.append(input()) arr=set(arr) answer=[] for i in arr: answer.append([len(i), i]) # 인덱스를 단어의 길이인 배열 answer에 길이마다 저장 answer.sort() # sort()는 앞 조건이 같으면 뒤 조건으로 정렬한다 for i in answer: print(i[1]) ================================================ FILE: BOJ/1182.부분수열의 합/6047198844.py ================================================ from itertools import combinations #idx를 뽑거나 뽑지 않는 경우의수. #N개를 뽑았을때 합이 S면 True, 아니면 False반환 #idx 현재 판단의 기준이되는 idx / 목표하는 합 S / 누적합 partial_sum def partial_sequence(idx:int, N:int, S:int, partial_sum:int, sequence:list): if N < 0: return 0 if idx == len(sequence): if partial_sum == S and N == 0: return 1 return 0 res = 0 res += partial_sequence(idx+1, N-1, S, partial_sum+sequence[idx], sequence) res += partial_sequence(idx+1, N, S, partial_sum, sequence) return res N, S = map(int, input().split()) sequence = list(map(int, input().split())) res = 0 for _ in range(1,N+1): res += partial_sequence(0, _, S, 0, sequence) print(res) ================================================ FILE: BOJ/11866.요세푸스 문제 0/6047198844.cpp ================================================ #include #include using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int N,K; cin >> N >> K; queue q; for (int i = 1; i <= N; i++) q.push(i); cout << "<"; while (1) { for (int i = 0; i < K-1; i++) { q.push(q.front()); q.pop(); } cout << q.front(); q.pop(); if (!q.empty()) { cout << ", "; } else { cout << ">"; break; } } } ================================================ FILE: BOJ/1188.음식 평론가/6047198844.py ================================================ def gcd(a, b): if a % b == 0: return b return gcd(b, a % b) n, m = map(int, input().split()) print(m - gcd(n, m)) ================================================ FILE: BOJ/11942.고려대는 사랑입니다/6047198844.py ================================================ print("고려대학교") ================================================ FILE: BOJ/11942.고려대는 사랑입니다./6047198844.py ================================================ print("고려대학교") ================================================ FILE: BOJ/11943.파일 옮기기/6047198844.py ================================================ import sys A, B = map(int, sys.stdin.readline().split()) C, D = map(int, sys.stdin.readline().split()) print(min(A+D, B+C)) ================================================ FILE: BOJ/11948.과목선택/6047198844.py ================================================ arr = [int(input()) for _ in range(6)] science = arr[:4] geo = arr[4:6] science.sort() geo.sort() print(sum(science[1:4], geo[1])) ================================================ FILE: BOJ/1197.최소 스패닝 트리/6047198844.py ================================================ # 문제 # 그래프가 주어졌을 때, 그 그래프의 최소 스패닝 트리를 구하는 프로그램을 작성하시오. # # 최소 스패닝 트리는, 주어진 그래프의 모든 정점들을 연결하는 부분 그래프 중에서 그 가중치의 합이 최소인 트리를 말한다. # # 입력 # 첫째 줄에 정점의 개수 V(1 ≤ V ≤ 10,000)와 간선의 개수 E(1 ≤ E ≤ 100,000)가 주어진다. 다음 E개의 줄에는 각 간선에 대한 정보를 나타내는 세 정수 A, B, C가 주어진다. # 이는 A번 정점과 B번 정점이 가중치 C인 간선으로 연결되어 있다는 의미이다. C는 음수일 수도 있으며, 절댓값이 1,000,000을 넘지 않는다. # # 그래프의 정점은 1번부터 V번까지 번호가 매겨져 있고, 임의의 두 정점 사이에 경로가 있다. 최소 스패닝 트리의 가중치가 -2,147,483,648보다 크거나 같고, 2,147,483,647보다 작거나 같은 데이터만 입력으로 주어진다. # # 출력 # 첫째 줄에 최소 스패닝 트리의 가중치를 출력한다. import heapq import sys # union-find 로 스패닝트리를 만들자 # A와 B를 합친다. def union(A, B): PA = find(A) PB = find(B) if PA == PB: return False P[PB] = PA return True def find(A): if P[A] == A: return A P[A] = find(P[A]) return P[A] V, E = map(int, sys.stdin.readline().split()) P = [i for i in range(V + 1)] Q = [] for _ in range(E): A, B, C = map(int, sys.stdin.readline().split()) heapq.heappush(Q, (C, A, B)) res = 0 while Q: C, A, B = heapq.heappop(Q) if union(A, B): res += C print(res) ================================================ FILE: BOJ/1199.오일러 회로/6047198844.cpp ================================================ ================================================ FILE: BOJ/1199.오일러 회로/sAp00n.py ================================================ from sys import stdin global N N = int(stdin.readline()) def DFS(start_node, graph): visit_list = [] dfs_visit(start_node, visit_list, graph) return visit_list def dfs_visit(node, visit_list, graph): current_ad_mat = graph[node - 1] if sum(current_ad_mat) == 0: visit_list.append(node) for idx in range(N): if current_ad_mat[idx] >= 1: graph[node - 1][idx] -= 1 graph[idx][node - 1] -= 1 dfs_visit(idx + 1, visit_list, graph) if len(visit_list) == 0: visit_list.append(node) elif visit_list[-1] != node: visit_list.append(node) def solution(): ad_mat = [] state = True for _ in range(N): node_admat = list(map(int, stdin.readline().split())) if sum(node_admat) % 2 == 1: state = False ad_mat += [node_admat] visit_list = DFS(1, ad_mat) if not state: print(-1) return for j in ad_mat: if sum(j) > 0: print(-1) return print(str(visit_list)[1:-1]) solution() ================================================ FILE: BOJ/12015.가장 긴 증가하는 부분 수열 2/6047198844.py ================================================ # 문제 # 수열 A가 주어졌을 때, 가장 긴 증가하는 부분 수열을 구하는 프로그램을 작성하시오. # # 예를 들어, 수열 A = {10, 20, 10, 30, 20, 50} 인 경우에 가장 긴 증가하는 부분 수열은 A = {10, 20, 10, 30, 20, 50} 이고, 길이는 4이다. # # 입력 # 첫째 줄에 수열 A의 크기 N (1 ≤ N ≤ 1,000,000)이 주어진다. # # 둘째 줄에는 수열 A를 이루고 있는 Ai가 주어진다. (1 ≤ Ai ≤ 1,000,000) # # 출력 # 첫째 줄에 수열 A의 가장 긴 증가하는 부분 수열의 길이를 출력한다. from bisect import bisect_left N = int(input()) A = list(map(int, input().split())) arr = [A[0]] for e in A: idx = bisect_left(arr, e) if idx >= len(arr): arr.append(e) else: arr[idx] = e print(len(arr)) ================================================ FILE: BOJ/1202.보석 도둑/6047198844.py ================================================ import heapq import sys N, K = map(int, sys.stdin.readline().split()) diamonds = [tuple(map(int, sys.stdin.readline().split()))for _ in range(N)] bags = [int(sys.stdin.readline()) for _ in range(K)] # 최대한 작은 가방을 가지고, 최대한 비싼 다이아몬드를 담는다. diamonds.sort() bags.sort() # 임시큐. Q = [] diamond_idx = 0 res = 0 for bag in bags: # 허용되는 다이아몬드를 담는다. 이때 diamond_idx 를 유지시킨다. # Q 는 항상 가장 값어치 있는 다이아몬드를 가리킨다. while diamond_idx < N and diamonds[diamond_idx][0] <= bag: heapq.heappush(Q, (-diamonds[diamond_idx][1], diamonds[diamond_idx][1])) diamond_idx += 1 if Q: res += heapq.heappop(Q)[1] # Q 의 맨위에는 가장 값어치 있는 다이아몬드가 있다. # 이 다이아몬드는 현재 가방의 무게에 맞는다. # 근거 # 이전의 가방이 낮은 무게를 허용하는 가방이기 때문에 현재가방은 당연히 클수밖에 없다. # 우선순위큐의 정의에 의해서 가장 값어치있음이 보장된다. print(res) ================================================ FILE: BOJ/1208.부분수열의 합 2/6047198844.py ================================================ from collections import defaultdict N, S = map(int, input().split()) arr = list(map(int, input().split())) # meet in the middle # N = 40 -> 20 두개로 쪼개면 시간 복잡도가 현저히 낮아진다. # 2^40 -> 2^20 + 2^20 half = N // 2 arr1 = arr[:half] arr2 = arr[half:] arr1_dict = defaultdict(int) arr2_dict = defaultdict(int) # 1 ~ len 개 뽑는다. def func(arr, dict, idx, s): if idx == len(arr): dict[s] += 1 return # 뽑음 func(arr, dict, idx + 1, s + arr[idx]) # 뽑지 않음 func(arr, dict, idx + 1, s) func(arr1, arr1_dict, 0, 0) func(arr2, arr2_dict, 0, 0) res = 0 for key in arr1_dict: # 공집합 포함한다. res += arr1_dict[key] * arr2_dict[S-key] if S == 0: # 공집합 * 공집합도 정답에 포함되므로 1 뺀다. res -= 1 print(res) ================================================ FILE: BOJ/12100.2048 (Easy)/6047198844.py ================================================ # 4진수로 변경한다. 5번의 행동에 대해 반환한다. import copy def convert_binary_quaternary(binary_command): quaternary_command = [] for _ in range(5): quaternary_command.append(binary_command & 3) binary_command = binary_command >> 2 return quaternary_command # 명령이 주어진대로(상하좌우) 움직인다. # 명령, board # 움직인후 최대값을 반환한다. def move_up(board): for y in range(len(board)): for x in range(len(board[0])): #현재값이 0이 아니라면 if board[y][x] != 0: #이전값이 범위에 있고 0이라면 ny = y #이동 가능한 위치를 탐색한다. while ny - 1 >= 0 and board[ny - 1][x] == 0: ny -= 1 #이동이 이루어 진다면 if ny != y: board[ny][x] = board[y][x] board[y][x] = 0 return def move_down(board): for y in range(len(board)-1,-1,-1): for x in range(len(board[0])): #현재값이 0이 아니라면 if board[y][x] != 0: #이전값이 범위에 있고 0이라면 ny = y #이동 가능한 위치를 탐색한다. while ny + 1 < N and board[ny + 1][x] == 0: ny += 1 #이동이 이루어 진다면 if ny != y: board[ny][x] = board[y][x] board[y][x] = 0 return def move_left(board): for x in range(len(board[0])): for y in range(len(board)): #현재값이 0이 아니라면 if board[y][x] != 0: #이전값이 범위에 있고 0이라면 nx = x #이동 가능한 위치를 탐색한다. while nx - 1 >= 0 and board[y][nx - 1] == 0: nx -= 1 #이동이 이루어 진다면 if nx != x: board[y][nx] = board[y][x] board[y][x] = 0 return def move_right(board): for x in range(len(board[0]) - 1, -1, -1): for y in range(len(board)): # 현재값이 0이 아니라면 if board[y][x] != 0: # 이전값이 범위에 있고 0이라면 nx = x # 이동 가능한 위치를 탐색한다. while nx + 1 < N and board[y][nx + 1] == 0: nx += 1 # 이동이 이루어 진다면 if nx != x: board[y][nx] = board[y][x] board[y][x] = 0 return def add_up(board): for y in range(1, len(board)): for x in range(len(board[0])): if board[y][x] != 0 and board[y-1][x] == board[y][x]: board[y-1][x] += board[y][x] board[y][x] = 0 def add_down(board): for y in range(len(board) - 2, -1, -1): for x in range(len(board[0])): if board[y][x] != 0 and board[y + 1][x] == board[y][x]: board[y + 1][x] += board[y][x] board[y][x] = 0 def add_left(board): for x in range(1, len(board[0])): for y in range(len(board)): if board[y][x] != 0 and board[y][x - 1] == board[y][x]: board[y][x - 1] += board[y][x] board[y][x] = 0 def add_right(board): for x in range(len(board[0]) - 2, -1, -1): for y in range(len(board)): if board[y][x] != 0 and board[y][x + 1] == board[y][x]: board[y][x + 1] += board[y][x] board[y][x] = 0 def move_board(commands, board): for command in commands: # 상 # 한칸씩 올려야 한다. if command == 0: pass #숫자를 모두 올린다. 덧샘 없이. move_up(board) add_up(board) move_up(board) # 하 # 한칸씩 내려야 한다. elif command == 1: #숫자를 모두 내린다. 덧샘 없이 move_down(board) add_down(board) move_down(board) # 좌 elif command == 2: move_left(board) add_left(board) move_left(board) # 우 else: move_right(board) add_right(board) move_right(board) return max(map(max, board)) N = int(input()) board = [list(map(int, input().split())) for _ in range(N)] #모든 경우의 수에 대해 생각한다. #4^5 ==> 2^10 res = -1 for binary_command in range(1 << 10): quaternary_command = convert_binary_quaternary(binary_command) res = max(res, move_board(quaternary_command, copy.deepcopy(board))) print(res) # 2차원배열에서 max값을 구하는 법 # https://devbull.xyz/python-2caweon-baeyeolyi-coedaegabs-coesogabs-cajgi/ ================================================ FILE: BOJ/1213.팰린드롬 만들기/6047198844.py ================================================ from collections import Counter s = input() res = '' even_alpha = '' for alpha, cnt in sorted(Counter(s).items()): res += alpha * (cnt // 2) if cnt % 2 != 0: if even_alpha == '': even_alpha = alpha else: print("I'm Sorry Hansoo") break else: print(res+even_alpha+res[::-1]) ================================================ FILE: BOJ/1219.오민식의 고민/6047198844.cpp ================================================ #include #include #include #include #define INF INT_MIN using namespace std; // u v w // start_city에서 v까지 가는 비용 vector dist(100, INF); bool bellman_ford(int start_city, int end_city, vector >>& cost, vector & earn) { int N = earn.size(); vector visit(N, false); queue vertex; dist[start_city] = earn[start_city]; for (int i = 0; i < N; i++) { for (int v = 0; v < N; v++) { for (auto p : cost[v]) { int w = p.first; int v_w_cost = p.second + earn[w]; if (dist[v] != INF && (dist[w] < dist[v] + v_w_cost)) { dist[w] = dist[v] + v_w_cost; if (i == N - 1) { if (!visit[w]) { if (w == end_city) return false; visit[w] = true; vertex.push(w); while (!vertex.empty()) { int check_vertex = vertex.front(); vertex.pop(); for (auto q : cost[check_vertex]) { if (!visit[q.first]) { if (q.first == end_city) return false; visit[q.first] = true; vertex.push(q.first); } } } } } } } } } return true; } int main() { int N, start_city, end_city, edge_num; cin >> N >> start_city >> end_city >> edge_num; vector >> cost(N); int u, v, k; //비용을 입력받는다. while (edge_num--) { cin >> u >> v >> k; cost[u].push_back({ v,-k }); } vector earn(N); for (int i = 0; i < N; i++) cin >> earn[i]; bool res = bellman_ford(start_city, end_city, cost, earn); if (res) { if (dist[end_city] == INF) cout << "gg"; else cout << dist[end_city]; return 0; } cout << "Gee"; } ================================================ FILE: BOJ/1238.파티/6047198844.cpp ================================================ //다익스트라 알고리즘 1 //#include //#include //#include //#include //#define INF INT_MAX // //using namespace std; // //vector > edge[1001]; // //vector Dijkstra(int N, int K) { // priority_queue > pq; // vector dest(N + 1, INF); // dest[K] = 0; // pq.push({ 0, K }); // while (!pq.empty()) { // int cost = -pq.top().first; // int here = pq.top().second; // pq.pop(); // if (cost > dest[here]) // continue; // for (auto there : edge[here]) { // if (dest[there.first] > cost + there.second) { // dest[there.first] = cost + there.second; // pq.push({ -dest[there.first],there.first }); // } // } // } // return dest; //} // //int main() { // int N, M, X; // cin >> N >> M >> X; // int a, b, cost; // while (M--) { // cin >> a >> b >> cost; // edge[a].push_back({ b,cost }); // } // vector res[1001]; // for (int i = 1; i <= N; i++) { // res[i] = Dijkstra(N, i); // } // int r = -1; // for (int i = 1; i <= N; i++) { // if((res[X][i]!=INF)&&(res[i][X]!=INF)) // r = max(r, res[X][i] + res[i][X]); // } // cout << r; //} //다익스트라 알고리즘2 #include #include #include #include #define INF INT_MAX using namespace std; vector >> edge[2]; vector Dijkstra(int N, int K,int num) { priority_queue > pq; vector dest(N + 1, INF); dest[K] = 0; pq.push({ 0, K }); while (!pq.empty()) { int cost = -pq.top().first; int here = pq.top().second; pq.pop(); if (cost > dest[here]) continue; for (auto there : edge[num][here]) { if (dest[there.first] > cost + there.second) { dest[there.first] = cost + there.second; pq.push({ -dest[there.first],there.first }); } } } return dest; } int main() { int N, M, X; cin >> N >> M >> X; int a, b, cost; edge[0].resize(N + 1); edge[1].resize(N + 1); while (M--) { cin >> a >> b >> cost; edge[0][a].push_back({ b,cost }); edge[1][b].push_back({ a,cost }); } vector res[2]; res[0] = Dijkstra(N, X, 0); res[1] = Dijkstra(N, X, 1); int r = -1; for (int i = 1; i <= N; i++) { r = max(r, res[0][i] + res[1][i]); } cout << r; } ================================================ FILE: BOJ/1245.농장관리/input_data.md ================================================ ex 01 8 7 4 3 2 2 1 0 1 3 3 3 2 1 0 1 2 2 2 2 1 0 0 2 1 1 1 1 0 0 1 1 0 0 0 1 0 0 0 0 1 1 1 0 0 1 2 2 1 1 0 0 1 1 1 2 1 0 극단값 9 9 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 999 최소크기 2 2 2 0 0 2 세로로 긴 10 2 8 0 7 6 0 0 5 6 0 0 1 0 0 0 0 1 1 0 0 1 ================================================ FILE: BOJ/1245.농장관리/sAp00n.py ================================================ from sys import stdin from collections import deque def near_check(mat, node): global N_Column global M_Row i, j = node node_val = mat[j][i] return_list = [] if i == 0: if j == 0: search_list = [[i + 1, j], [i, j + 1], [i + 1, j + 1]] for near_node in search_list: near_i, near_j = near_node if near_i <= M_Row - 1 and near_j <= N_Column - 1: if mat[near_j][near_i] <= node_val: return_list.append([near_i, near_j]) elif j == N_Column - 1: search_list = [[i + 1, j], [i, j - 1], [i + 1, j - 1]] for near_node in search_list: near_i, near_j = near_node if near_i <= M_Row -1 and near_j <= N_Column - 1: if mat[near_j][near_i] <= node_val: return_list.append([near_i, near_j]) else: search_list = [[i, j - 1], [i + 1, j - 1], [i + 1, j], [i + 1, j + 1], [i, j + 1]] for near_node in search_list: near_i, near_j = near_node if near_i <= M_Row - 1 and near_j <= N_Column -1: if mat[near_j][near_i] <= node_val: return_list.append([near_i, near_j]) elif i == M_Row - 1: if j == 0: search_list = [[i - 1, j], [i - 1, j + 1], [i, j + 1]] for near_node in search_list: near_i, near_j = near_node if near_i <= M_Row - 1 and near_j <= N_Column - 1: if mat[near_j][near_i] <= node_val: return_list.append([near_i, near_j]) elif j == N_Column - 1: search_list = [[i - 1, j], [i - 1, j - 1], [i, j - 1]] for near_node in search_list: near_i, near_j = near_node if near_i <= M_Row - 1 and near_j <= N_Column - 1: if mat[near_j][near_i] <= node_val: return_list.append([near_i, near_j]) else: search_list = [[i, j - 1], [i - 1, j - 1], [i - 1, j], [i - 1, j + 1], [i, j + 1]] for near_node in search_list: near_i, near_j = near_node if near_i <= M_Row - 1 and near_j <= N_Column - 1: if mat[near_j][near_i] <= node_val: return_list.append([near_i, near_j]) else: if j == 0: search_list = [[i - 1, j], [i - 1, j + 1], [i, j + 1], [i + 1, j + 1], [i + 1, j]] for near_node in search_list: near_i, near_j = near_node if near_i <= M_Row - 1 and near_j <= N_Column -1: if mat[near_j][near_i] <= node_val: return_list.append([near_i, near_j]) elif j == N_Column - 1: search_list = [[i - 1, j], [i - 1, j - 1], [i, j - 1], [i + 1, j - 1], [i + 1, j]] for near_node in search_list: near_i, near_j = near_node if near_i <= M_Row - 1 and near_j <= N_Column - 1: if mat[near_j][near_i] <= node_val: return_list.append([near_i, near_j]) else: search_list = [[i - 1, j], [i - 1, j - 1], [i, j - 1], [i + 1, j - 1], [i + 1, j], [i + 1, j + 1], [i, j + 1], [i - 1, j + 1]] for near_node in search_list: near_i, near_j = near_node if near_i <= M_Row - 1 and near_j <= N_Column - 1: if mat[near_j][near_i] <= node_val: return_list.append([near_i, near_j]) return return_list N_Column, M_Row = list(map(int, stdin.readline().split())) if N_Column == 1 and M_Row == 1: if int(stdin.readline()) != 0: print(1) else: print(0) else: mat = [None] * N_Column num_of_Mount = 0 for j in range(N_Column): mat[j] = list(map(int, stdin.readline().split())) graph = {} max_val = 0 for j in range(N_Column): for i in range(M_Row): ele = mat[j][i] if ele not in graph: graph[ele] = [] graph[ele] += [[i, j]] max_val = max(max_val, ele) for value in range(max_val, 0, -1): same_value_node_list = graph.get(value) if same_value_node_list is None: continue for searching_node in same_value_node_list: searching_i, searching_j = searching_node if mat[searching_j][searching_i] == 0: continue stack = deque() stack.append([searching_i, searching_j]) while len(stack) > 0: current_node = stack.popleft() #print(f'stack: {stack}') current_i, current_j = current_node #print(f'current : ({current_i}, {current_j}) = {mat[current_j][current_i]}') if mat[current_j][current_i] == 0: continue near_node_list = near_check(mat, current_node) #print(f'near_node : {near_node_list}') for node in near_node_list: node_i, node_j = node if mat[node_j][node_i] == 0: continue if mat[current_j][current_i] >= mat[node_j][node_i]: stack.append(node) #print(f'append node : ({node_i}, {node_j})') mat[current_j][current_i] = 0 num_of_Mount += 1 '''for i in mat: print(i) print('\n')''' print(num_of_Mount) ================================================ FILE: BOJ/1247.부호/6047198844.py ================================================ import sys for _ in range(3): N = int(sys.stdin.readline()) s = 0 for _ in range(N): s += int(sys.stdin.readline()) if s == 0: print("0") elif s > 0: print("+") else: print("-") ================================================ FILE: BOJ/1251.단어 나누기/6047198844.py ================================================ word = input() res = list() for i in range(1, len(word) - 1): for j in range(1, len(word) - i): k = len(word) - i - j res.append(word[:i][::-1] + word[i:i+j][::-1] + word[i+j:i+j+k][::-1]) res.sort() print(res[0]) ================================================ FILE: BOJ/1260.DFS와 BFS/input_data.md ================================================ ex 01 4 5 1 1 2 1 3 1 4 2 4 3 4 result 1 2 4 3 1 2 3 4 ex02 5 5 3 5 4 5 2 1 2 3 4 3 1 result 3 1 2 5 4 3 1 4 2 5 ex03 1000 1 1000 999 1000 result 1000 999 1000 999 원형 10 10 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 1 result 1 2 3 4 5 6 7 8 9 10 1 2 10 3 9 4 8 5 7 6 0 connection 100 0 65 result 65 65 mannnnnnny 10 45 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 2 3 2 4 2 5 2 6 2 7 2 8 2 9 2 10 3 4 3 5 3 6 3 7 3 8 3 9 3 10 4 5 4 6 4 7 4 8 4 9 4 10 5 6 5 7 5 8 5 9 5 10 6 7 6 8 6 9 6 10 7 8 7 9 7 10 8 9 8 10 9 10 ================================================ FILE: BOJ/1260.DFS와 BFS/rockmiin.py ================================================ def dfs(v): print(v, end=" ") visited[v]= True for i in adj[v]: if not visited[i]: dfs(i) from collections import deque def bfs(v): q= deque([v]) while q: v= q.popleft() if not visited[v]: visited[v]= True print(v, end=" ") for i in adj[v]: if not visited[i]: q.append(i) # n, m, v 입력 n, m, v= map(int, input().split()) # 간선 입력 adj =[[] for i in range(n+1)] for i in range(m): x, y= map(int, input().split()) adj[x].append(y) adj[y].append(x) # print(adj) for i in adj: i.sort() # print(adj) visited= [False] * (n+1) dfs(v) print() visited= [False] * (n+1) bfs(v) ================================================ FILE: BOJ/1260.DFS와 BFS/s2uyeoii.c ================================================ #include #define MAX 1001 int metrix[MAX][MAX]; int visited[MAX * MAX]; //깊이 우선 탐색 void DFS (int v, int N) { printf("%d ", v); visited[v] = 1; for (int d = 1; d <= N; d++) { if (!visited[d] && metrix[v][d]) { DFS(d, N); } } } //너비 우선 탐색 void BFS (int v, int N) { int front = -1, rear = -1; int queue[MAX * MAX] = { 0 }; rear++; queue[rear] = v; visited[v] = 1; printf("%d ", v); while (front < rear) { front++; int nextV = queue[front]; for (int d = 1; d <= N; d++) { if (!visited[d] && metrix[nextV][d]) { rear++; visited[d] = 1; queue[rear] = d; printf("%d ", d); } } } } void init (int N) { printf("\n"); for (int i = 1; i <= N; i++) { visited[i] = 0; } } int main(void) { int N = 0; int M = 0; int V = 0; scanf("%d %d %d", &N, &M, &V); for (int i = 0; i < M; i++) { int s = 0; int d = 0; scanf("%d %d", &s, &d); metrix[s][d] = 1; metrix[d][s] = 1; } DFS(V, N); init(N); BFS(V, N); return 0; } ================================================ FILE: BOJ/1260.DFS와 BFS/sAp00n.py ================================================ from sys import stdin from collections import deque def dfs(input_graph): global V dps_que = deque() visit = [V] for node in input_graph[V]: dps_que.append(node) while len(dps_que) > 0: #print(f'dps_visit: {visit}\ndps_que: {dps_que}') searching_node = dps_que.popleft() #print(f'current_node: {searching_node}') if searching_node not in visit: visit.append(searching_node) link_list = graph[searching_node] for idx in range(len(link_list)-1, -1, -1): if link_list[idx] not in visit: dps_que.appendleft(link_list[idx]) return visit def bfs(input_graph): global V bfs_que = deque() visit = [V] for node in graph[V]: bfs_que.append(node) while len(bfs_que) > 0: #print(f'bfs_visit: {visit}\nbfs_que : {bfs_que}') searching_node = bfs_que.popleft() #print(f'current_node: {searching_node}') if searching_node not in visit: visit.append(searching_node) linked_node_list = input_graph[searching_node] for linked_node in linked_node_list: if linked_node not in visit: bfs_que.append(linked_node) return visit global V N, M, V = list(map(int, stdin.readline().split())) graph = {V: []} node_list = [V] for _ in range(M): node01, node02 = list(map(int, stdin.readline().split())) if node01 not in graph: graph[node01] = [] node_list.append(node01) if node02 not in graph: graph[node02] = [] node_list.append(node02) graph[node01].append(node02) graph[node02].append(node01) #print(f'node_list : {node_list}') # print(graph) for i in node_list: graph[i].sort() #print(graph) # DFS DFS_result = dfs(graph) # print(DFS_result) DFS_str = '' for i in range(len(DFS_result)): DFS_str += str(DFS_result[i]) if i < N - 1: DFS_str += ' ' print(DFS_str) # BFS BFS_result = bfs(graph) BFS_str = '' for i in range(len(BFS_result)): BFS_str += str(BFS_result[i]) if i < N - 1: BFS_str += ' ' print(BFS_str) ================================================ FILE: BOJ/1261.알고스팟/6047198844.cpp ================================================ #include #include using namespace std; int arr[100][100]; // 그냥값 pair arr_sum_bool[100][100]; // 누적값 / 방문했는지 int around[4][2] = { {1,0}, {-1,0}, {0,-1}, {0,1} }; // 상하좌우 int M; int N; // x값 ,y값 bool Range(int y, int x) { if (x < 0 || x >= M) return false; if (y < 0 || y >= N) return false; return true; } int bfs(){ queue > q; // y값 x값 q.push(make_pair(0, 0)); arr_sum_bool[0][0].first = 0; arr_sum_bool[0][0].second = true; while (!q.empty()) { int y = q.front().first; int x = q.front().second; q.pop(); for (int i = 0; i < 4; i++){ int pushed_y = y + around[i][0]; int pushed_x = x + around[i][1]; if (Range(pushed_y, pushed_x)){ if (!arr_sum_bool[pushed_y][pushed_x].second){ q.push(make_pair(pushed_y, pushed_x)); arr_sum_bool[pushed_y][pushed_x].second = true; if (arr_sum_bool[pushed_y][pushed_x].first > arr_sum_bool[y][x].first + arr[y][x]) { arr_sum_bool[pushed_y][pushed_x].first = arr_sum_bool[y][x].first + arr[y][x]; } } else { if (arr_sum_bool[pushed_y][pushed_x].first > arr_sum_bool[y][x].first + arr[y][x]) { q.push(make_pair(pushed_y, pushed_x)); arr_sum_bool[pushed_y][pushed_x].first = arr_sum_bool[y][x].first + arr[y][x]; } } } } } return arr_sum_bool[N - 1][M - 1].first; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> M >> N; for (int y = 0; y < N; y++)for (int x = 0; x < M; x++) scanf(" %1d", &arr[y][x]); for (int y = 0; y < N; y++)for (int x = 0; x < M; x++) { arr_sum_bool[y][x].first = 999999; arr_sum_bool[y][x].second = false; } cout << bfs(); } ================================================ FILE: BOJ/1261.알고스팟/dosimpact.py ================================================ import sys import math from typing import * import itertools from collections import deque # 알고스팟 # N,M 빈방 - 가중치 0, 벽 1 M, N = map(int, input().split()) graph: List[List[int]] = [list(map(int, list(input()))) for _ in range(N)] check: List[List[int]] = [[-1 for _ in range(M)] for _ in range(N)] def inRange(x: int, y: int): return x >= 0 and y >= 0 and x < N and y < M dx, dy = [0, 0, 1, -1], [1, -1, 0, 0] q = deque() q.append((0, 0)) # 0,0 으로 들어옴 check[0][0] = 0 while q: x, y = q.popleft() for k in range(4): nx, ny = x+dx[k], y+dy[k] if inRange(nx, ny) and check[nx][ny] == -1: if graph[nx][ny] == 0: check[nx][ny] = check[x][y] q.appendleft((nx, ny)) continue if graph[nx][ny] == 1: check[nx][ny] = check[x][y] + 1 q.append((nx, ny)) continue print(check[N-1][M-1]) ================================================ FILE: BOJ/1264.모음의 개수/6047198844.py ================================================ while True: s = input() if s == '#': break cnt = 0 for i in 'a','A','e','E','i','I','o','O','u','U': cnt += s.count(i) print(cnt) ================================================ FILE: BOJ/1269.대칭 차집합/6047198844.py ================================================ # 문제 # 자연수를 원소로 갖는 공집합이 아닌 두 집합 A와 B가 있다. # 이때, 두 집합의 대칭 차집합의 원소의 개수를 출력하는 프로그램을 작성하시오. # 두 집합 A와 B가 있을 때, (A-B)와 (B-A)의 합집합을 A와 B의 대칭 차집합이라고 한다. # # 예를 들어, A = { 1, 2, 4 } 이고, B = { 2, 3, 4, 5, 6 } 라고 할 때, A-B = { 1 } 이고, B-A = { 3, 5, 6 } 이므로, 대칭 차집합의 원소의 개수는 1 + 3 = 4개이다. # # 입력 # 첫째 줄에 집합 A의 원소의 개수와 집합 B의 원소의 개수가 빈 칸을 사이에 두고 주어진다. # 둘째 줄에는 집합 A의 모든 원소가, 셋째 줄에는 집합 B의 모든 원소가 빈 칸을 사이에 두고 각각 주어진다. # 각 집합의 원소의 개수는 200,000을 넘지 않으며, 모든 원소의 값은 100,000,000을 넘지 않는다. # # 출력 # 첫째 줄에 대칭 차집합의 원소의 개수를 출력 input() A = set(input().split()) B = set(input().split()) print(len(A.union(B)-A.intersection(B))) ================================================ FILE: BOJ/1271.엄청난 부자2/6047198844.py ================================================ import sys n,m = map(int, sys.stdin.readline().split()) print(n//m, n%m) ================================================ FILE: BOJ/1283.단축키 지정/6047198844.py ================================================ N = int(input()) options = [input() for _ in range(N)] shortcuts = set() for option in options: words = option.split() # 1. 먼저 하나의 옵션에 대해 왼쪽에서부터 오른쪽 순서로 단어의 첫 글자가 이미 단축키로 지정되었는지 살펴본다. 만약 단축키로 아직 지정이 안 되어있다면 그 알파벳을 단축키로 지정한다. for idx, word in enumerate(words): if word[0].isalpha() and word[0].upper() not in shortcuts: shortcuts.add(word[0].upper()) words[idx] = '[' + words[idx][0] + ']' + words[idx][1:] print(' '.join(words)) break # 2. 만약 모든 단어의 첫 글자가 이미 지정이 되어있다면 왼쪽에서부터 차례대로 알파벳을 보면서 단축키로 지정 안 된 것이 있다면 단축키로 지정한다. else: for idx, char in enumerate(option): if char.isalpha() and char.upper() not in shortcuts: shortcuts.add(char.upper()) print(option[:idx] + '[' + char + ']' + option[idx + 1:]) break else: print(option) ================================================ FILE: BOJ/12847.꿀 아르바이트/6047198844.py ================================================ n, m = map(int, input().split()) arr = list(map(int, input().split())) start = sum(arr[0:m]) res = start for i in range(n-m): start = start - arr[i] + arr[i+m] res = max(res, start) print(res) ================================================ FILE: BOJ/12850.본대 산책2/6047198844.py ================================================ # 정점 8개 # 0번 정점이 정보과학관 # 1번 정점이 전산관 # 2번 정점이 미래관 # 3번 정점이 신앙관 # 4번 정점이 한경직기념관 # 5번 정점이 진리관 # 6번 정점이 학생회관 # 7번 정점이 형남공학관 # D분 일때 해당 경로를 지난 경우. # arr[D][경로] import sys from collections import defaultdict memo = defaultdict(lambda: [[-1 for _ in range(1 + 7)] for _ in range(1 + 7)]) memo[1] = [ [0, 1, 1, 0, 0, 0, 0, 0], [1, 0, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0, 1], [0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 1, 0]] # 10억? log N 의 방법이 필요하다. # frm -> to # 거리가 D 만큼남았을때 A에서 C 까지 가는 경우의 수 def func(A, C, D): # 범위는 항상 안전하다. if memo[D][A][C] != -1: return memo[D][A][C] memo[D][A][C] = 0 for B in range(7 + 1): # 곱! memo[D][A][C] += (func(A, B, D // 2) % 1000000007 * func(B, C, D // 2 + D % 2) % 1000000007) % 1000000007 return memo[D][A][C] % 1000000007 D = int(sys.stdin.readline()) print(func(0, 0, D)) ================================================ FILE: BOJ/12852.1로 만들기 2/6047198844.py ================================================ import math N = int(input()) memo = [math.inf for _ in range(N+1)] memo[0] = -1 # 경로 생성 for x in range(1, N + 1): # 모두 알아야하기때문에 if 로 엮는다. if x % 3 == 0: memo[x] = min(memo[x], memo[x//3] + 1) if x % 2 == 0: memo[x] = min(memo[x], memo[x//2] + 1) memo[x] = min(memo[x], memo[x-1] + 1) print(memo[N]) # 경로 추적 x = N routes = [N] while x != 1: # 아무거나 해도 되기때문에 if else 로 엮는다. if x % 3 == 0 and memo[x] == memo[x//3] + 1: x //= 3 elif x % 2 == 0 and memo[x] == memo[x//2] + 1: x //= 2 else: x -= 1 routes.append(x) for route in routes: print(route, end=' ') ================================================ FILE: BOJ/12852.1로 만들기 2/ms9849.cpp ================================================ #include using namespace std; int N; int dp[1000001]; int Num_dp[1000001]; int main(void) { cin >> N; Num_dp[1]; for(int i=2; i<=N; i++) { //bottom up 방식을 이용했습니다. 비슷한 문제인 1463번 문제에서 숫자들을 저장하는 Num_dp를 선언하여 확장한 개념입니다. dp[i] = dp[i-1] +1; Num_dp[i] = i-1; if(i%2==0 && dp[i] > dp[i/2] + 1) { dp[i] = dp[i/2] + 1; Num_dp[i] = i/2; } if(i%3==0 && dp[i] > dp[i/3] + 1) { dp[i] = dp[i/3] + 1; Num_dp[i] = i/3; } } cout << dp[N] << "\n"; while(N!=0) { cout << N << " "; N = Num_dp[N]; } } /* ================================================ FILE: BOJ/12865.평범한 배낭/6047198844.cpp ================================================ #include #include #include using namespace std; int memo[101][100001]; vector > vt = { {0,0} }; int main() { int N; int K; cin >> N >> K; int a; int b; for (int i = 0; i < N; i++) { cin >> a >> b; vt.push_back({ a,b }); } for (int i = 1; i <= N; i++) { for (int k = 1; k < vt[i].first; k++) { memo[i][k] = memo[i - 1][k]; } for (int j = vt[i].first; j <= K; j++) { memo[i][j] = max(memo[i - 1][j], memo[i - 1][j - vt[i].first] + vt[i].second); } } cout << memo[N][K]; } ================================================ FILE: BOJ/12886.돌 그룹/6047198844.py ================================================ import collections from itertools import combinations A, B, C = map(int, input().split()) Q = collections.deque() discovered = set() Q.append((A, B, C)) discovered.add((A, B, C)) while Q: a, b, c = Q.popleft() if a == b == c: print(1) exit() if a != b: if a < b: na = a + a nb = b - a else: nb = b + b na = a - b if (na, nb, c) not in discovered: discovered.add((na, nb, c)) Q.append((na, nb, c)) if a != c: if a < c: na = a + a nc = c - a else: nc = c + c na = a - c if (na, b, nc) not in discovered: discovered.add((na, b, nc)) Q.append((na, b, nc)) if b != c: if b < c: nb = b + b nc = c - b else: nc = c + c nb = b - c if (a, nb, nc) not in discovered: discovered.add((a, nb, nc)) Q.append((a, nb, nc)) print(0) ================================================ FILE: BOJ/12904.A와 B/6047198844.py ================================================ import sys S = sys.stdin.readline().rstrip() T = sys.stdin.readline().rstrip() while len(T) > len(S): if T[-1] == 'A': T = T[:-1] else: T = T[:-1][::-1] print(int(T==S)) ================================================ FILE: BOJ/1292.쉽게 푸는 문제/6047198844.py ================================================ import sys arr = [0] for i in range(1, 50 + 1): for _ in range(i): arr.append(i) s = [0] for i in range(1, len(arr)): s.append(s[i-1] + arr[i]) A, B = map(int, sys.stdin.readline().split()) print(s[B] - s[A-1]) ================================================ FILE: BOJ/1300.K번째 수/6047198844.py ================================================ import sys def rank(m): mn, mx = 0, 0 for i in range(1, N + 1): mx = mx + min(m // i, N) mn = mn + min(m // i, N) if m % i == 0 and m <= N*i: mn -= 1 return mn, mx N = int(sys.stdin.readline()) k = int(sys.stdin.readline()) begin, end = 1, 10**10 while begin < end: mid = (begin + end) // 2 mn, mx = rank(mid) # 구한값이 실제보다 작다. -> 높히자 if mn < k <= mx: begin = mid break elif mx < k: begin = mid + 1 else: end = mid - 1 print(begin) # 1*1 2*1 3*1 # 1*2 2*2 3*2 # 1*3 2*3 3*3 # 1 2 3 4 5 6 7 8 9 # 1 2 2 3 3 4 6 6 9 # 1 ~ 7 # 5 ~ 7 ================================================ FILE: BOJ/1302.베스트셀러/6047198844.py ================================================ from collections import Counter N = int(input()) books = list() for _ in range(N): books.append(input()) books = Counter(books) books = sorted(books, key=lambda x: (-books.get(x), x)) print(books[0]) ================================================ FILE: BOJ/13022.늑대와 올바른 단어/6047198844.py ================================================ from itertools import permutations wolfs = ['w' * i + 'o' * i + 'l' * i + 'f' * i for i in range(1, 12 + 1)] table = dict() for idx, wolf in enumerate(wolfs): table[idx+1] = wolf word = input() start_idx = 0 while start_idx < len(word): for wolf in wolfs: if word[start_idx:].startswith(wolf): start_idx += len(wolf) break else: print(0) exit() print(1) ================================================ FILE: BOJ/1312.소수/6047198844.py ================================================ A, B, N = map(int, input().split()) A %= B for i in range(N - 1): A = (A * 10) % B print((A * 10) // B) ================================================ FILE: BOJ/1316.그룹 단어 체커/6047198844.py ================================================ n = int(input()) res = n for _ in range(n): check = [False]*26 s = [ord(i)-ord('a') for i in input()] for idx in range(len(s)): cur, lst = s[idx] , s[idx-1] if idx == 0 or (cur!=lst and not check[cur]) or (cur==lst and check[cur]): check[cur] = True continue else: res+=-1 break print(res) # 그룹 단어 2가지 경우 # 현재 알파벳이 이전꺼와 같지 않으면서 방문이 안된경우. # 현재 알파벳이 이전꺼와 같으면서 방문이 된경우. ================================================ FILE: BOJ/13241.최소공배수/6047198844.py ================================================ import sys a, b = map(int ,sys.stdin.readline().split()) def gcf(a, b): if b == 0: return a return gcf(b, a % b) print(a * b // gcf(a, b)) ================================================ FILE: BOJ/1325.효율적인 해킹/효율적인해킹_1325.py ================================================ from collections import deque n, m=map(int, input().split()) arr=[[] for _ in range(n+1)] count=[] def bfs(v): q=deque([v]) cnt=0 while q: k=q.popleft() if not visited[k]: visited[k]=1 cnt += 1 for e in arr[k]: q.append(e); count.append(cnt) for i in range(m): x, y=map(int, input().split()) arr[y].append(x) for e in arr: e.sort() for i in range(1, n+1): visited = [0 for _ in range(n + 1)] bfs(i) for i in range(len(count)): if max(count)==count[i]: print(i+1, end=" ") ================================================ FILE: BOJ/13277.큰 수 곱셈/6047198844.py ================================================ import sys A, B = map(int, sys.stdin.readline().split()) print(A*B) ================================================ FILE: BOJ/13301.타일 장식물/6047198844.py ================================================ N = int(input()) A, B = 2, 4 for _ in range(N - 1): A, B = B, A + B print(B) # 4, 6, 10, 16, 26 ================================================ FILE: BOJ/13333.Q-인덱스/6047198844.py ================================================ import sys n = int(sys.stdin.readline()) mentions = list(map(int, sys.stdin.readline().split())) for k in range(len(mentions), -1, -1): # k번 이상 인용된 논문이 k편 이상이고 나머지 n − k 편의 논문들 인용회수가 각각 k 번 이하라면, 해당 학생의 q-인덱스는 k이다. upper_cnt = 0 lower_cnt = 0 for mention in mentions: if mention >= k: upper_cnt += 1 if mention <= k: lower_cnt += 1 if k <= upper_cnt and len(mentions) - k <= lower_cnt: print(k) exit() ================================================ FILE: BOJ/1339.단어 수학/6047198844.py ================================================ #00GCF #ACDEB #자릿수가 클수록 높은 번호를 가져야함. #그러면 만약에 #ACDEB CAGCF 의 경우는 ? import collections import sys N = int(input()) words = [sys.stdin.readline().rstrip() for _ in range(N)] dict = collections.defaultdict(int) for word in words: for idx, w in enumerate(word[::-1]): dict[w] = dict[w] + 10 ** idx nums = sorted(dict.values(), reverse=True) res = 0 for idx, num in enumerate(nums): res += num * (9-idx) print(res) #dict.update() #string배열을 set으로 하는 방법 #dict key를 기준으로 정렬 #dict update #가중치 ================================================ FILE: BOJ/13460.구슬 탈출 2/6047198844.py ================================================ import collections #움직이고 싶은 marble의 위치, 움직이고 싶은 방향의 y, 움직이고 싶은 방향의 x #가장 바깥 행과 열은 모두 막혀져 있다. (범위 체크하지 않아도 됨.) #다 옮긴 후에는 옮겨진 marble의 위치, 움직인 길이를 반환한다. #벽은 '#'으로 표현된다. #원래 자리에서 움직일 위치가 '#'이면 안되고 원래 위치가 'O'이면 움직임을 멈춘다. def move_marble(marble_position, dy, dx): y, x = marble_position moved_num = 0 while board[y+dy][x+dx] != '#' and board[y][x] != 'O': moved_num += 1 y += dy x += dx return y, x, moved_num N, M = map(int, input().split()) board = [list(input()) for _ in range(N)] red_position = tuple() blue_position = tuple() for y in range(N): for x in range(M): if board[y][x] == 'R': red_position = (y, x) elif board[y][x] == 'B': blue_position = (y, x) #bfs로 푼다. #초기 포지션에 대해 큐에 넣는다 Q = collections.deque() Q.append((red_position, blue_position)) path = set((red_position, blue_position)) #빨강구슬을 빼내는것이다. 파랑구슬을 빼면 실패이다. cnt = 0 while Q: cnt += 1 #현재의 움직임이 11번째일때 while문을 탈출한다. if cnt == 11: break for _ in range(len(Q)): red_position, blue_position = Q.popleft() #상하좌우로 움직인다. for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): n_red_y, n_red_x, n_moved_red = move_marble(red_position, dy, dx) n_blue_y, n_blue_x, n_moved_blue = move_marble(blue_position, dy, dx) #구멍은 두 구슬의 위치가 곂칠수있다. #움직인 위치가 blue를 구멍에 떨어뜨릴때. -> 더이상 진행하지 않는다. if board[n_blue_y][n_blue_x] == 'O': continue #움직인 위치가 red를 구멍에 떨어뜨릴때. -> 정답이다. elif board[n_red_y][n_red_x] == 'O': print(cnt) exit() #둘다 구멍에 위치하지 않는 경우. 위치가 곂치면 안된다. #곂칠경우 구슬에 대해서 바로 직전의 포지션으로 돌릴 필요가 있다. #길게 움직였다는것은 뒤에 있다는 뜻이다. 길게 움직인 marble의 위치를 한칸 무른다. #같은 길이는 움직일수없다. (동일한 위치에 있었다는 이야기이므로.) if n_red_y == n_blue_y and n_red_x == n_blue_x: if n_moved_red > n_moved_blue: n_red_y += -dy n_red_x += -dx else: n_blue_y += -dy n_blue_x += -dx n_marble_position = ((n_red_y, n_red_x), (n_blue_y, n_blue_x)) #조정된 끝난 위치가 발견하지 않은 포지션인 경우 Q에 집어 넣는다. if n_marble_position not in path: #발견 완료 path.add(n_marble_position) #Q에 넣는다. Q.append(n_marble_position) #현재의 움직임이 11번째 & 공이 움직이지 않을때 print(-1) ================================================ FILE: BOJ/13549.숨바꼭질 3/6047198844.cpp ================================================ // *2 / +1 / -1 #include #include using namespace std; bool check[100001]; int num[100001]; int bfs(int N, int K) { queue spot; spot.push(N); check[N] = true; while (!spot.empty()) { int node = spot.front(); if (node == K) return num[K]; spot.pop(); if (node * 2 <= 100000 && (!check[node * 2]||num[node*2]>num[node])) { spot.push(node * 2); check[node * 2] = true; num[node * 2] = num[node]; } if (node + 1 <= 100000 && (!check[node + 1] || num[node + 1] > num[node] + 1)) { spot.push(node + 1); check[node + 1] = true; num[node + 1] = num[node] + 1; } if (node - 1 >= 0 && (!check[node - 1] || num[node - 1] > num[node] + 1)) { spot.push(node - 1); check[node - 1] = true; num[node - 1] = num[node] + 1; } } } int main() { int N; int K; cin >> N >> K; cout << bfs(N, K); } ================================================ FILE: BOJ/13565.침투/6047198844.py ================================================ # 문제 # 전류가 침투(percolate) 할 수 있는 섬유 물질을 개발하고 있다. 이 섬유 물질은 2차원 M × N 격자로 표현될 수 있다. # 편의상 2차원 격자의 위쪽을 바깥쪽(outer side), 아래쪽을 안쪽(inner side)라고 생각하기로 한다. 또한 각 격자는 검은색 아니면 흰색인데, 검은색은 전류를 차단하는 물질임을 뜻하고 흰색은 전류가 통할 수 있는 물질임을 뜻한다. # 전류는 섬유 물질의 가장 바깥쪽 흰색 격자들에 공급되고, 이후에는 상하좌우로 인접한 흰색 격자들로 전달될 수 있다. # # 김 교수가 개발한 섬유 물질을 나타내는 정보가 2차원 격자 형태로 주어질 때, 바깥쪽에서 흘려 준 전류가 안쪽까지 침투될 수 있는지 아닌지를 판단하는 프로그램을 작성하시오. # 입력 # 첫째 줄에는 격자의 크기를 나타내는 M (2 ≤ M ≤ 1,000) 과 N (2 ≤ N ≤ 1,000) 이 주어진다. M줄에 걸쳐서, N개의 0 또는 1 이 공백 없이 주어진다. 0은 전류가 잘 통하는 흰색, 1은 전류가 통하지 않는 검은색 격자임을 뜻한다. # # 출력 # 바깥에서 흘려준 전류가 안쪽까지 잘 전달되면 YES를 출력한다. # # 그렇지 않으면 NO를 출력한다. # BFS import sys from collections import deque M, N = map(int, input().split()) board = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(M)] # 위쪽에 전류를 흘린다. for i in range(N): # 전류가 흐를수없음 if board[0][i] == 1: continue # 전류가 흐를수있음 Q = deque() board[0][i] = 1 Q.append((0, i)) while Q: y, x = Q.popleft() for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny, nx = y + dy, x + dx if 0 <= ny < M and 0 <= nx < N and board[ny][nx] == 0: if ny == M - 1: # 도착하면 YES 출력후 종료 print('YES') exit() board[ny][nx] = 1 Q.append((ny, nx)) # 아무것도 안거칠경우 NO 출력후 종료 print('NO') ================================================ FILE: BOJ/13702.이상한 술집/6047198844.py ================================================ # 이분 탐색 문제 # 이 술집에서 막걸리를 시키면 주전자의 용량은 똑같았으나 안에 들어 있는 막걸리 용량은 랜덤이다. # 은상은 막걸리 N 주전자를 주문하고, 자신을 포함한 친구들 K 명에게 막걸리를 똑같은 양으로 나눠주려고 한다. # 즉, 한 번 주문한 막걸리에 남은 것을 모아서 친구들에게 다시 주는 경우는 없다. # 예를 들어 5명이 3 주전자를 주문하여 1002, 802, 705 ml의 막걸리가 각 주전자에 담겨져 나왔고, 이것을 401ml로 동등하게 나눴을 경우 각각 주전자에서 200ml, 0m, 304ml 만큼은 버린다.) 이럴 때 # K명에게 최대한의 많은 양의 막걸리를 분배할 수 있는 용량 ml는 무엇인지 출력해주세요. # # 입력 # 첫째 줄에는 은상이가 주문한 막걸리 주전자의 개수 N, 그리고 은상이를 포함한 친구들의 수 K가 주어진다. # 둘째 줄부터 N개의 줄에 차례로 주전자의 용량이 주어진다. N은 10000이하의 정수이고, K는 1,000,000이하의 정수이다. 막걸리의 용량은 2^31 -1 보다 작거나 같은 자연수 또는 0이다. # 단, 항상 N ≤ K 이다. 즉, 주전자의 개수가 사람 수보다 많을 수는 없다. # # 출력 # 첫째 줄에 K명에게 나눠줄 수 있는 최대의 막걸리 용량 ml 를 출력한다. import sys N, K = map(int, input().split()) arr = list(int(sys.stdin.readline()) for _ in range(N)) begin = 1 end = max(arr) + 1 # 주의 : upperbound while begin < end: cnt = 0 mid = (begin + end) // 2 for num in arr: cnt += num // mid if K <= cnt: begin = mid + 1 else: end = mid print(end-1) ================================================ FILE: BOJ/1376.민식우선탐색/input_list.md ================================================ ex 01 5 6 1 2 1 4 1 3 3 2 3 4 2 5 out 1 3 2 5 4 line 5 4 1 2 2 3 3 4 4 5 out 1 2 3 4 5 all linked 6 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 out 1 4 2 5 3 6 circle 6 6 1 2 2 3 3 4 4 5 5 6 6 1 out 1 2 3 4 5 6 ex 03 12 11 1 2 1 3 1 4 2 5 2 6 2 7 2 8 3 9 3 10 3 11 4 12 out 1 3 10 9 11 2 5 6 7 8 4 12 test 6 8 1 2 1 2 1 2 1 2 1 3 1 4 1 5 1 6 ================================================ FILE: BOJ/1376.민식우선탐색/sAp00n.py ================================================ from sys import stdin def mFS(graph): global N current_node = 1 visit_list = [] checker = {} while len(visit_list) < N: # print(f'visit_list : {visit_list}') temp = graph[current_node] connected_list = [] for node in temp: if node in checker: continue connected_list.append(node) # print(f'current : {current_node} connect: {connected_list}') if current_node in checker and len(connected_list) == 0: current_node = visit_list[visit_list.index(current_node) - 1] continue if len(connected_list) == 0: if current_node not in checker: visit_list.append(current_node) checker[current_node] = True current_node = visit_list[visit_list.index(current_node) - 1] elif len(connected_list) == 1: if current_node not in checker: visit_list.append(current_node) checker[current_node] = True current_node = connected_list[0] elif len(connected_list) % 2 == 1: if current_node not in checker: visit_list.append(current_node) checker[current_node] = True current_node = connected_list[len(connected_list) // 2] else: if current_node not in checker: visit_list.append(current_node) checker[current_node] = True current_node = connected_list[0] return visit_list global N N, M = list(map(int, stdin.readline().split())) graph = {} checker = {} for i in range(1, N + 1): graph[i] = [] checker[i] = {} for _ in range(M): node01, node02 = list(map(int, stdin.readline().split())) if node01 == node02: continue if node02 not in checker[node01]: graph[node01].append(node02) checker[node01][node02] = True if node01 not in checker[node02]: graph[node02].append(node01) checker[node02][node01] = True for i in range(1, N + 1): graph[i].sort() #print(graph) #print(checker) visit_list = mFS(graph) return_str = '' for node in visit_list: return_str += str(node) + ' ' print(return_str[:-1]) ================================================ FILE: BOJ/1389. 케빈 베이컨의 6단계 법칙/6047198844.py ================================================ import math import sys N, M = map(int, sys.stdin.readline().split()) distance = [[math.inf for _ in range(N)] for _ in range(N)] for y in range(N): for x in range(N): if y == x: distance[y][x] = 0 for _ in range(M): i, j = map(lambda x: int(x) - 1, sys.stdin.readline().split()) distance[i][j] = 1 distance[j][i] = 1 for k in range(N): for i in range(N): for j in range(N): if distance[i][j] > distance[i][k] + distance[k][j]: distance[i][j] = distance[i][k] + distance[k][j] res = list(map(sum, distance)) print(res.index(min(res)) + 1) ================================================ FILE: BOJ/1389. 케빈 베이컨의 6단계 법칙/rockmiin.py ================================================ from collections import deque def bfs(start, end): q= deque([start]) visited = [0] * (n+1) visited[start]= 1 while q: x= q.popleft() if x==end: return visited[end]-1 for i in adj[x]: if not visited[i]: q.append(i) visited[i]= visited[x]+1 n, m= map(int, input().split()) res= [0] adj=[[] for _ in range(n+1)] for i in range(m): x, y= map(int, input().split()) adj[x].append(y) adj[y].append(x) # print(adj) for i in range(1, n+1): cnt= 0 for j in range(1, n+1): cnt+=bfs(i, j) res.append(cnt) print(res.index(min(res[1:]))) ================================================ FILE: BOJ/13902.개업 2/6047198844.py ================================================ # 문제 # 해빈이는 양손잡이여서 동시에 두 개의 웍(중국 냄비)을 사용하여 요리할 수 있다. 필요 이상 크기의 웍을 사용하지 않으며, 주문 받은 짜장면의 그릇 수에 딱 맞게 요리한다. # 예를 들어 짜장면 4그릇을 주문 받았는데 5그릇 이상을 요리하지 않으며, 4그릇을 요리할 수 있는 웍에 3그릇 이하의 요리를 하지 않는다. # # 해빈이가 5그릇을 주문 받았고, 해빈이가 가지고 있는 웍의 종류가 1, 3그릇 용이라면 처음에 1,3그릇용 웍을 동시에 이용하여 4그릇을 만들고 다음 1그릇용 웍을 이용하여 1그릇을 만들어 총 5그릇을 두 번의 요리로 만들 수 있다. # # 해빈이가 주문 받은 짜장면의 수와 가지고 있는 웍의 크기가 주어질 때, 최소 몇 번의 요리로 모든 주문을 처리할 수 있는지 출력하는 프로그램을 작성하시오. # # 입력 # 첫 번째 줄에는 해빈이가 주문 받은 짜장면의 수N(1≤N≤10,000)과 가지고 있는 웍의 개수 M(1≤M≤1,000)이 주어진다. 두 번째 줄에는 웍의 크기 Si(1≤Si≤N)이 M개가 주어지며 같은 크기의 웍을 여러 개 가지고 있을 수 있다. # # 출력 # 해빈이가 모든 주문을 처리하기 위해 해야 하는 최소 요리 횟수를 출력한다. 만약 모든 주문을 처리 할 수 없는 경우 -1을 출력한다. from itertools import combinations N, M = map(int, input().split()) wack = list(map(int, input().split())) for i, j in combinations(wack, 2): if i + j <= N: wack.append(i + j) # 중복제거, 한 요리수로 만들수있는 모든 그릇수 wack = list(set(wack)) # dishes[N] = N 그릇을 만드는데 필요한 최소 요리수. dishes = [0 for _ in range(N+1)] for i in wack: # i 는 한번 요리로 만들수있는 그릇수. -> 무조건 최소 비용 1이다. dishes[i] = 1 for j in range(i+1, N+1): # j - i : X번 요리로 만든 그릇수. 이떄 X는 최소임이 보장된다. # dishes[j - i] : X번. 만약에 0이라면 만들 수 없는것. if dishes[j - i] != 0 and (dishes[j] == 0 or dishes[j] > dishes[j - i] + 1): dishes[j] = dishes[j - i] + 1 print(dishes[N]) if dishes[N] != 0 else print(-1) ================================================ FILE: BOJ/13985.Equality/6047198844.py ================================================ import sys input = sys.stdin.readline().split() plus = int(input[0]) + int(input[2]) result = int(input[4]) if plus == result: print("YES") else: print("NO") ================================================ FILE: BOJ/14002.가장 긴 증가하는 부분 수열 4/와일드카드.cpp ================================================ // A ־ , ϴ κ ϴ α׷ ۼϽÿ. // // , A = { 10, 20, 10, 30, 20, 50 } 쿡 ϴ κ { 10, 20, 30, 50 } ̰, ̴ 4̴. //V[i] D[i] ̸ κ ε Ѵ. //D[i] A[i] ϴ . //A[i] Ѵ. #include #include #include using namespace std; int v[1001]; int d[1001]; int a[1001]; int main() { int N; cin >> N; for (int i = 0; i < N; i++) { cin >> a[i]; d[i] = 1; v[i] = -1; } for (int i = 0; i < N; i++) { for (int j = 0; j < i; j++) { if (a[i] > a[j] && d[i] < d[j] + 1) { d[i] = d[j] + 1; v[i] = j; } } } stack st; // ̸ ε int max_idx = max_element(d, d + N) - d; cout << d[max_idx] << "\n"; st.push(a[max_idx]); for (int idx = v[max_idx];idx!=-1;idx = v[idx]) { st.push(a[idx]); } while (!st.empty()) { cout << st.top() << " "; st.pop(); } } ================================================ FILE: BOJ/14003.가장 긴 증가하는 부분 수열 5/6047198844.py ================================================ # 문제 # 수열 A가 주어졌을 때, 가장 긴 증가하는 부분 수열을 구하는 프로그램을 작성하시오. # # 예를 들어, 수열 A = {10, 20, 10, 30, 20, 50} 인 경우에 가장 긴 증가하는 부분 수열은 A = {10, 20, 10, 30, 20, 50} 이고, 길이는 4이다. # # 입력 # 첫째 줄에 수열 A의 크기 N (1 ≤ N ≤ 1,000,000)이 주어진다. # # 둘째 줄에는 수열 A를 이루고 있는 Ai가 주어진다. (-1,000,000,000 ≤ Ai ≤ 1,000,000,000) # # 출력 # 첫째 줄에 수열 A의 가장 긴 증가하는 부분 수열의 길이를 출력한다. # # 둘째 줄에는 정답이 될 수 있는 가장 긴 증가하는 부분 수열을 출력한다. import bisect N = int(input()) arr = list(map(int, input().split())) memo = [] increase_arr = [] for i in arr: idx = bisect.bisect_left(increase_arr, i) if idx == len(increase_arr): increase_arr.append(i) else: increase_arr[idx] = i memo.append(idx) print(len(increase_arr)) res = [] p = len(increase_arr) - 1 for idx, i in enumerate(memo[::-1]): if i == p: res.append(arr[- 1 - idx]) p -= 1 for i in res[::-1]: print(i, end = ' ') ================================================ FILE: BOJ/1417.국회의원 선거/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) people = [int(sys.stdin.readline()) for _ in range(N)] res = 0 while people[0] <= max(people[1:len(people)]): max_person = max(people[1:len(people)]) idx = people[1:len(people)].index(max_person) + 1 people[idx] -= 1 people[0] += 1 res += 1 print(res) ================================================ FILE: BOJ/14226.이모티콘/6047198844.cpp ================================================ #include #include using namespace std; int check[2001]; bool flag[2001][2001]; int bfs(int S) { queue > q; // 상태, 클립보드에 저장된수 q.push({1,0}); int timer = 0; flag[1][0] = true; while (!q.empty()) { int q_size = q.size(); while (q_size--) { //상태,클립보드 pair emoji = q.front(); q.pop(); if (emoji.first == S) return timer; //복사 if (!flag[emoji.first][emoji.first]) { q.push({ emoji.first, emoji.first }); flag[emoji.first][emoji.first] = true; } //붙여넣기 if (emoji.first+emoji.second<=2000 && (!flag[emoji.first + emoji.second][emoji.second])) { q.push({emoji.first + emoji.second, emoji.second}); flag[emoji.first + emoji.second][emoji.second] = true; } //삭제 if (emoji.first > 0 && !flag[emoji.first - 1][emoji.second]) { q.push({ emoji.first - 1,emoji.second }); flag[emoji.first - 1][emoji.second] = true; } } timer++; } return check[S]; } int main() { int S; cin >> S; cout << bfs(S); } ================================================ FILE: BOJ/1427.소트인사이드/6047198844.cpp ================================================ #include #include using namespace std; int main() { int N; vector arr(10); while (~scanf("%1d", &N)) ++arr[N]; for (int i = 9; i >= 0; i--) while(arr[i]--) cout << i; } ================================================ FILE: BOJ/1436.영화감독 숌/6047198844.cpp ================================================ #include using namespace std; int main() { int start = 666; int res = 1; int temp; int N; cin >> N; while (res != N) { start++; temp = start; int cnt = 0; while (temp&&cnt!=3) { if (temp % 10 == 6) cnt++; else cnt = 0; temp /= 10; } if (cnt == 3) res++; } cout << start; } ================================================ FILE: BOJ/1439.뒤집기/6047198844.py ================================================ S = str(input()) zero = 0 one = 0 if S[0] == '0': zero += 1 else: one += 1 for idx in range(1, len(S)): if S[idx-1] != S[idx]: if S[idx] == '0': zero += 1 else: one += 1 print(min(zero, one)) ================================================ FILE: BOJ/14395.4연산/6047198844.py ================================================ import collections #0, 1은 필수 def bfs(s, t): Q = collections.deque() Q.append((s, "")) discovered = set() discovered.add(s) # * + - / while Q: for _ in range(len(Q)): num, operator = Q.popleft() #뺄셈 나눗셈은 무조건 0,1이 된다. -> 연산하지 않는다. #곱/더하기/빼기/나누기 순 #곱 mul_n = num * num if mul_n == t: return operator + '*' elif mul_n < t and mul_n not in discovered: Q.append((mul_n, operator + '*')) discovered.add(mul_n) #더하기 add_n = num + num if add_n == t: return operator + '+' elif add_n < t and add_n not in discovered: Q.append((add_n, operator + '+')) discovered.add(add_n) #나누기. 최초 1회수행 if 1 not in discovered: Q.append((1, '/')) discovered.add(1) return -1 s, t = map(int, input().split()) if s == t: print(0) elif t == 1: print('/') else: print(bfs(s, t)) #소트 접근이 아니다. ================================================ FILE: BOJ/14405.피카츄/6047198844.py ================================================ # 문제 # 피카츄는 "pi", "ka", "chu"를 발음할 수 있다. 따라서, 피카츄는 이 세 음절을 합친 단어만 발음할 수 있다. 예를 들면, "pikapi"와 "pikachu"가 있다. # # 문자열 S가 주어졌을 때, 피카츄가 발음할 수 있는 문자열인지 아닌지 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 문자열 S가 주어진다. 문자열은 알파벳 소문자로 이루어진 문자열이며, 길이는 5000을 넘지 않는다. # # 출력 # 문자열 S가 "pi", "ka", "chu"를 이어 붙여서 만들 수 있으면 "YES"를 아니면 "NO"를 출력한다. S = input() idx = 0 while idx < len(S): if S[idx] == 'p' and idx + 1 < len(S) and S[idx+1] == 'i': idx += 2 elif S[idx] == 'k' and idx + 1 < len(S) and S[idx+1] == 'a': idx += 2 elif S[idx] == 'c' and idx + 2 < len(S) and S[idx+1] == 'h' and S[idx+2] == 'u': idx += 3 else: print('NO') exit() else: print('YES') ================================================ FILE: BOJ/14425.문자열 집합/6047198844.py ================================================ N, M = map(int, input().split()) N_set = set() for _ in range(N): N_set.add(input()) res = 0 for _ in range(M): if input() in N_set: res += 1 print(res) ================================================ FILE: BOJ/1446.지름길/6047198844.py ================================================ # 문제 # 차를 타고 D킬로미터 길이의 고속도로를 지난다. # 고속도로에 지름길이 존재. 모든 지름길은 일방통행이고, 고속도로를 역주행할 수는 없다. # # 세준이가 운전해야 하는 거리의 최솟값을 출력하시오. # # 입력 # 첫째 줄에 지름길의 개수 N과 고속도로의 길이 D가 주어진다. N은 12 이하인 양의 정수이고, D는 10,000보다 작거나 같은 자연수이다. # 다음 N개의 줄에 지름길의 시작 위치, 도착 위치, 지름길의 길이가 주어진다. 모든 위치와 길이는 10,000보다 작거나 같은 음이 아닌 정수이다. 지름길의 시작 위치는 도착 위치보다 작다. # # 출력 # 세준이가 운전해야하는 거리의 최솟값을 출력하시오. # 한정점에서 다른 정점까지 가는데 최소거리 -> 다익스트라 활용가능. import heapq from collections import defaultdict INF = 987654321 N, D = map(int, input().split()) edges = defaultdict(lambda: dict()) vertexes = set() for _ in range(N): i, j, cost = map(int, input().split()) # edges 필터링. 유일한 간선만 만들어보자. if j not in edges[i] or edges[i][j] > cost: edges[i][j] = cost vertexes.add(i) vertexes.add(j) depart, arrive = 0, D vertexes.add(0) vertexes.add(D) vertexes = list(vertexes) for i in vertexes: for j in vertexes: if i < j and (j not in edges[i] or edges[i][j] > j - i): edges[i][j] = j - i # 최단거리 초기화 distance = dict() for v in vertexes: distance[v] = INF distance[0] = 0 PQ = [] # cost, 정점 heapq.heappush(PQ, (0, 0)) while PQ: cm, mid = heapq.heappop(PQ) # 최적이 아니면 버린다. if distance[mid] != cm: continue # 최적인 경우이므로 해당 경우로 최적화 가능한지 묻고, 가능하면 우선순위 큐에 넣는다. # == cm까지의 최적 경로 + mid -> end 의 경로 < ce 까지의 최적경로 for end, ce in edges[mid].items(): if distance[mid] + ce < distance[end]: distance[end] = distance[mid] + ce heapq.heappush(PQ, (distance[end], end)) print(distance[D]) ================================================ FILE: BOJ/14467.소가 길을 건너간 이유 1/6047198844.py ================================================ # 문제 # 존은 소의 위치를 N번 관찰하는데, 각 관찰은 소의 번호와 소의 위치 하나씩으로 이루어져 있다. 존은 소를 10마리 가지고 있으므로 소의 번호는 1 이상 10 이하의 정수고, 소의 위치는 길의 왼쪽과 오른쪽을 의미하는 0과 1 중 하나다. # # 이 관찰 기록을 가지고 소가 최소 몇 번 길을 건넜는지 알아보자. 즉 같은 번호의 소가 위치를 바꾼 것이 몇 번인지 세면 된다. # # 입력 # 첫 줄에 관찰 횟수 N이 주어진다. N은 100 이하의 양의 정수이다. 다음 N줄에는 한 줄에 하나씩 관찰 결과가 주어진다. 관찰 결과는 소의 번호와 위치(0 또는 1)로 이루어져 있다. # # 출력 # 첫 줄에 소가 길을 건너간 최소 횟수를 출력한다. import sys N = int(sys.stdin.readline()) table = dict() res = 0 for _ in range(N): cow, pos = map(int, input().split()) if cow in table and table[cow] != pos: res += 1 table[cow] = pos print(res) ================================================ FILE: BOJ/1449.수리공 항승/6047198844.py ================================================ from collections import deque N, L = map(int, input().split()) arr = deque(sorted(map(int, input().split()))) start = arr.popleft() - 0.5 cnt = 1 while arr: tmp = arr.popleft() if start + L >= tmp + 0.5: pass else: start = tmp - 0.5 cnt += 1 print(cnt) ================================================ FILE: BOJ/14490.백대열/6047198844.py ================================================ import sys def func(a, b): if b == 0: return a return func(b, a % b) a, b = map(int, sys.stdin.readline().split(':')) gcf = func(a, b) print(f'{a//gcf}:{b//gcf}') ================================================ FILE: BOJ/14500.테트로미노/6047198844.cpp ================================================ //폴리오미노란 크기가 1×1인 정사각형을 여러 개 이어서 붙인 도형이며, 다음과 같은 조건을 만족해야 한다. // //정사각형은 서로 겹치면 안 된다. //도형은 모두 연결되어 있어야 한다. //정사각형의 변끼리 연결되어 있어야 한다.즉, 꼭짓점과 꼭짓점만 맞닿아 있으면 안 된다. //정사각형 4개를 이어 붙인 폴리오미노는 테트로미노라고 하며, 다음과 같은 5가지가 있다. // //아름이는 크기가 N×M인 종이 위에 테트로미노 하나를 놓으려고 한다.종이는 1×1 크기의 칸으로 나누어져 있으며, 각각의 칸에는 정수가 하나 쓰여 있다. // //테트로미노 하나를 적절히 놓아서 테트로미노가 놓인 칸에 쓰여 있는 수들의 합을 최대로 하는 프로그램을 작성하시오. // //테트로미노는 반드시 한 정사각형이 정확히 하나의 칸을 포함하도록 놓아야 하며, 회전이나 대칭을 시켜도 된다. /* 1. 각각의 경우의 수를 구한다 테트로미노는 19가지의 경우의 수가 있다. 각각 가장 좌상단의 정사각형은 N X M 칸정도 가능하다. N = 4 M = 500 이므로 4*500*19 < 1억 따라서 브루트 포스로 가능하다. 2. 가능한 모든 방법을 다 만들어 본다. 각각의 경우의 수를 프로그래밍한다. */ #include #include using namespace std; //19개의 테트로미노를 만든다. 좌상단 기준. y증가량, x증가량 vector > tetromino[19] = { {{0,0},{0,1},{0,2},{0,3}}, {{0,0},{1,0},{2,0},{3,0}}, {{0,0},{0,1},{1,0},{1,1}}, {{0,0},{1,0},{2,0},{1,1}}, {{0,0},{0,1},{1,1},{0,2}}, {{0,0},{-1,1},{0,1},{1,1}}, {{0,0},{-1,1},{0,1},{0,2}}, {{0,0},{0,1},{0,2},{1,2}}, {{0,0},{1,0},{2,0},{0,1}}, {{0,0},{1,0},{1,1},{1,2}}, {{0,0},{-2,1},{-1,1},{0,1}}, {{0,0},{1,0},{0,1},{0,2}}, {{0,0},{0,1},{1,1},{2,1}}, {{0,0},{0,1},{-1,2},{0,2}}, {{0,0},{1,0},{2,0},{2,1}}, {{0,0},{0,1},{-1,1},{-1,2}}, {{0,0},{1,0},{1,1},{2,1}}, {{0,0},{0,1},{1,1},{1,2}}, {{0,0},{1,0},{0,1},{-1,1}}, }; int arr[501][501]; int N; int M; int brute_force() { //테트로미노 19개를 좌상단을 기준으로 N X M 배열에 모두 놓는다. 1,1부터 시작. 500,500까지 //각 좌표중 하나라도 1미만이거나 N초과일경우 답에 해당되지 않는다. int max = 0; int res = 0; for (int i = 0; i < 19; i++) { for (int y = 1; y <= N; y++) for (int x = 1; x <= M; x++) { if ((y + tetromino[i][0].first >= 1 && y + tetromino[i][0].first <= N)&&(x + tetromino[i][0].second >= 1 && x + tetromino[i][0].second <= M)&& (y + tetromino[i][1].first >= 1 && y + tetromino[i][1].first <= N)&&(x + tetromino[i][1].second >= 1 && x + tetromino[i][1].second <= M) && (y + tetromino[i][2].first >= 1 && y + tetromino[i][2].first <= N)&&(x + tetromino[i][2].second >= 1 && x + tetromino[i][2].second <= M) && (y + tetromino[i][3].first >= 1 && y + tetromino[i][3].first <= N)&&(x + tetromino[i][3].second >= 1 && x + tetromino[i][3].second <= M) ) { res = arr[y + tetromino[i][0].first][x + tetromino[i][0].second] + arr[y + tetromino[i][1].first][x + tetromino[i][1].second] + arr[y + tetromino[i][2].first][x + tetromino[i][2].second] + arr[y + tetromino[i][3].first][x + tetromino[i][3].second]; max = max > res ? max : res; } } } return max; } int main() { cin >> N >> M; for (int y = 1; y <= N; y++) for (int x = 1; x <= M; x++) { cin >> arr[y][x]; } cout << brute_force(); } ================================================ FILE: BOJ/14501.퇴사/6047198844.py ================================================ # 현재 시점을 기점으로 만들수있는 최대 이익을 반환한다. def dfs(start_day): # 퇴사했으므로 일을 시작할 수 없다. if start_day == N + 1: return 0 global memo # 현재 시점이 저장되어 있는가? if memo[start_day] != -1: return memo[start_day] # 현재 시점의 누적금액. 아직 일을 진행하지 않은 상태이다. res = 0 # 현재시점을 진행하는데 드는 비용 = (시간비용, 돈비용) time_cost, money_cost = bill[start_day] # 기간내에 일을 끝내고 난 후의 범위 for day in range(time_cost + start_day, N + 2): res = max(res, money_cost + dfs(day)) memo[start_day] = res return memo[start_day] N = int(input()) # (시간 , 비용) bill = [(1, 0)] + [tuple(map(int, input().split())) for _ in range(N)] memo = [-1] * (N + 1) print(dfs(0)) ================================================ FILE: BOJ/14502.연구소/6047198844.py ================================================ #세로크기, 가로크기 import collections import copy from itertools import combinations def spread_virus(board): safe_cnt = 0 Q = collections.deque() for y in range(N): for x in range(M): if board[y][x] == 2: Q.append((y,x)) elif board[y][x] == 0: safe_cnt += 1 while Q: #바이러스 위치 vy, vx = Q.popleft() for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny = vy + dy nx = vx + dx if (0 <= ny < N and 0 <= nx < M) and board[ny][nx] == 0: board[ny][nx] = 2 safe_cnt -= 1 Q.append((ny, nx)) return safe_cnt N, M = map(int, input().split()) #실수 board = [list(map(int, input().split())) for y in range(N)] zero_pos = [(y, x) for y in range(N) for x in range(M) if board[y][x] == 0] res = -1 for wall1, wall2, wall3 in combinations(zero_pos, 3): y_wall1, x_wall1 = wall1 y_wall2, x_wall2 = wall2 y_wall3, x_wall3 = wall3 board[y_wall1][x_wall1] = 1 board[y_wall2][x_wall2] = 1 board[y_wall3][x_wall3] = 1 res = max(res, spread_virus(copy.deepcopy(board))) board[y_wall1][x_wall1] = 0 board[y_wall2][x_wall2] = 0 board[y_wall3][x_wall3] = 0 print(res) ================================================ FILE: BOJ/14502.연구소/rockmiin.py ================================================ from collections import deque import copy import time # st= time.time() def bfs(): # 함수 안에서 전역 변수의 값을 변경하려면 global 키워드를 사용 global res # adj, real_q값을 변경하면 안되니까 깊은 복사를 사용하여 구현 adj_copy= copy.deepcopy(adj) # q= copy.deepcopy(real_q) cnt= 0 q = deque() for i in range(n): for j in range(m): if adj[i][j] == 2: q.append([i, j]) while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+ dx, y+ dy if 0<= tmp_x< n and 0<= tmp_y< m and adj_copy[tmp_x][tmp_y]==0: adj_copy[tmp_x][tmp_y]= 2 q.append([tmp_x, tmp_y]) # adj_copy 값이 바이러스가 다 퍼졌을 시 확인 # for i in adj_copy: # print(i) # print() # adj_copy에서 0의 개수가 res 값보다 크면 change for i in range(n): for j in range(m): if adj_copy[i][j]==0: cnt+=1 res= max(res, cnt) def search_wall(cnt): if cnt==3: # for i in adj: # print(i) # print() bfs() return for i in range(n): for j in range(m): if adj[i][j]== 0: # 모든 경우의 수를 다 돌고 0으로 바꿔준다 다시 adj[i][j]= 1 search_wall(cnt+1) adj[i][j]= 0 n, m= map(int, input().split()) adj= [] res= 0 for i in range(n): adj.append(list(map(int, input().split()))) # 바이러스가 있는 위치를 real_q에 담아놓음음 # real_q=deque() # for i in range(n): # for j in range(m): # if adj[i][j]== 2: # real_q.append([i, j]) # for i in adj: # print(i) # print() search_wall(0) print(res) # print("time :", time.time()-st) # 입력 예시 # 4 6 # 0 0 0 0 0 0 # 1 0 0 0 0 2 # 1 1 1 0 0 2 # 0 0 0 0 0 2 # 출력 예시 # 9 ================================================ FILE: BOJ/14502.연구소/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/14502 14502 연구소 BFS 이용 : 기둥을 3개씩 세우는 모든 경우의 수를 계산한다 N, M이 8보다 작기 때문에 이게 돌아갈까? 하는 걱정을 좀 덜어도 된다. ''' from itertools import combinations def dfs(y, x): for ay, ax in [(0, 1), (1, 0), (0, -1), (-1, 0)]: ny, nx = y + ay, x + ax if 0 <= ny < n and 0 <= nx < m and visited[ny][nx] == 0 and adj[ny][nx] == 0: visited[ny][nx] = 1 dfs(ny, nx) return n, m = map(int, input().split()) adj = [] for i in range(n): adj.append(list(map(int, input().split()))) col_list = [] index = [(y, x) for y in range(n) for x in range(m)] for case in combinations(index, 3): col = [(y, x) for y, x in case if adj[y][x] == 0] if len(col) == 3: col_list.append(col) ret = [] virus_list = [(y, x) for y in range(n) for x in range(m) if adj[y][x] == 2] column_num = sum([row.count(1) for row in adj]) + 3 for col in col_list: for y, x in col: adj[y][x] = 1 visited = [[0 for _ in range(m)] for _ in range(n)] for y, x in virus_list: visited[y][x] = 1 dfs(y, x) ret.append(sum([row.count(0) for row in visited])-column_num) for y, x in col: adj[y][x] = 0 print(max(ret)) ''' 항상 풀이할 때 수학적인 부분으로 해결이 가능한지 고민하다 보니 시간이 걸린 문제 N, M 이 8 이하인 것 보고 컴퓨터 식으로 일일이 해결해야 된다고 생각 ''' ================================================ FILE: BOJ/14503.로봇 청소기/6047198844.py ================================================ # 문제 # 로봇 청소기가 주어졌을 때, 청소하는 영역의 개수를 구하는 프로그램을 작성하시오. # 로봇 청소기가 있는 장소는 N×M 크기의 정사각형이다. # 각각의 칸은 벽 또는 빈 칸이다. 청소기는 바라보는 방향이 있으며, 이 방향은 동, 서, 남, 북중 하나이다. # 로봇 청소기는 다음과 같이 작동한다. # # 1. 현재 위치를 청소한다. # 2. 현재 위치에서 현재 방향을 기준으로 왼쪽 방향부터 차례대로 인접한 칸을 탐색한다. # a. 왼쪽 방향에 아직 청소하지 않은 공간이 존재한다면, 그 방향으로 회전한 다음 한 칸을 전진하고 1번부터 진행한다. # b. 왼쪽 방향에 청소할 공간이 없다면, 그 방향으로 회전하고 2번으로 돌아간다. # c. 네 방향 모두 청소가 이미 되어있거나 벽인 경우에는, 바라보는 방향을 유지한 채로 한 칸 후진을 하고 2번으로 돌아간다. # d. 네 방향 모두 청소가 이미 되어있거나 벽이면서, 뒤쪽 방향이 벽이라 후진도 할 수 없는 경우에는 작동을 멈춘다. # 로봇 청소기는 이미 청소되어있는 칸을 또 청소하지 않으며, 벽을 통과할 수 없다. # # 입력 # 첫째 줄에 세로 크기 N과 가로 크기 M이 주어진다. (3 ≤ N, M ≤ 50) # 둘째 줄에 로봇 청소기가 있는 칸의 좌표 (r, c)와 바라보는 방향 d가 주어진다. d가 0인 경우에는 북쪽을, 1인 경우에는 동쪽을, 2인 경우에는 남쪽을, 3인 경우에는 서쪽을 바라보고 있는 것이다. # 셋째 줄부터 N개의 줄에 장소의 상태가 북쪽부터 남쪽 순서대로, 각 줄은 서쪽부터 동쪽 순서대로 주어진다. 빈 칸은 0, 벽은 1로 주어진다. 지도의 첫 행, 마지막 행, 첫 열, 마지막 열에 있는 모든 칸은 벽이다. # 로봇 청소기가 있는 칸의 상태는 항상 빈 칸이다. # # 출력 # 로봇 청소기가 청소하는 칸의 개수를 출력한다. import sys # 행 / 열 N, M = map(int, sys.stdin.readline().split()) r, c, d = map(int, sys.stdin.readline().split()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] clear = set() while True: # 현재 위치를 청소한다. clear.add((r, c)) # 4 방향 탐색 for _ in range(4): # 상 if d == 0: # 좌로 회전 d = 3 # 벽 / 청소한 경우. if board[r][c - 1] == 1 or (r, c - 1) in clear: continue else: c -= 1 break # 우 elif d == 1: # 상으로 회전 d = 0 # 벽 / 청소한 경우. if board[r - 1][c] == 1 or (r - 1, c) in clear: continue else: r -= 1 break # 하 elif d == 2: # 우로 회전 d = 1 # 벽 / 청소한 경우. if board[r][c + 1] == 1 or (r, c + 1) in clear: continue else: c += 1 break # 좌 else: # 하로 회전 d = 2 # 벽 / 청소한 경우. if board[r + 1][c] == 1 or (r + 1, c) in clear: continue else: r += 1 break # 네 방향 모두 청소가 되어있는 경우 else: # 상 if d == 0: # 벽이 아님 if board[r + 1][c] != 1: r += 1 else: break # 우 elif d == 1: # 벽이 아님 if board[r][c - 1] != 1: c -= 1 else: break # 하 elif d == 2: # 벽이 아님 if board[r - 1][c] != 1: r -= 1 else: break # 좌 else: # 벽이 아님 if board[r][c + 1] != 1: c += 1 else: break print(len(clear)) ================================================ FILE: BOJ/14575.뒤풀이/6047198844.py ================================================ # 문제 # # 도현이는 우선 각 사람에게 어느 정도 마시면 기분이 좋은지(Li)와, 어느 정도 마시면 힘든지(Ri)를 물어보았다. # 도현이는 정확히 T의 술을 결제하였다. # 이제 도현이는 모든 사람 i에게 Li이상 Ri이하의 술을 주면서, 그 총합이 정확히 T가 되도록 술을 분배하려고 한다. # 도현이는 S의 값을 정하고, 각 사람에게 그 사람이 원하는 술의 양이 얼마이던지 관계없이 S이하의 술만을 주려고 한다. # 모든 사람 i가 Li이상 Ri이하의 술을 받으면서, # 모든 사람이 받은 술의 총합이 정확히 T가 되고, # 어떤 사람도 S를 초과하는 술은 받지 않게 할 수 있는, # 그러한 S값만 결정하면 된다. # 도현이를 도와 조건을 만족하는 S값을 찾아주도록 하자. # 만약 그런 값이 여러 개라면, 도현이는 그 중 가장 작은 값을 찾고 싶다. # # 입력 # 첫째 줄에 대회 참가자의 수 N과 술의 총량 T가 주어진다. (1 ≤ N ≤ 1000, 1 ≤ T ≤ 10^9) # # 둘째 줄부터 N개의 줄에 걸쳐, 각 사람에 대한 Li와 Ri값이 주어진다. (1 ≤ Li ≤ Ri ≤ 106) # # 출력 # 만약 S의 값과는 관계없이 항상 불가능하다면 첫째 줄에 -1만을 출력한다. # # 문제의 조건을 만족하는 S값이 존재한다면 가장 작은 값 하나를 출력한다. N, T = map(int, input().split()) drinks = [tuple(map(int, input().split())) for _ in range(N)] min_list, max_list = zip(*drinks) min_sum = sum(min_list) max_sum = sum(max_list) # 최저로 소비 || 최대로 소비 if min_sum > T or max_sum < T: print(-1) exit() begin = min(min_list) end = max(max_list) + 1 def is_possible(S): more = 0 for L, R in drinks: if S < L: return False more += min(S, R) - L return more >= T - min_sum while begin < end: mid = (begin + end) // 2 # 가능하지? 가능하다면 범위를 좁힌다. if is_possible(mid): end = mid else: begin = mid + 1 print(end) ================================================ FILE: BOJ/14582.오늘도 졌다/6047198844.py ================================================ import sys ul = list(map(int, sys.stdin.readline().split())) st = list(map(int, sys.stdin.readline().split())) ul_res = 0 st_res = 0 for i in range(9): ul_res += ul[i] if ul_res > st_res: print('Yes') exit() st_res += st[i] print('No') ================================================ FILE: BOJ/1463. 1로 만들기/rockmiin.py ================================================ n= int(input()) dp= [0] * (n+1) for i in range(2, n+1): dp[i]= dp[i-1] +1 if i%3== 0: dp[i]= min(dp[i], dp[i//3] +1) if i%2== 0: dp[i]= min(dp[i], dp[i//2]+ 1) print(dp[n]) ================================================ FILE: BOJ/14712.넴모넴모 (Easy)/6047198844.py ================================================ # 문제 # 이 게임의 규칙은 아주 간단하다. # 격자판의 비어 있는 칸을 임의로 골라 “넴모”를 하나 올려놓거나, “넴모”가 올라간 칸 네 개가 2 × 2 사각형을 이루는 부분을 찾아 그 위에 있는 “넴모”들을 모두 없애는 것을 질릴 때까지 반복하면 된다. # 네모는 게임을 적당히 플레이하다가, “넴모”를 없애고 싶은데 격자판 위에 없앨 수 있는 “넴모”가 없으면 게임을 그만두기로 했다. 네모가 게임을 그만두었을 때 나올 수 있는 “넴모”의 배치의 가짓수를 구하여라. # # 입력 # 첫 번째 줄에 격자판의 행의 개수 N, 열의 개수 M(1 ≤ N, M ≤ 25, 1 ≤ N × M ≤ 25)이 공백으로 구분되어 주어진다. # # 출력 # 첫 번째 줄에 주어진 격자판에서 나올 수 있는, “넴모”들이 올라간 칸이 2 × 2 사각형을 이루지 않는 모든 배치의 가짓수를 출력한다. # 브루트 포스 # 근거 : 2^25 = 33,554,432 < 1억 import sys N, M = map(int, sys.stdin.readline().split()) board = [[0 for _ in range(M)] for _ in range(N)] # y, x를 기점으로 하는 board 를 만들고 평가한다. def dfs(y, x): # base case.1 : 끝까지 도달했을떄. if y == N: return 1 # base case.2 : x 끝까지 도착했을떄. if x == M: return dfs(y + 1, 0) # 두가지 경우에 대해 관찰한다. # 넴모를 올리는 경우는 1, 넴모를 올리지 않는 경우는 0 이라고 가정한다. res = 0 board[y][x] = 0 res += dfs(y, x + 1) board[y][x] = 1 if 0 <= y - 1 < N and 0 <= x - 1 < M and board[y-1][x] == board[y-1][x-1] == board[y][x-1] == board[y][x]: return res res += dfs(y, x + 1) return res print(dfs(0, 0)) ================================================ FILE: BOJ/14719. 빗물/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/14719 빗물 [풀이] 1. 20칸인 기차 생성 2. 각 액션들을 인덱스 번호로 실행할 수 있도록 선언 => exec 사용 => lambda 에서는 할당이 안되므로 3. 열차칸을 문자열로 만들고 set()으로 중복 조사. ''' import sys input = sys.stdin.readline input() blocks = [i for i in map(int, input().strip().split())] left_block = rain = stagnant_rain = 0 for idx, block in enumerate(blocks): left_block = max(block, left_block) rain = left_block - block if rain > 0: right_block = block for next_b in blocks[idx+1:]: right_block = max(right_block, next_b) if right_block >= left_block: break stagnant_rain += min(left_block, right_block) - block print(stagnant_rain) ================================================ FILE: BOJ/14722.우유 도시/6047198844.py ================================================ # 문제 # 딸기우유 -> 초코우유 -> 바나나우유 # 이 도시는 정사각형 형태의 2차원 격자 모양으로 총 N*N개의 우유 가게들이 있다. # 영학이는 도시의 서북쪽 끝 (1, 1)에서 출발해서 동남쪽 아래 (N, N)까지 까지 가면서 우유를 사 마신다. # 각각의 우유 가게는 딸기, 초코, 바나나 중 한 종류의 우유만을 취급한다. # 각각의 우유 가게 앞에서, 영학이는 우유를 사 마시거나, 사 마시지 않는다. # 영학이는 오직 동쪽 또는 남쪽으로만 움직이기 때문에 한 번 지나친 우유 가게에는 다시 가지 않는다. # 영학이가 마실 수 있는 우유의 최대 개수를 구하여라. # # 입력 # 첫 번째 줄에는 우유 도시의 영역 크기 N이 주어진다. (1 ≤ N ≤ 1000) # 두 번째 줄부터 N+1 번째 줄까지 우유 도시의 정보가 주어진다. # 0은 딸기우유만을 파는 가게, 1은 초코우유만을 파는 가게, 2는 바나나우유만을 파는 가게를 뜻하며, 0, 1, 2 외의 정수는 주어지지 않는다. # # 출력 # 영학이가 마실 수 있는 우유의 최대 개수를 출력하시오. import sys N = int(sys.stdin.readline()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] # 딸기우유 / 초코우유 / 바나나우유 를 마지막으로 먹었을때 먹은 우유의 수를 메모한다. memo = [[[0 for _ in range(3)] for _ in range(N)] for _ in range(N)] # base case 1 : 딸기우유를 마신다 if board[0][0] == 0: memo[0][0][0] = 1 for y in range(N): for x in range(N): # 북쪽에서 온 경우 / 서쪽에서 온경우 for dy, dx in (0, -1), (-1, 0): ny, nx = y + dy, x + dx if 0 <= ny < N and 0 <= nx < N: for i in range(3): memo[y][x][i] = max(memo[y][x][i], memo[ny][nx][i]) # 현재 상점의 우유 종류 cur_milk_type = board[y][x] # 이전 우유 종류 pre_milk_type = (cur_milk_type - 1) % 3 # 이전에 우유를 마신 상태여야한다. if memo[y][x][pre_milk_type] != 0: memo[y][x][cur_milk_type] = max(memo[ny][nx][pre_milk_type] + 1, memo[y][x][cur_milk_type]) # 이전에 안마셨다면 지금 마신다. elif cur_milk_type == 0: memo[y][x][cur_milk_type] = 1 print(max(memo[N-1][N-1])) ================================================ FILE: BOJ/14725.개미굴/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) foods = [sys.stdin.readline().rstrip().split() for _ in range(N)] ant = {} for i in range(N): node = ant for food in foods[i][1:]: # 노드가 없으면 생성하고 있으면 생성하지 않는다. if food not in node: node[food] = {} # 다음노드로 파고든다. node = node[food] def func(ant, i): keys = sorted(ant.keys()) for key in keys: print('--' * i + key) func(ant[key], i + 1) func(ant, 0) ================================================ FILE: BOJ/14727.퍼즐 자르기/6047198844.cpp ================================================ #include #include #include #define LL long long using namespace std; LL divide_and_conquer(int start, int end, vector &arr) { if (start == end) return arr[start]; int mid = (start + end) / 2; int mid_left = mid; int mid_right = mid + 1; LL left_side = divide_and_conquer(start, mid_left, arr); LL right_side = divide_and_conquer(mid_right, end, arr); LL res = max(left_side, right_side); LL height = min(arr[mid_left], arr[mid_right]); res = max(res, height * 2); while (mid_left > start || mid_right < end) { // ϴ if (mid_left != start && (mid_right == end || (arr[mid_left-1]>arr[mid_right+1]))) height = min(height, arr[--mid_left]); // ϴ else height = min(height, arr[++mid_right]); res = max(res, (mid_right - mid_left + 1) * height); } return res; } int main() { int N; cin >> N; vector arr(N); for (int i = 0; i < N; i++) cin >> arr[i]; cout << divide_and_conquer(0, N - 1, arr); } ================================================ FILE: BOJ/14729.칠무해/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) students = [float(sys.stdin.readline()) for _ in range(N)] students.sort() for i in range(7): print(format(students[i], ".3f")) ================================================ FILE: BOJ/1484.다이어트/6047198844.py ================================================ import sys G = int(sys.stdin.readline()) arr = list() # i = x+y # j = x-y for i in range(G, 0, -1): # 나누어 떨어진다면. if G % i == 0: j = G // i if j > i: break x = (i + j) // 2 y = (i - j) // 2 if y > 0 and (i + j) % 2 == 0: arr.append((i + j) // 2) arr.sort() if arr: for i in arr: print(i) else: print(-1) # 4 ================================================ FILE: BOJ/1487.물건 팔기/6047198844.py ================================================ # N명의 사람과, 각각의 사람이 지불할 용의가 있는 최대 금액과 배송비가 주어졌을 때, 세준이의 이익을 최대로 하는 가격을 출력하는 프로그램을 작성하시오. # 세준이가 안 팔수도 있다. # 1000000 -> brute force N = int(input()) pays = list() for _ in range(N): pays.append(tuple(map(int, input().split()))) pays.sort() res = 0 benefit = 0 for real_price, _ in pays: acc = 0 for pay in pays: affordable_price, delivery_price = pay # 고객이 사는 경우 / 세준이가 파는 경우 if affordable_price >= real_price and real_price - delivery_price > 0: acc += real_price - delivery_price if acc > benefit: benefit = acc res = real_price print(res) ================================================ FILE: BOJ/14888.연산자 끼워넣기/6047198844.cpp ================================================ #include #include using namespace std; int res_min = 1000000000; int res_max = -1000000000; int N; //res () number[idx] ؼ res ִ´. void brute_force(vector const number, vector& oper, int idx, int res) { // ʴ´. if (idx == N) { if (res > res_max) res_max = res; if (res < res_min) res_min = res; return; } // ϴ // . . . for (int i = 0; i < 4; i++) { if (oper[i] > 0) { --oper[i]; switch (i) { case 0: brute_force(number, oper, idx + 1, res + number[idx]); break; case 1: brute_force(number, oper, idx + 1, res - number[idx]); break; case 2: brute_force(number, oper, idx + 1, res * number[idx]); break; case 3: brute_force(number, oper, idx + 1, res / number[idx]); break; } ++oper[i]; } } return; } int main() { cin >> N; vector number(N); for (int i = 0; i < N; i++) cin >> number[i]; vector oper(4); for (int i = 0; i < 4; i++) cin >> oper[i]; brute_force(number, oper, 1, number[0]); cout << res_max << "\n"; cout << res_min << "\n"; } ================================================ FILE: BOJ/14888.연산자 끼워넣기/ms9849.cpp ================================================ #include #include using namespace std; vector v; int Cnt_op[4]; // 연산자 갯수를 저장하는 배열 int N,num; int Max=-1000000001, Min=1000000001; void Recursion(int depth, int value) { int next_depth = depth+1; // depth+1 int next_value; // 다음 재귀에 들어갈 값을 담는 변수 if(depth==N) {// 재귀 탈출 조건. 이 때 벡터에 0부터 입력받았으므로 depth가 N이면 v[N-1]까지의 연산을 완료한 것이다. if(Max < value) Max = value; if(Min > value) Min = value; return; } if(Cnt_op[0] != 0) { // + 연산자 Cnt_op[0]--; next_value = value + v[depth]; Recursion(next_depth, next_value); Cnt_op[0]++; } if(Cnt_op[1] != 0) { // - 연산자 Cnt_op[1]--; next_value = value - v[depth]; Recursion(next_depth, next_value); Cnt_op[1]++; } if(Cnt_op[2] != 0) { // * 연산자 Cnt_op[2]--; next_value = value * v[depth]; Recursion(next_depth, next_value); Cnt_op[2]++; } if(Cnt_op[3] != 0) { // / 연산자 Cnt_op[3]--; next_value = value / v[depth]; Recursion(next_depth, next_value); Cnt_op[3]++; } } int main(void) { cin >> N; for(int i=0; i> num; v.push_back(num); } for(int i=0; i<4; i++) cin >> Cnt_op[i]; Recursion(1,v[0]); // 재귀를 이용하여 브루트 포스를 수행, 모든 값을 일일이 구해서 비교한다. cout << Max << "\n" << Min; return 0; } ================================================ FILE: BOJ/14889. 스타트와 링크/ms9849.cpp ================================================ #include #include using namespace std; int N; int arr[21][21]; int checked[21]; int Min=100000000; void Recursion(int match,int depth) { int next_depth = depth+1; if(depth == N/2) { int comp1=0,comp2=0,ans; for(int i=1; i<=N; i++) { for(int j=1; j<=N; j++) { if(checked[i]==0 && checked[j]==0) // 한 팀에 있는 사람들끼리의 arr값을 합침 comp1+= arr[i][j]; else if(checked[i]==1 && checked[j]==1) // 나머지 팀에 있는 사람들끼리 arr 값을 합침 comp2+= arr[i][j]; } } ans = abs(comp1-comp2); if(Min > ans) Min = ans; return; } for(int i=match+1; i> N; for(int i=1; i<=N; i++) for(int j=1; j<=N; j++) cin >> arr[i][j]; for(int i=1; i<=N; i++) { checked[i] = 1; Recursion(i,1); checked[i] = 0; } cout << Min; return 0; } ================================================ FILE: BOJ/14890.경사로/6047198844.py ================================================ N, L = map(int, input().split()) arr = [list(map(int, input().split())) for _ in range(N)] # 이전 블록, 현재 위치, 이전에 두었는지 def func(cy, cx, dy, dx, visited): if cy == N or cx == N: return True # 이전이 없는 경우 if (cy == 0 and dy == 1) or (cx == 0 and dx == 1): return func(cy + dy, cx + dx, dy, dx, visited) py, px = cy - dy, cx - dx # 이전과 같은 경우 if arr[py][px] == arr[cy][cx]: return func(cy + dy, cx + dx, dy, dx, visited) # 이전과 1 이상 차이나는 경우 if abs(arr[py][px] - arr[cy][cx]) != 1: return False # 이전이 1 만큼 작은 경우 if arr[py][px] - arr[cy][cx] == -1: for i in range(1, L + 1): ny, nx = cy - (i * dy), cx - (i * dx) # 이전 칸에 놓을수 있는 경우 if not (0 <= ny < N and 0 <= nx < N) or arr[py][px] != arr[ny][nx] or (ny, nx) in visited: return False visited.add((ny,nx)) # 다음칸 return func(cy + dy, cx + dx, dy, dx, visited) # 이전이 1 만큼 큰 경우 for i in range(L): ny, nx = cy + (i * dy), cx + (i * dx) # 현재 칸에 놓을수 있는 경우 if not (0 <= ny < N and 0 <= nx < N) or arr[cy][cx] != arr[ny][nx] or (ny, nx) in visited: return False visited.add((ny, nx)) return func(cy + (dy * L), cx + (dx * L), dy, dx, visited) res = 0 for y in range(N): visited = set() res += func(y, 0, 0, +1, visited) for x in range(N): visited = set() res += func(0, x, +1, 0, visited) print(res) ================================================ FILE: BOJ/14912.숫자 빈도수/6047198844.py ================================================ import sys from collections import Counter n, d = map(int, sys.stdin.readline().split()) counter = Counter() for i in range(1, n + 1): counter += Counter(str(i)) print(counter.get(str(d))) ================================================ FILE: BOJ/14916.거스름돈/6047198844.py ================================================ n = int(input()) res = -1 five = 0 while five * 5 <= n: if (n - five * 5) % 2 == 0: res = five + (n - five * 5) // 2 five += 1 print(res) ================================================ FILE: BOJ/14928.큰 수 (BIG)/6047198844.py ================================================ print(int(input()) % 20000303) ================================================ FILE: BOJ/1503.세 수 고르기/6047198844.py ================================================ # 문제 # M개의 자연수로 이루어진 집합 S와 자연수 N이 주어진다. # # S에 속하지 않는 자연수 x, y, z를 골라서, |N - xyz|의 최솟값을 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 N(1 ≤ N ≤ 1,000)과 집합 S의 크기 M(0 ≤ M ≤ 50)이 주어진다. 둘째 줄에는 집합 S에 들어있는 수가 주어진다. 집합에 들어있는 수는 1,000보다 작거나 같은 자연수이고, 공백으로 구분되어져 있다. 또, 중복되는 수는 없다. # # 집합의 크기가 0인 경우에는 둘째 줄은 빈 줄이다. # # 출력 # 첫째 줄에 |N - xyz|의 최솟값을 출력한다. N, M = map(int, input().split()) S = set(map(int, input().split())) ans = 987654321 for x in range(1, 1000 + 1): if x in S: continue for y in range(x, 1000 + 1): if y in S: continue for z in range(y, 1001 + 1): if z in S: continue ans = abs(N - x*y*z) print(ans) ================================================ FILE: BOJ/1504.특정한 최단 경로/6047198844.cpp ================================================ #include #include #include #include #include #define INF 987654321 using namespace std; vector > graph[801]; vector dijkstra(int N,int v) { vector dest(N + 1, INF); priority_queue > pq; pq.push({ 0,v }); dest[v] = 0; while (!pq.empty()) { int cost = -pq.top().first; int here = pq.top().second; pq.pop(); if (cost > dest[here]) continue; for (auto node : graph[here]) { if (dest[node.first] > cost + node.second) { dest[node.first] = cost + node.second; pq.push({ -dest[node.first], node.first }); } } } return dest; } int main() { int N, E; cin >> N >> E; int a, b, c; while (E--) { cin >> a >> b >> c; graph[a].push_back({ b,c }); graph[b].push_back({ a,c }); } int v1, v2; cin >> v1 >> v2; vector start_di = dijkstra(N, 1); vector dist_v1 = dijkstra(N, v1); vector dist_v2 = dijkstra(N, v2); //오버플로우. int cnt = INF; int res; // 1 -> v1 -> v2 -> N // 1 -> v2 -> v1 -> N res = min(start_di[v1] + dist_v1[v2] + dist_v2[N], start_di[v2] + dist_v2[v1] + dist_v1[N]); if (res < INF && res > 0) cout << res; else cout << "-1"; } //edge가 반드시 최저라는 보장이 없다. //INF를 ================================================ FILE: BOJ/1509.팰린드롬 분할/6047198844.py ================================================ # 문제 # 세준이는 어떤 문자열을 팰린드롬으로 분할하려고 한다. 예를 들어, ABACABA를 팰린드롬으로 분할하면, {A, B, A, C, A, B, A}, {A, BACAB, A}, {ABA, C, ABA}, {ABACABA}등이 있다. # # 분할의 개수의 최솟값을 출력하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 문자열이 주어진다. 이 문자열은 알파벳 대문자로만 이루어져 있고, 최대 길이는 2,500이다. # # 출력 # 첫째 줄에 팰린드롬 분할의 개수의 최솟값을 출력한다. import math arr = list(input()) N = len(arr) is_palindrome = [[False for _ in range(N + 1)] for _ in range(N + 1)] # 크기 1일때 -> 항상 true for i in range(1, N+1): is_palindrome[i][i] = True # 크기 2일때 -> 같으면 true for i in range(N): is_palindrome[i][i+1] = arr[i] == arr[i+1] # 크기 3일때 ~ 크기 N for k in range(2, N): for i in range(N-k): if arr[i] == arr[i+k]: is_palindrome[i][i+k] = is_palindrome[i+1][i+k-1] memo = [math.inf for _ in range(N+1)] memo[1] = 1 for end in range(1, N): for begin in range(1, end + 1): if is_palindrome[begin][end]: memo[end+1] = min(memo[end + 1], memo[end] + 1) print(memo[N]) for i in range(1, n+1): dp[i][i] = 1 for i in range(1, n): if a[i-1] == a[i]: dp[i][i+1] = 1 for i in range(2, n): for j in range(1, n+1-i): if a[j-1] == a[j+i-1] and dp[j+1][i+j-1] == 1: dp[j][i+j] = 1 for i in range(1, n+1): result[i] = min(result[i], result[i-1] + 1) # result[i-1]+1인 이유는 result[i-1]까지의 팰린드롭에 j부터 i까지의 팰린드롭 한개를 더하는 것이기 때문이다 for j in range(i+1, n+1): if dp[i][j] != 0: # 팰린드롭이면 result[j] = min(result[j], result[i-1] + 1) print(result[n]) ================================================ FILE: BOJ/1516.게임 개발/6047198844.py ================================================ import sys from collections import defaultdict, deque N = int(sys.stdin.readline()) indegrees = [0 for _ in range(N+1)] edges = defaultdict(list) times = [0 for _ in range(N+1)] for V in range(1, N + 1): cmd = list(map(int, sys.stdin.readline().split())) times[V] = cmd[0] for W in cmd[1:-1]: edges[W].append(V) indegrees[V] += 1 Q = deque() res = [0 for _ in range(N+1)] for V in range(1, N+1): if indegrees[V] == 0: Q.append(V) res[V] = times[V] while Q: V = Q.popleft() for W in edges[V]: indegrees[W] -= 1 res[W] = max(res[V] + times[W], res[W]) if indegrees[W] == 0: Q.append(W) for V in range(1, N+1): print(res[V]) ================================================ FILE: BOJ/1520.내리막길/6047198844.cpp ================================================ #include #include using namespace std; int arr[500][500]; int memo[500][500]; bool check[500][500]; int dx[4] = {-1,+1, 0, 0}; int dy[4] = { 0, 0,-1,+1}; int M; int N; bool check_arr(int y, int x) { if (y < 0 || y >= M) return false; if (x < 0 || x >= N) return false; if (check[y][x]&&memo[y][x]==-1) return false; return true; } int dfs(int y, int x) { if (memo[y][x] != -1) return memo[y][x]; if (y == M - 1 && x == N - 1) return 1; int res = 0; for (int i = 0; i < 4; i++) { if (check_arr(y + dy[i], x + dx[i])&&arr[y][x]>arr[y+dy[i]][x+dx[i]]) { check[dy[i] + y][dx[i] + x] = true; res += dfs(y + dy[i], x + dx[i]); } } return memo[y][x] = res; } int main() { cin >> M >> N; for (int y = 0; y < M; y++) for (int x = 0; x < N; x++) cin >> arr[y][x]; memset(memo, -1, sizeof(arr)); memset(check, false, sizeof(check)); check[0][0] = true; memo[M - 1][N - 1] = 1; cout << dfs(0, 0); } ================================================ FILE: BOJ/15312.이름 궁합/6047198844.py ================================================ A = input() B = input() score = [3, 2, 1, 2, 3, 3, 2, 3, 3, 2, 2, 1, 2, 2, 1, 2, 2, 2, 1, 2, 1, 1, 1, 2, 2, 1] name = '' for i in range(len(A)): name += A[i] + B[i] res = '' for word in name: idx = ord(word) - ord('A') res += str(score[idx]) while len(res) != 2: tmp = '' for i in range(len(res)-1): tmp += str((int(res[i]) + int(res[i+1]))%10) res = tmp print(res) ================================================ FILE: BOJ/1541.잃어버린 괄호/6047198844.cpp ================================================ #include #include using namespace std; int main() { vector arr; int N; cin >> N; char op; arr.push_back(N); while (cin >> op >> N) { if (op == '-') arr.push_back(N); else arr[arr.size() - 1] = arr.back() + N; } int res = arr[0]; for (int i = 1; i < arr.size(); i++) res -= arr[i]; cout << res; } ``` ================================================ FILE: BOJ/1541.잃어버린 괄호/ms9849.cpp ================================================ #include using namespace std; int result=0,tmp; string s; int Flag = 0; int main(void) { cin >> s; int len = s.length(); for(int i=0; i<=s.length(); i++) { if(s[i] == '+' || s[i] == '-' || i== len) { if(Flag == 0) result += tmp; else result -= tmp; tmp = 0; if(s[i] == '-') Flag = 1; } else { tmp *= 10; tmp += s[i] -'0'; } } cout << result; return 0; } ================================================ FILE: BOJ/15439.Vera and Outfits/6047198844.py ================================================ N = int(input()) print(N * (N-1)) ================================================ FILE: BOJ/1550.16진수/6047198844.py ================================================ print(int(input(), 16)) ================================================ FILE: BOJ/15591.MooTube (Silver)/6047198844.cpp ================================================ #include #include #include #include using namespace std; int node[5001]; bool check[5001]; vector > edge[5001]; void dfs(int n) { check[n] = true; int edge_size = edge[n].size(); for (int i = 0; i < edge_size; i++) { if (!check[edge[n][i].first]) { node[edge[n][i].first] = !node[n] ? edge[n][i].second : node[n] < edge[n][i].second ? node[n] : edge[n][i].second; dfs(edge[n][i].first); } } return; } int main() { int N; int Q; cin >> N >> Q; int p; int q; int r; for (int i = 0; i < N-1; i++) { cin >> p >> q >> r; edge[p].push_back({ q,r }); edge[q].push_back({ p,r }); } int k; int v; for (int i = 0; i < Q; i++) { memset(node, 0, sizeof(node)); memset(check, false, sizeof(check)); cin >> k >> v; dfs(v); cout << count_if(node + 1, node + N + 1, [=](int elem) { return elem >= k; }) << "\n"; } } ================================================ FILE: BOJ/1562.계단 수/6047198844.py ================================================ # memo[마지막수][방문] ''' memo[0][0000000001] = 0 memo[1][0000000010] = 1 ... ... memo[9][1000000000] = 1 ''' N = int(input()) memo = [[[0 for _ in range(1 << 10)] for _ in range(10)] for _ in range(N+1)] for num in range(1, 9 + 1): memo[1][num][1 << num] = 1 # 길이가 2인 경우부터 for S in range(2, N + 1): # 끝이 0인 경우. 끝자리가 1인 경우를 모두 합친다. for k in range(1 << 10): memo[S][0][k | (1 << 0)] += memo[S-1][1][k] % 1000000000 # 끝이 1~8인 경우 for num in range(1, 8 + 1): for k in range((1 << 10)): memo[S][num][k | (1 << num)] += (memo[S-1][num - 1][k] % 1000000000 + memo[S-1][num + 1][k] % 1000000000) % 1000000000 # 끝이 9인 경우. 끝자리가 8인 경우를 모두 합친다. for k in range((1 << 10)): memo[S][9][k | (1 << 9)] += memo[S-1][8][k] % 1000000000 res = 0 for i in range(9 + 1): res += memo[N][i][(1 << 10) - 1] % 1000000000 print(res % 1000000000) ================================================ FILE: BOJ/15652.N과 M (4)/6047198844.cpp ================================================ //자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. // //1부터 N까지 자연수 중에서 M개를 고른 수열 //같은 수를 여러 번 골라도 된다. //고른 수열은 비내림차순이어야 한다. //길이가 K인 수열 A가 A1 ≤ A2 ≤ ... ≤ AK - 1 ≤ AK를 만족하면, 비내림차순이라고 한다. // //입력 //첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8) // //출력 //한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. // //수열은 사전 순으로 증가하는 순서로 출력해야 한다. #include #include using namespace std; int N; int M; vector vt; void brute_force(int start, int cnt) { if (cnt == M) { for (auto i : vt) cout << i << " "; cout << "\n"; return; } for (int i = start; i <= N; i++) { vt.push_back(i); brute_force(i, cnt + 1); vt.pop_back(); } } int main() { cin >> N >> M; brute_force(1, 0); } ================================================ FILE: BOJ/15680.연세대학교/6047198844.py ================================================ N = int(input()) if N == 0: print('YONSEI') else: print('Leading the Way to the Future') ================================================ FILE: BOJ/15686.치킨 배달/6047198844.py ================================================ # 문제 # 크기가 N×N인 도시가 있다. # 도시의 각 칸은 빈 칸, 치킨집, 집 중 하나이다. 도시의 칸은 (r, c)와 같은 형태로 나타내고, r행 c열 또는 위에서부터 r번째 칸, 왼쪽에서부터 c번째 칸을 의미한다. r과 c는 1부터 시작한다. # # 치킨 거리는 집과 가장 가까운 치킨집 사이의 거리이다. # 즉, 치킨 거리는 집을 기준으로 정해지며, 각각의 집은 치킨 거리를 가지고 있다. 도시의 치킨 거리는 모든 집의 치킨 거리의 합이다. # # 임의의 두 칸 (r1, c1)과 (r2, c2) 사이의 거리는 |r1-r2| + |c1-c2|로 구한다. # # 예를 들어, 아래와 같은 지도를 갖는 도시를 살펴보자. # # 0 2 0 1 0 # 1 0 1 0 0 # 0 0 0 0 0 # 0 0 0 1 1 # 0 0 0 1 2 # 0은 빈 칸, 1은 집, 2는 치킨집이다. # # (2, 1)에 있는 집과 (1, 2)에 있는 치킨집과의 거리는 |2-1| + |1-2| = 2, (5, 5)에 있는 치킨집과의 거리는 |2-5| + |1-5| = 7이다. 따라서, (2, 1)에 있는 집의 치킨 거리는 2이다. # # (5, 4)에 있는 집과 (1, 2)에 있는 치킨집과의 거리는 |5-1| + |4-2| = 6, (5, 5)에 있는 치킨집과의 거리는 |5-5| + |4-5| = 1이다. 따라서, (5, 4)에 있는 집의 치킨 거리는 1이다. # # 이 도시에 있는 치킨집은 모두 같은 프랜차이즈이다. 프렌차이즈 본사에서는 수익을 증가시키기 위해 일부 치킨집을 폐업시키려고 한다. 오랜 연구 끝에 이 도시에서 가장 수익을 많이 낼 수 있는 치킨집의 개수는 최대 M개라는 사실을 알아내었다. # # 도시에 있는 치킨집 중에서 최대 M개를 고르고, 나머지 치킨집은 모두 폐업시켜야 한다. 어떻게 고르면, 도시의 치킨 거리가 가장 작게 될지 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 N(2 ≤ N ≤ 50)과 M(1 ≤ M ≤ 13)이 주어진다. # # 둘째 줄부터 N개의 줄에는 도시의 정보가 주어진다. # # 도시의 정보는 0, 1, 2로 이루어져 있고, 0은 빈 칸, 1은 집, 2는 치킨집을 의미한다. 집의 개수는 2N개를 넘지 않으며, 적어도 1개는 존재한다. 치킨집의 개수는 M보다 크거나 같고, 13보다 작거나 같다. # # 출력 # 첫째 줄에 폐업시키지 않을 치킨집을 최대 M개를 골랐을 때, 도시의 치킨 거리의 최솟값을 출력한다. import heapq import math import sys from itertools import combinations N, M = map(int, sys.stdin.readline().split()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] houses = [] chickens = [] for y in range(N): for x in range(N): if board[y][x] == 1: houses.append((y + 1, x + 1)) elif board[y][x] == 2: chickens.append((y + 1, x + 1)) # chicken 에서 M 개를 중복없이 뽑는다 -> 조합 res = math.inf for picked_chickens in combinations(chickens, M): chicken_distances = 0 for hy, hx in houses: chicken_distance = math.inf for cy, cx in picked_chickens: distance = abs(hy-cy) + abs(hx-cx) if chicken_distance > distance: chicken_distance = distance chicken_distances += chicken_distance if res > chicken_distances: res = chicken_distances print(res) ================================================ FILE: BOJ/15719.중복된 숫자/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) numbers = sys.stdin.readline() sum = 0 temp = "" for num in numbers: if num.isdigit(): temp += num elif num == " ": sum += int(temp) temp = "" sum += int(temp) print(sum - N * (N - 1) // 2) ================================================ FILE: BOJ/15727.조별과제를 하려는데 조장이 사라졌다/6047198844.py ================================================ import math print(math.ceil(int(input()) / 5)) ================================================ FILE: BOJ/15733.나는 누구인가/6047198844.py ================================================ print("I'm Sexy") ================================================ FILE: BOJ/15787.기차가 어둠을 헤치고 은하수를/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/15787 기차가 어둠을 헤치고 은하수를 [풀이] 1. 20칸인 기차 생성 2. 각 액션들을 인덱스 번호로 실행할 수 있도록 선언 => exec 사용 => lambda 에서는 할당이 안되므로 3. 열차칸을 문자열로 만들고 set()으로 중복 조사. ''' import sys input = sys.stdin.readline n, m = map(int, input().strip().split()) train = [['0'] * 20 for _ in range(n)] action = [ lambda x, y : exec('train[x][y] = "1"'), lambda x, y : exec('train[x][y] = "0"'), lambda x, y : exec('train[x] = ["0"] + train[x][:-1]'), lambda x, y : exec('train[x] = train[x][1:] + ["0"]') ] for _ in range(m): ipt = list(map(int, input().strip().split())) if len(ipt) == 3: a, b, c = ipt else: a, b = ipt; c = 0 action[a-1](b-1, c-1) print(len(set([''.join(t) for t in train]))) ================================================ FILE: BOJ/15829.Hashing/6047198844.py ================================================ L = int(input()) line = list(input()) r = 31 M = 1234567891 res = 0 for i in range(L): a = ord(line[i]) - ord('a') + 1 res += (a * r ** i) res %= M print(res) ================================================ FILE: BOJ/15873,공백 없는 A+B/6047198844.py ================================================ nums = input() tmp = '' for i in range(len(nums)): if 0 <= int(tmp + nums[i]) <= 10: tmp += nums[i] else: print(int(nums[:i]) + int(nums[i:])) break ================================================ FILE: BOJ/15904.UCPC는 무엇의 약자일까?/6047198844.py ================================================ from collections import deque res = deque('UCPC') str = input() for char in str: if not res: break if char == res[0]: res.popleft() if res: print("I hate UCPC") else: print("I love UCPC") ================================================ FILE: BOJ/15963.CASIO/6047198844.py ================================================ import sys N, M = map(int, sys.stdin.readline().split()) if N == M: print(1) else: print(0) ================================================ FILE: BOJ/15970.화살표 그리기/6047198844.py ================================================ import math import sys N = int(sys.stdin.readline()) arr = [] for _ in range(N): x, y = map(int, sys.stdin.readline().split()) arr.append((x, y)) arr.sort() res = 0 for i in range(len(arr)): left = i - 1 right = i + 1 diff = math.inf while left >= 0: if arr[left][1] == arr[i][1]: diff = min(diff, arr[i][0] - arr[left][0]) break else: left -= 1 while right < len(arr): if arr[right][1] == arr[i][1]: diff = min(diff, arr[right][0] - arr[i][0]) break else: right += 1 res += diff print(res) ================================================ FILE: BOJ/15993.1, 2, 3 더하기 8/6047198844.py ================================================ T = int(input()) L = list() for _ in range(T): L.append(int(input())) N = sorted(L)[-1] # 0 : 짝수 / 1 : 홀수 memo = [[0, 0] for _ in range(N + 1)] # 1 : 1 memo[1][1] = 1 # 2 : 1+1, 2 memo[2][0] = 1 memo[2][1] = 1 # 3 : 1+1+1, 1+2, 2+1, 3 memo[3][0] = 2 memo[3][1] = 2 for i in range(4, N + 1): # 1더하기 / 2더하기 / 3더하기 memo[i][0] = (memo[i - 1][1] % 1000000009 + memo[i - 2][1] % 1000000009 + memo[i - 3][1] % 1000000009) % 1000000009 memo[i][1] = (memo[i - 1][0] % 1000000009 + memo[i - 2][0] % 1000000009 + memo[i - 3][0] % 1000000009) % 1000000009 for i in L: print(memo[i][1], memo[i][0]) ================================================ FILE: BOJ/1600.말이 되고픈 원숭이/6047198844.cpp ================================================ #include #include using namespace std; int board[200][200][31]; int dy[4] = {0,0,-1,1}; int dx[4] = {-1,1,0,0}; int horse_dy[8] = {-1,-2,-2,-1,1,2, 2, 1}; int horse_dx[8] = {-2,-1, 1, 2,2,1,-1,-2}; bool range(int W,int H, int y, int x) { if (0 > y || y >= H) return false; if (0 > x || x >= W) return false; return true; } int bfs(int W,int H,int K) { if (W == 1 && H == 1) return 0; pair , int> start = { {0,0},K }; queue < pair , int>> q; q.push(start); for(int i=0;i<=K;i++) board[0][0][i] = 1; int res = 0; while (!q.empty()) { int cnt = q.size(); while (cnt--) { int y = q.front().first.first; int x = q.front().first.second; int k = q.front().second; q.pop(); if (y == H - 1 && x == W - 1) return res; //¿ for (int i = 0; i < 4; i++) { int check_y = y + dy[i]; int check_x = x + dx[i]; if (range(W, H, check_y, check_x) && !board[check_y][check_x][k]) { q.push({ { check_y,check_x }, k }); board[check_y][check_x][k] = 1; } } // ϼֳ Ǵ if (k) { --k; for (int i = 0; i < 8; i++) { int check_y = y + horse_dy[i]; int check_x = x + horse_dx[i]; if (range(W, H, check_y, check_x) && !board[check_y][check_x][k]) { q.push({ { check_y,check_x }, k }); board[check_y][check_x][k] = 1; } } } } res++; } return -1; } int main() { int K; cin >> K; int W; int H; cin >> W >> H; for (int y = 0; y < H; y++) for (int x = 0; x < W; x++) { cin >> board[y][x][0]; for (int i = 1; i <= K; i++) board[y][x][i] = board[y][x][0]; } cout << bfs(W,H,K); } ================================================ FILE: BOJ/1613.역사/6047198844.cpp ================================================ #include #include #include #define INF INT_MAX using namespace std; void floyd(vector >&vt,int n) { for (int k = 1; k <= n; k++) for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (i!=j && vt[i][k] != INF && vt[k][j] != INF) vt[i][j] = 1; } int main() { int n, k; scanf("%d %d", &n, &k); vector > vt(n + 1, vector(n + 1,INF)); int i, j; while (k--) { scanf("%d %d", &i, &j); vt[i][j] = 1; } floyd(vt, n); cin >> n; while (n--) { scanf("%d %d", &i, &j); if (vt[i][j] == 1) printf("-1\n"); else if (vt[j][i] == 1) printf("1\n"); else printf("0\n"); } } ================================================ FILE: BOJ/16162.가희와 3단 고음/6047198844.py ================================================ N, A, D = map(int, input().split()) melodies = list(map(int, input().split())) res = 0 cur = A for melody in melodies: if cur == melody: cur += D res += 1 print(res) ================================================ FILE: BOJ/16173.점프왕 쪨리 (Small)/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] visited = set() def func(y, x): if y >= N or x >= N: return False if (y, x) in visited: return False if y == N - 1 and x == N - 1: return True visited.add((y, x)) if func(y + board[y][x], x): return True if func(y, x + board[y][x]): return True if func(0, 0): print('HaruHaru') else: print('Hing') ================================================ FILE: BOJ/16197.두 동전/6047198844.py ================================================ import collections buttons = [(0, -1), (0, 1), (-1, 0), (1, 0)] #y, x N, M = map(int, input().split()) board = [list(input()) for _ in range(N)] coins = list() for y in range(N): for x in range(M): if board[y][x] == 'o': coins.append((y, x)) # ((3, 0), (4, 0)) def bfs(coins): discovered = set() discovered.add(coins) queue = collections.deque() queue.append(coins) cnt = 0 while queue and cnt < 10: cnt += 1 n = len(queue) for _ in range(n): coin1, coin2 = queue.popleft() for button in buttons: dropped_coin = 0 #새로운 동전의 위치 new_coin1 = (coin1[0] + button[0], coin1[1] + button[1]) new_coin2 = (coin2[0] + button[0], coin2[1] + button[1]) ###############동전 위치 조정############### #동전 1이 떨어진 경우 / 범위를 벗어난 경우. if not(0 <= new_coin1[0] < N and 0 <= new_coin1[1] < M): dropped_coin += 1 #동전 1이 #인경우 #버튼 조작을 취소한다. elif board[new_coin1[0]][new_coin1[1]] == '#': new_coin1 = (coin1[0], coin1[1]) #동전 2가 떨어진경우 if not(0 <= new_coin2[0] < N and 0 <= new_coin2[1] < M): dropped_coin += 1 # 동전 2이 #인경우 # 버튼 조작을 취소한다. elif board[new_coin2[0]][new_coin2[1]] == '#': new_coin2 = (coin2[0], coin2[1]) ###############위치 조정 종료############### ###############모든 조작이 완료된 상태############### ###############새로 방문할 필요가 있는지 판단############### # 예외처리 : 이미 발견한 경우 / 안 움직인 경우 if (new_coin1, new_coin2) in discovered: continue #하나도 안떨어진 경우 -> 재평가 / 새로운 발견 if dropped_coin == 0: queue.append((new_coin1, new_coin2)) discovered.add((new_coin1, new_coin2)) #하나만 떨어진경우 -> 정답 elif dropped_coin == 1: return cnt # 실수한 부분 : while문에서 cnt의 범위를 cnt <= 10으로 잡으면 답이 11이 될수있다. #둘다 떨어진경우 -> 평가 종료. return -1 print(bfs(tuple(coins))) ================================================ FILE: BOJ/16198.에너지 모으기/6047198844.py ================================================ N = int(input()) marbles = list(map(int, input().split())) def dfs(marbels:list, acc:int): if len(marbles) == 2: return acc res = 0 for idx in range(1,len(marbles)-1): tmp = marbels.pop(idx) res = max(res,dfs(marbels, acc + marbels[idx-1] * marbels[idx])) marbels.insert(idx,tmp) return res print(dfs(marbles,0)) ================================================ FILE: BOJ/1620.나는야 포켓몬 마스터 이다솜/6047198844.py ================================================ import sys N, M = map(int, sys.stdin.readline().split()) table = dict() for i in map(str, range(1, N + 1)): pokemon = sys.stdin.readline().rstrip() table[pokemon] = i table[i] = pokemon for _ in range(M): print(table[sys.stdin.readline().rstrip()]) ================================================ FILE: BOJ/16204.카드 뽑기/6047198844.py ================================================ # M개 O가 1개 # N-M X가 1개 import sys N, M, K = map(int, sys.stdin.readline().split()) o_num = M x_num = N - M o_write = K x_write = N - K print(min(o_num, o_write) + min(x_num, x_write)) ================================================ FILE: BOJ/16208.귀찮음/6047198844.py ================================================ import sys n = int(input()) bars = list(map(int, sys.stdin.readline().split())) res = 0 s = sum(bars) for bar in bars: res += bar * (s - bar) s -= bar print(res) ================================================ FILE: BOJ/16212.정열적인 정렬/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) a = list(map(int, sys.stdin.readline().split())) a.sort() for i in a: print(i, end=' ') ================================================ FILE: BOJ/16234.인구 이동/6047198844.cpp ================================================ #include #include #include #include using namespace std; const int dy[4] = { -1,+1,0,0 }; const int dx[4] = { 0,0,-1,+1 }; bool rangeCheck(int y, int x, int N) { if (0 <= y && y < N && 0 <= x && x < N) return true; return false; } int bfs(vector> arr,int N,int L, int R) { int cnt = 0; while (1) { bool flag = false; vector < vector < bool >> check(N, vector(N)); for (int y = 0; y < N; y++) { for (int x = 0; x < N; x++) { if (!check[y][x]) { queue > q; queue > cq; check[y][x] = true; q.push({ y,x }); int sum = arr[y][x]; while (!q.empty()) { int y = q.front().first; int x = q.front().second; q.pop(); for (int d = 0; d < 4; d++) { int iy = y + dy[d]; int ix = x + dx[d]; if (rangeCheck(iy, ix, N) && !check[iy][ix]) { int sub = abs(arr[y][x] - arr[iy][ix]); if (L <= sub && sub <= R) { q.push({ iy,ix }); cq.push({ iy,ix }); sum += arr[iy][ix]; check[iy][ix] = true; } } } } int avg; if (cq.size()) { cq.push({ y,x }); avg = sum / cq.size(); flag = true; } while (!cq.empty()) { int y = cq.front().first; int x = cq.front().second; cq.pop(); arr[y][x] = avg; } } } } if (flag) cnt++; else return cnt; } } int main() { int N, L, R; cin >> N >> L >> R; vector> arr(N, vector(N)); for (int y = 0; y < N; y++) for (int x = 0; x < N; x++) cin >> arr[y][x]; cout << bfs(arr, N, L, R); } ================================================ FILE: BOJ/16234.인구 이동/rockmiin.py ================================================ from collections import deque def bfs(v): q= deque([v]) visited[v[0]][v[1]]= 1 area= [v] sum_value= adj[v[0]][v[1]] while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tx, ty= x+ dx, y+ dy if 0<=tx size: continue # 크기가 같은 물고기인 경우 elif arr[ny][nx] == size: Q.append((ny, nx)) visited.add((ny, nx)) # 크기가 작은 물고기인 경우, 큐에는 굳이 넣지않음. else: catch.append((ny, nx)) visited.add((ny, nx)) # 잡은 물고기가 있음? if catch: # 맨위, 맨좌 물고기뽑음 return cnt, min(catch) # 잡은 물고기가 없음. return None, (None, None) fishes = [] for y in range(N): for x in range(N): if arr[y][x] != 0: if arr[y][x] == 9: shark = (y, x) else: fishes.append((y, x)) sy, sx = shark shark_size = 2 fish_cnt = 0 res = 0 while True: # 물고기를 잡는데 든 시간, 잡은 물고기 위치 t, (ny, nx) = bfs(sy, sx, shark_size) if t is None: print(res) break # 물고기 잡음 res += t fish_cnt += 1 arr[sy][sx] = 0 arr[ny][nx] = 9 sy, sx = ny, nx if fish_cnt == shark_size: fish_cnt = 0 shark_size += 1 ================================================ FILE: BOJ/1629.곱셈/6047198844.cpp ================================================ #include #define LL long long using namespace std; LL divide_and_conquer(LL A, LL B, LL C) { if (B == 0) return 1; if (B % 2) { return ((A % C) * (divide_and_conquer(A, B - 1, C) % C)) % C; } else { int res = divide_and_conquer(A, B / 2, C); return (res % C * res % C) % C; } } int main() { LL A, B, C; cin >> A >> B >> C; cout << divide_and_conquer(A, B, C); } ================================================ FILE: BOJ/1633.최고의 팀 만들기/6047198844.py ================================================ # 완전 탐색. # 경우의 수 # 선택하는 경우 # 흑 팀을 선택하는 경우 # 백 팀을 선택하는 경우 # 선택하지 않은 경우 import sys # 입력 lines = sys.stdin.readlines() members = [tuple(map(int, line.split())) for line in lines] memo = [[[0 for _ in range(15 + 1)] for _ in range(15 + 1)] for _ in range(len(members))] # 독립적이다. def dfs(idx: int, white, black): # base case 1 : idx 이상이 존재하지 않는 경우 if idx == len(members): return 0 # base case 2 : white, black 선수단이 꽉찬 경우 if white == 0 and black == 0: return 0 # base case 3 : 탐색이 완료된 케이스의 경우 if memo[idx][white][black] != 0: return memo[idx][white][black] # 선택하는 경우 # 백 팀을 선택하는 경우 if white > 0: memo[idx][white][black] = max(memo[idx][white][black], dfs(idx + 1, white - 1, black) + members[idx][0]) # 흑 팀을 선택하는 경우 if black > 0: memo[idx][white][black] = max(memo[idx][white][black], dfs(idx + 1, white, black - 1) + members[idx][1]) # 선택하지 않은 경우 memo[idx][white][black] = max(memo[idx][white][black], dfs(idx + 1, white, black)) return memo[idx][white][black] # idx 번째 이상 선택이 가질수있는 높은 플레이 능력치의 합 # idx, 남은 흑팀 수, 남은 백팀수 print(dfs(0, 15, 15)) ================================================ FILE: BOJ/16394.홍익대학교/6047198844.py ================================================ N = int(input()) print(N - 2018 + 72) ================================================ FILE: BOJ/16395.파스칼의 삼각형/6047198844.py ================================================ # (n-1)! / (n-m)! * m! import sys N, K = map(int, sys.stdin.readline().split()) arr = [1] for i in range(1, 31): arr.append(arr[-1] * i) print(arr[N - 1] // arr[(N - 1) - (K - 1)] // arr[K - 1]) ================================================ FILE: BOJ/16430.제리와 톰/6047198844.py ================================================ A, B = map(int, input().split()) print(B-A, B) ================================================ FILE: BOJ/16435.스네이크버드/6047198844.py ================================================ import sys N, L = map(int, sys.stdin.readline().split()) nums = list(map(int, sys.stdin.readline().split())) nums.sort() for num in nums: if L >= num: L += 1 else: break print(L) ================================================ FILE: BOJ/16439.치킨치킨치킨/6047198844.py ================================================ from itertools import combinations N, M = map(int, input().split()) satifies = [list(map(int, input().split())) for _ in range(N)] res = 0 for chickens in combinations(range(M), 3): total = 0 for satify in satifies: unit = max(satify[chickens[0]], satify[chickens[1]], satify[chickens[2]]) total += unit res = max(res, total) print(res) ================================================ FILE: BOJ/1647.도시 분할 계획/6047198844.py ================================================ # 문제 # 마을은 N개의 집과 그 집들을 연결하는 M개의 길로 이루어져 있다. 길은 어느 방향으로든지 다닐 수 있는 편리한 길이다. 그리고 각 길마다 길을 유지하는데 드는 유지비가 있다. # 마을의 이장은 마을을 두 개의 분리된 마을로 분할할 계획을 가지고 있다. # 마을이 너무 커서 혼자서는 관리할 수 없기 때문이다. 마을을 분할할 때는 각 분리된 마을 안에 집들이 서로 연결되도록 분할해야 한다. # 각 분리된 마을 안에 있는 임의의 두 집 사이에 경로가 항상 존재해야 한다는 뜻이다. 마을에는 집이 하나 이상 있어야 한다. # # 그렇게 마을의 이장은 계획을 세우다가 마을 안에 길이 너무 많다는 생각을 하게 되었다. # 일단 분리된 두 마을 사이에 있는 길들은 필요가 없으므로 없앨 수 있다. 그리고 각 분리된 마을 안에서도 임의의 두 집 사이에 경로가 항상 존재하게 하면서 길을 더 없앨 수 있다. # 마을의 이장은 위 조건을 만족하도록 길들을 모두 없애고 나머지 길의 유지비의 합을 최소로 하고 싶다. 이것을 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 집의 개수 N, 길의 개수 M이 주어진다. N은 2이상 100,000이하인 정수이고, M은 1이상 1,000,000이하인 정수이다. 그 다음 줄부터 M줄에 걸쳐 길의 정보가 A B C 세 개의 정수로 주어지는데 A번 집과 B번 집을 연결하는 길의 유지비가 C (1 ≤ C ≤ 1,000)라는 뜻이다. # # 출력 # 첫째 줄에 없애고 남은 길 유지비의 합의 최솟값을 출력한다. import heapq import sys N, M = map(int, sys.stdin.readline().split()) Q = [] for _ in range(M): A, B, C = map(int, sys.stdin.readline().split()) heapq.heappush(Q, (C, A, B)) P = [-1 for _ in range(N + 1)] def union(A, B): PA = find(A) PB = find(B) if PA == PB: return P[PB] = PA def find(A): if P[A] == -1: return A P[A] = find(P[A]) return P[A] res = [] while Q: cost, A, B = heapq.heappop(Q) PA = find(A) PB = find(B) if PA == PB: continue res.append(cost) union(PA, PB) print(sum(res[:-1])) ================================================ FILE: BOJ/16507.어두운 건 무서워/6047198844.py ================================================ import sys R, C, Q = map(int, input().split()) board = [[0] * (C + 1)] + [[0] + list(map(int, input().split())) for _ in range(R)] memo = [[0 for i in range(C + 1)] for j in range(R + 1)] for y in range(1, R + 1): for x in range(1, C + 1): memo[y][x] = memo[y - 1][x] + memo[y][x - 1] - memo[y - 1][x - 1] + board[y][x] for input in sys.stdin: r1, c1, r2, c2 = map(int, input.split()) print((memo[r2][c2] + memo[r1 - 1][c1 - 1] - memo[r1 - 1][c2] - memo[r2][c1 - 1]) // ((r2 - r1 + 1) * (c2 - c1 + 1))) # 중복되어서 빼지는 사각형은 더한다. ================================================ FILE: BOJ/16508.전공책/6047198844.py ================================================ from itertools import combinations T = list(input()) N = int(input()) books = list() for _ in range(N): money, book = input().split() books.append((int(money), list(book))) res = 9999999999999 for i in range(1, N+1): for pick_books in combinations(books, i): target = T.copy() acc = 0 for pick_book in pick_books: money, book = pick_book is_cut = False for word in book: if word in target: is_cut = True target.remove(word) if is_cut: acc += money if not target: res = min(res, acc) if res == 9999999999999: res = -1 print(res) res = 0 # for book in books: # money, book = book # is_cut = False # for word in book: # if word in T: # is_cut = True # T.remove(word) # if is_cut: # res += money # # if T: # print(res) # else: # print(-1) ================================================ FILE: BOJ/1654.랜선 자르기/6047198844.cpp ================================================ #include #include #include using namespace std; int main() { int K, N; cin >> K >> N; vector arr(K); for (int i = 0; i < K; i++) cin >> arr[i]; sort(arr.begin(), arr.end()); long long begin = 1; long long end = arr[K - 1] + 1; while (begin+1 < end) { long long mid = (begin + end) / 2; int res = 0; for (int i = K-1; i >= 0; i--) { int _ = arr[i] / mid; if (_ == 0) break; else res += _; } if (res < N) { end = mid; } else { begin = mid; } } cout << begin; } // 2147483647 ================================================ FILE: BOJ/1654.랜선 자르기/rockmiin_1654.py ================================================ k, n= map(int, input().split()) arr=[int(input()) for i in range(k)] start= 1 end=max(arr) result= 0 while(start <= end): cnt=0 mid= (start+ end)// 2 for i in arr: cnt+= i // mid if cnt >= n: start= mid+1 else: end= mid- 1 print(end) ================================================ FILE: BOJ/1655.가운데를 말해요/6047198844.cpp ================================================ #include #include #define fastio cin.sync_with_stdio(false); cin.tie(nullptr) using namespace std; int main() { fastio; priority_queue, less> left; priority_queue, greater> right; /* 시간제한은 0.1초이다. N이 100,000 이기 때문에. 일반 배열을 사용할수없다. 일반 배열을 사용하면 탐색에 O(1) , 중앙에 삽입에 O(N)의 시간이 걸린다. 삽입을 N번하므로 . O(N^2) 시간이 걸린다. 1초를 넘긴다. 우선순위큐를 사용해서 푼다. 우선순위큐는 새 원소를 추가하는 연산 / 최대,최소원소를 꺼내는 연산을 O(lgN) 시간에 수행한다. 따라서 100,000 * 16 == 1,600,000 이므로 1천만이 안된다. 가능하다. 두개의 우선순위큐를 사용한다. 현재 가지고 있는 배열을 오름차순으로 정렬한뒤 반으로 나눈다. 두가지 규칙을 세운다. 1. 왼쪽 배열은 오른쪽 배열보다 개수가 1개 많거나 같다. -> 먼저 만족 2. 왼쪽 배열의 top값은 오른쪽 배열의 top값보다 작다. -> 이후 만족 */ int N; cin >> N; int num; while (N--) { cin >> num; //같은 경우 항상 left에 넣어야 1번 규칙이 만족된다. if (left.size() == right.size()) left.push(num); //왼쪽이 하나더 많은 경우 항상 right에 넣어야 1번 규칙이 만족된다. else right.push(num); //왼쪽이 비는 경우는 존재하지 않는다. 오른쪽이 비는 경우는 존재할수있다. 왼쪽에 하나 있고 오른쪽에 없는 경우이다. //여기서는 오른쪽이 비지 않았을때 두개의 값을 비교한다. if (!right.empty() && left.top() > right.top()) { int leftMax = left.top(); int rightMin = right.top(); left.pop(); left.push(rightMin); right.pop(); right.push(leftMax); } cout << left.top() << "\n"; } } ================================================ FILE: BOJ/16637.괄호 추가하기/6047198844.py ================================================ import math import sys def cal(operand1, operator, operand2): if operator == '+': return operand1 + operand2 elif operator == '-': return operand1 - operand2 return operand1 * operand2 def func(idx, s): global res if idx > N - 1: res = max(s, res) return operator = '+' if idx == 0 else exp[idx - 1] if idx != N - 1: brace = cal(int(exp[idx]), exp[idx + 1], int(exp[idx + 2])) func(idx + 4, cal(s, operator, brace)) func(idx + 2, cal(s, operator, int(exp[idx]))) N = int(sys.stdin.readline()) exp = list(sys.stdin.readline().rstrip()) res = -math.inf func(0, 0) print(res) ================================================ FILE: BOJ/1668.트로피 진열/6047198844.py ================================================ import sys N = int(sys.stdin.readline().rstrip()) left, right = 0, 0 left_res, right_res = 0, 0 trophies = [int(sys.stdin.readline().rstrip()) for _ in range(N)] for trophy in trophies: if left < trophy: left = trophy left_res += 1 for trophy in trophies[::-1]: if right < trophy: right = trophy right_res += 1 print(left_res) print(right_res) ================================================ FILE: BOJ/16724.피리 부는 사나이/6047198844.py ================================================ # 문제 # 성우가 정해놓은 방향은 총 4가지로 U, D, L, R이고 각각 위, 아래, 왼쪽, 오른쪽으로 이동하게 한다. # 성우가 설정한 방향 지도가 주어졌을 때 재훈이를 도와서 영과일 회원들이 지도 어느 구역에 있더라도 성우가 피리를 불 때 ‘SAFE ZONE’에 들어갈 수 있게 하는 ‘SAFE ZONE’의 최소 개수를 출력하는 프로그램을 작성하시오. # # 입력 # 첫 번째 줄에 지도의 행의 수를 나타내는 N(1 ≤ N ≤ 1,000)과 지도의 열의 수를 나타내는 M(1 ≤ M ≤ 1,000)이 주어진다. # # 두 번째 줄부터 N개의 줄에 지도의 정보를 나타내는 길이가 M인 문자열이 주어진다. # # 지도 밖으로 나가는 방향의 입력은 주어지지 않는다. # # 출력 # 첫 번째 줄에 ‘SAFE ZONE’의 최소 개수를 출력한다. import sys sys.setrecursionlimit(10**6) N, M = map(int, sys.stdin.readline().split()) board = [list(sys.stdin.readline().rstrip()) for _ in range(N)] P = [i for i in range(N * M)] def union(A, B): PA = find(A) PB = find(B) if PA == PB: return P[PB] = PA def find(A): if A == P[A]: return A P[A] = find(P[A]) return P[A] for y in range(N): for x in range(M): i = (M * y) + x if board[y][x] == 'U': j = (M * (y - 1)) + x elif board[y][x] == 'D': j = (M * (y + 1)) + x elif board[y][x] == 'L': j = (M * y) + (x - 1) elif board[y][x] == 'R': j = (M * y) + (x + 1) union(i, j) visited = set() for y in range(N): for x in range(M): i = (M * y) + x Pi = find(i) if Pi not in visited: visited.add(Pi) print(len(visited)) ================================================ FILE: BOJ/16918.봄버맨/6047198844.py ================================================ R, C, N = map(int, input().split()) board = [list(input()) for _ in range(R)] # 예외처리 # 짝수 일 경우. 전채 폭탄을 프린트한다. if N % 2 == 0: for r in range(R): print('O' * C) else: # 초기 세팅 'O'를 0으로 교체. # 0초째 -> 설치 for r in range(R): for c in range(C): if board[r][c] == 'O': board[r][c] = 0 # 1초째 -> 아무것도 안함 pass # 처음 1초 제외 (2초부터 N초 까지) for sec in range(2, N+1): pass # 2초째 -> 폭탄이 설치되어 있지 않은 모든 칸에 폭탄 설치 # 4초째 -> 폭탄이 설치되어 있지 않은 모든 칸에 폭탄 설치 if sec % 2 == 0: for r in range(R): for c in range(C): if board[r][c] == '.': board[r][c] = sec # 3초째 -> 폭탄 폭발 / 0초째의 폭탄이 폭발된다. # 5초째 -> 폭탄 폭발 / 2초째의 폭탄이 폭발된다. else: for r in range(R): for c in range(C): # 3초 지난 폭탄을 터트린다. if board[r][c] == sec - 3: # 자신을 터트린다. board[r][c] = '.' # 주변을 터트린다. for dr, dc in (-1, 0), (+1, 0), (0, -1), (0, +1): nr, nc = r + dr, c + dc if 0 <= nr < R and 0 <= nc < C and board[nr][nc] != sec - 3: board[nr][nc] = '.' #output 출력 for r in range(R): for c in range(C): if type(board[r][c]) == int: print('O', end='') else: print('.', end='') print() ================================================ FILE: BOJ/16922.로마 숫자 만들기/6047198844.py ================================================ from itertools import combinations_with_replacement N = int(input()) res = set() arr = [1, 5, 10, 50] for i in combinations_with_replacement(arr, N): res.add(sum(i)) print(len(res)) ================================================ FILE: BOJ/16928.뱀과 사다리 게임/6047198844.py ================================================ import collections N, M = map(int, input().split()) #모든 칸은 최대 하나의 사다리 또는 뱀을 가지고 있으며, 동시에 두 가지를 모두 가지고 있는 경우는 없다. skip = dict() for _ in range(N+M): key, value = map(int, input().split()) skip[key] = value Q = collections.deque() Q.append(1) path = set() path.add(1) dice_cnt = 0 while Q: dice_cnt += 1 for _ in range(len(Q)): position = Q.popleft() for dice in range(1,6+1): new_position = position + dice #만약 주사위를 굴려서 이동한 결과가 100번 칸을 넘어간다면 이동할 수 없다. if new_position > 100: continue # 1번 칸과 100번 칸은 뱀과 사다리의 시작 또는 끝이 아니다. # 정답에 도달한 경우 주사위를 굴린 횟수를 반환하고 종료한다. if new_position == 100: print(dice_cnt) exit() #사다리나 뱀에 존재할경우. 해당 좌표로 이동한다. if new_position in skip: new_position = skip[new_position] #해당 경로가 발견되지 않았다면 if new_position not in path: path.add(new_position) Q.append(new_position) #발견되었다면 Q에 넣지 않는다. #항상 100번 칸에 도착할 수 있는 입력만 주어진다. -> Q가 empty인 경우는 없다. #skip = {key: value for key, value in map(int, input().split()) for _ in range(N+M)} #뱀 / 사다리 정보 저장. #https://bio-info.tistory.com/40 ================================================ FILE: BOJ/16929.Two Dots/6047198844.cpp ================================================ #include #include using namespace std; int board_y; int board_x; bool check[50][50]; char board[50][50]; int dy[4] = {0,0,-1,+1}; int dx[4] = {-1,+1,0,0}; bool dfs(int y, int x, int start_y, int start_x,int cnt) { if (check[y][x]) { if ((y == start_y) && (x == start_x) && cnt >= 4) { return true; } return false; } check[y][x] = true; for (int i = 0; i < 4; i++) { if ((y < 0 || y >= board_y) || (x < 0 || x >= board_x)) continue; if (board[y][x] == board[y + dy[i]][x + dx[i]]) if (dfs(y + dy[i], x + dx[i], start_y, start_x, cnt + 1)) return true; } return false; } int main() { cin >> board_y >> board_x; for (int y = 0; y < board_y; y++) for (int x = 0; x < board_x; x++) cin >> board[y][x]; for (int y = 0; y < board_y; y++) for (int x = 0; x < board_x; x++) { if (dfs(y, x, y, x, 0)) { cout << "Yes"; return 0; } memset(check, false, sizeof(check)); } cout << "No"; } ================================================ FILE: BOJ/16937.두 스티커/6047198844.py ================================================ import sys from itertools import combinations H, W = map(int, sys.stdin.readline().split()) N = int(sys.stdin.readline()) stickers = [tuple(map(int, sys.stdin.readline().split())) for _ in range(N)] res = 0 for sticker in combinations(stickers, 2): A, B = sticker RA, CA = A RB, CB = B # A , B if (RA + RB <= H and CA <= W and CB <= W) or (CA + CB <= W and RA <= H and RB <= H): res = max(res, RA * CA + RB * CB) # A(90), B elif (CA + RB <= H and RA <= W and CB <= W) or (RA + CB <= W and CA <= H and RB <= H): res = max(res, RA * CA + RB * CB) # A, B(90) elif (RA + CB <= H and CA <= W and RB <= W) or (CA + RB <= W and RA <= H and CB <= H): res = max(res, RA * CA + RB * CB) # A(90), B(90) elif (CA + CB <= H and RA <= W and RB <= W) or (RA + RB <= W and CA <= H and CB <= H): res = max(res, RA * CA + RB * CB) print(res) ================================================ FILE: BOJ/16938.캠프 준비/6047198844.py ================================================ ''' 입력 N, L, R, X A1, A2, ... , An N : 개수 L <= 난이도의합 <= R X : 난이도 차이 (가장 어려운 문제 - 가장 쉬운 문제) ''' from itertools import combinations N, L, R, X = map(int, input().split()) A = sorted(list(map(int, input().split()))) result = 0 for i in range(1, N + 1): for c in combinations(A, i): if L <= sum(c) <= R and c[-1] - c[0] >= X: result += 1 print(result) ================================================ FILE: BOJ/16946.벽 부수고 이동하기 4/6047198844.py ================================================ import collections import copy N, M = map(int, input().split()) board = [list(map(int, input())) for _ in range(N)] #이 보드에 zero끼리 섬을 나누고 섬에 해당하는 0의 개수와 섬의 번호를 저장한다. zero_board = [[(0, -1) for _ in range(M)] for _ in range(N)] #zero_board를 만든다. #zero_board란 zero끼리 이루는 섬의 zero개수이다. def zero_bfs(i, j, group): #자기 자신을 포함한다. zero_cnt = 1 Q = collections.deque() Q.append((i,j)) visited = set() visited.add((i,j)) while Q: y, x = Q.popleft() for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny = y + dy nx = x + dx if 0 <= ny < N and 0 <= nx < M: if board[ny][nx] == 0 and (ny, nx) not in visited: zero_cnt += 1 Q.append((ny, nx)) visited.add((ny, nx)) for y, x in visited: zero_board[y][x] = (zero_cnt, group) group = 0 for y in range(len(board)): for x in range(len(board[0])): if board[y][x] == 0 and zero_board[y][x][0] == 0: zero_bfs(y, x, group) group += 1 #group 주의. for y in range(len(board)): for x in range(len(board[0])): if board[y][x] == 1: visited = set() for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny = y + dy nx = x + dx if 0 <= ny < N and 0 <= nx < M and board[ny][nx] == 0 and zero_board[ny][nx][1] not in visited: board[y][x] += zero_board[ny][nx][0] visited.add(zero_board[ny][nx][1]) board[y][x] %= 10 for row in board: print(*row, sep='') ================================================ FILE: BOJ/16948.데스 나이트/6047198844.py ================================================ import collections N = int(input()) r1, c1, r2, c2 = map(int, input().split()) Q = collections.deque() discovered = set() Q.append((r1,c1)) discovered.add((r1,c1)) move_cnt = 0 while Q: move_cnt += 1 for _ in range(len(Q)): r, c = Q.popleft() for dr, dc in (-2, -1), (-2, +1), (0, -2), (0, +2), (+2, -1), (+2, +1): nr = r + dr nc = c + dc #범위를 벗어난 경우 if not (0 <= nr 0: # 충격을 가한다. eggs_durability[picked_idx] -= eggs[target_idx][1] eggs_durability[target_idx] -= eggs[picked_idx][1] brute_force(picked_idx + 1, broken_eggs_n + int(eggs_durability[picked_idx] <= 0) + int(eggs_durability[target_idx] <= 0)) eggs_durability[picked_idx] += eggs[target_idx][1] eggs_durability[target_idx] += eggs[picked_idx][1] brute_force(0, 0) print(ans) ================================================ FILE: BOJ/1699.제곱수의 합/6047198844.py ================================================ N = int(input()) # base case # 최대 개수로 초기화 == 1^2으로 만드는수 == 수자체. # ex) 12로 만드는 제곱의 합 최대수는 1^2으로 만드는 12개의 제곱의 합이다. memo = [i for i in range(N + 1)] for i in range(1, N + 1): arr = list() for j in range(1, int(i ** 0.5) + 1): arr.append(memo[i-j*j] + 1) memo[i] = min(arr) print(memo[N]) ================================================ FILE: BOJ/1699.제곱수의 합/제곱수의_합_1699.py ================================================ n=int(input()) dp=[0]*(n+1) s=[] dp[1]=1 for i in range(1, 400): if i**2 >= 100000: break s.append(i) for i in range(1, n+1): q=[] for j in s: if i>=j**2: q.append(dp[i-j**2]) else: break; dp[i]=min(q)+1 print(dp[n]) ================================================ FILE: BOJ/1707.이분그래프/.vscode/launch.json ================================================ { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Launch Chrome against localhost", "file":"${workspaceFolder}/index.html" } ] } ================================================ FILE: BOJ/1707.이분그래프/6047198844.cpp ================================================ 1 /* 2 이분그래프 3 - 그래프의 정점을 둘로 분할하여, 각 집합에 속한 정점끼리는 서로 인접하지 않도록 분할 할수있는 그래프 4 - 그리프가 입력으로 주어졌을때, 이분 그래프인지 아닌지 판별하라. 5 ​ 6 풀이 7 - 인접한 그래프들 원소 각각에 색깔을 칠한다 -> 칠한 색깔이 맞는지 검증한다. 8 ​ 9 - n개의 조각으로 쪼갠다. 10 - 모든 그래프에 색을 칠한다. 11 - 그래프 탐색을 한다. 근처 원소에 색을 칠해야 하므로 BFS로 색을 칠한다. 12 ​ 13 - Base case 14 - 모든 원소가 색이 칠해졌을때 15 ​ 16 검증하는 함수 작성 17 - 빨강은 1 / 검정은 2로 표시한다. 18 */ 19 ​ 20 #include 21 #include 22 #include 23 #include 24 ​ 25 #define RED 1 26 #define BLACK 2 27 ​ 28 using namespace std; 29 ​ 30 pair Vertex[20001]; 31 vector Edge[20001]; 32 //배열이 아닌 vector로 받는다. 33 ​ 34 bool coloring(int start, int color, int Vernum) 35 { 36 queue q; 37 ​ 38 //처음에는 RED로 칠함. 39 q.push(start); 40 Vertex[start].first = true; Vertex[start].second = color; 41 ​ 42 while (!q.empty()) 43 { 44 int SelectVertex = q.front(); q.pop(); 45 for (int i = 0; i < Edge[SelectVertex].size(); i++) 46 { 47 int NeighborVertex = Edge[SelectVertex][i]; 48 if (!Vertex[NeighborVertex].first) 49 { 50 Vertex[NeighborVertex].first = true; 51 if (Vertex[SelectVertex].second == BLACK) 52 Vertex[NeighborVertex].second = RED; 53 else 54 Vertex[NeighborVertex].second = BLACK; 55 q.push(NeighborVertex); 56 } 57 else 58 { 59 if (Vertex[SelectVertex].second == Vertex[NeighborVertex].second) 60 return false; 61 } 62 } 63 } 64 return true; 65 } 66 ​ 67 int main() 68 { 69 int K; int V; int E; 70 cin >> K; 71 while (K--) 72 { 73 cin >> V >> E; 74 for (int i = 0; i < 20001; i++) 75 Edge[i].clear(); 76 for (int i = 0; i < 20001; i++) 77 Vertex[i].first = Vertex[i].second = 0; 78 ​ 79 int A; int B; 80 for (int i = 0; i < E; i++) 81 { 82 scanf("%d %d", &A, &B); 83 Edge[A].push_back(B); 84 Edge[B].push_back(A); 85 } 86 int res = 0; 87 for (int i = 1; i <= V; i++) 88 { 89 if(!Vertex[i].first) 90 if (!coloring(i, RED, V)) 91 { 92 res = 1; 93 break; 94 } 95 } 96 ​ 97 if (res) 98 cout << "NO" << endl; 99 else 100 cout << "YES" << endl; 101 } 102 } ================================================ FILE: BOJ/17070.파이프 옮기기1/6047198844.cpp ================================================ #include #include using namespace std; int memo[17][17][3]; int arr[17][17]; int N; int dp(int y,int x,int type) { if (x > N || y > N) return 0; if (x == N && y == N) return 1; int& res = memo[y][x][type]; if (res != -1) return res; res = 0; //type1 가로 if (type != 1) { if (!arr[y][x + 1]) res += dp(y, x + 1, 0); } //type2 세로 if (type != 0) { if (!arr[y + 1][x]) res += dp(y + 1, x, 1); } if (!arr[y][x + 1] && !arr[y + 1][x + 1] && !arr[y + 1][x]) { res += dp(y + 1, x + 1, 2); } return res; } int main() { cin >> N; for (int y = 1; y <= N; y++) for (int x = 1; x <= N; x++) cin >> arr[y][x]; memset(memo, -1, sizeof(memo)); cout << dp(1, 2, 0); } ================================================ FILE: BOJ/17128.소가 정보섬에 올라온 이유/6047198844.py ================================================ # 소들은 정보섬 1층 앞마당에서 A1, A2, A3, ..., AN, A1의 순서대로 동그랗게 앉아 쉬고 있다. # 각 소들에게는 품질 점수 Ai가 적힌 스티커가 붙어 있다. # 풀어 쓰자면, 원형으로 둘러 앉은 소들에 대해서, 연속한 네 마리 소들의 품질 점수를 곱한 값을 모두 (정확히 한 번씩) 더한 것이다. # 욱제는 총 Q번에 걸쳐 어떤 i번째 소를 선택할 것이다. 그러고는 Ai가 적힌 스티커를 떼어내고, Ai*(-1)이 적힌 스티커를 붙일 작정이다. # i 번째 소는 몇번째 그룹에 속할까? # A1 그룹 / A2 그룹 / A3 그룹 / ... / A8 그룹 # i를 3이라고 하면, A3 그룹 / A2 그룹 / A1 그룹 / A8 그룹에 속할것이다. 스티커가 바꿔치기 당했을때 해당 그룹 계산만 다시해주면 된다. # Ai / Ai-1 / Ai-2 / Ai-3 # 입력 # 첫째 줄에 소의 수를 나타내는 N과 욱제가 장난칠 횟수 Q가 주어진다. (4 ≤ N ≤ 200,000, 1 ≤ Q ≤ 200,000) # # 둘째 줄에 N마리 소들의 품질 점수 Ai가 순서대로 주어진다. (1 ≤ |Ai| ≤ 10) # # 셋째 줄에 욱제가 장난칠 Q개의 소의 번호가 순서대로 주어진다. (1 ≤ Qi ≤ N) # # 출력 # Q개의 줄에 걸쳐 다시 계산된 S의 값을 출력한다. N, Q = map(int, input().split()) cow_scores = list(map(int, input().split())) fake_idxes = list(map(int, input().split())) cow_groups = [cow_scores[i % N] * cow_scores[(i + 1) % N] * cow_scores[(i + 2) % N] * cow_scores[(i + 3) % N] for i in range(N)] res = sum(cow_groups) for idx in fake_idxes: idx = idx - 1 desc = 0 for i in range(idx, idx - 4, -1): cow_groups[i % N] = - cow_groups[i % N] desc += cow_groups[i % N] res += 2 * desc print(res) ================================================ FILE: BOJ/17135.캐슬 디펜스/6047198844.py ================================================ # N x M 격자판 # 각 칸에 적 하나. # N+1 행의 모든 칸에는 성이 있다. # 궁수 # 성이 있는칸에 3명 배치. 하나의 칸에는 최대 1명의 궁수. # 궁수는 적하나를 공격한다. # 모든 궁수는 동시에 공격한다. # 거리가 D 이하인 적중에서 가장 가까운적을 공격한다. 그러한 적이 여러명이면 가장 왼쪽에 있는 적을 공격한다. 같은 적이 여러 궁수에게 공격당할수있다. # 적 # 공격 받으면 게임에서 제외된다. # 공격이 끝나면 아래로 한칸 이동한다. 성이 있는 칸으로 이동한 경우 게임에서 제외된다. import sys from itertools import combinations def kill_enemy(arrow_x_positions, arrow_y_position, range, enemy_set): res = 0 while enemy_set: i, j, k = arrow_x_positions arrows = [Arrow(i, arrow_y_position, range), Arrow(j, arrow_y_position, range), Arrow(k, arrow_y_position, range)] for arrow in arrows: arrow.set_enemy(enemy_set) remove_enemy_list = list() for arrow in arrows: kill = arrow.kill() if kill is not None: remove_enemy_list.append(kill) for distance, remove_enemy in remove_enemy_list: if remove_enemy is not None and remove_enemy in enemy_set: enemy_set.remove(remove_enemy) res += 1 tmp_set = set() for x, y in enemy_set: if y + 1 < arrow_y_position: tmp_set.add((x, y+1)) enemy_set = tmp_set return res class Arrow: def __init__(self, x, y, range): self.x = x self.y = y self.range = range self.enemy_list = list() def calculate(self, enemy_position): ex, ey = enemy_position return abs(ex - self.x) + abs(ey - self.y) def set_enemy(self, enemys): self.reset() for enemy in enemys: distance = self.calculate(enemy) if distance <= self.range: self.enemy_list.append((distance, enemy)) def kill(self): if len(self.enemy_list) == 0: return None self.enemy_list.sort() return self.enemy_list[0] def reset(self): self.enemy_list = list() N, M, D = map(int, sys.stdin.readline().split()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] enemy = set() for y in range(N): for x in range(M): if board[y][x] == 1: enemy.add((x, y)) res = 0 for arrow_x_positions in combinations(range(M), 3): res = max(res, kill_enemy(arrow_x_positions, N, D, enemy.copy())) print(res) ================================================ FILE: BOJ/17136.색종이 붙이기/6047198844.py ================================================ # 문제 # 정사각형 모양을 한 다섯 종류의 색종이가 있다. 색종이의 크기는 1×1, 2×2, 3×3, 4×4, 5×5로 총 다섯 종류가 있으며, 각 종류의 색종이는 5개씩 가지고 있다. # # 색종이를 크기가 10×10인 종이 위에 붙이려고 한다. # 종이는 1×1 크기의 칸으로 나누어져 있으며, 각각의 칸에는 0 또는 1이 적혀 있다. 1이 적힌 칸은 모두 색종이로 덮여져야 한다. # 색종이를 붙일 때는 종이의 경계 밖으로 나가서는 안되고, 겹쳐도 안 된다. 또, 칸의 경계와 일치하게 붙여야 한다. 0이 적힌 칸에는 색종이가 있으면 안 된다. # # 종이가 주어졌을 때, 1이 적힌 모든 칸을 붙이는데 필요한 색종이의 최소 개수를 구해보자. # # 입력 # 총 10개의 줄에 종이의 각 칸에 적힌 수가 주어진다. # # 출력 # 모든 1을 덮는데 필요한 색종이의 최소 개수를 출력한다. 1을 모두 덮는 것이 불가능한 경우에는 -1을 출력한다. import sys # y, x 에 색종이를 붙였을때 색종이의 최소갯수로 교체한다. def switch(y, x, K): for i in range(y, y + K + 1): for j in range(x, x + K + 1): board[i][j] = int(board[i][j] == 0) def dfs(y, x, count): global ans # base case 1. y를 초과한경우. if y >= 10: ans = min(ans, count) return # base case 2. x를 초과한경우 if x >= 10: dfs(y + 1, 0, count) return # bse case 3. board[y][x] 가 0 인 경우 if board[y][x] == 0: dfs(y, x + 1, count) # 색종이를 붙여본다. 색종이는 각 종류마다 5개가 존재한다. # 색종이의 번호를 K라고 하자. for K in range(5): # 종이가 존재하는 지 확인한다. if paper[K] == 5: continue # 현재 위치에 색종이를 붙일 수 있다 if y + K < 10 and x + K < 10: # 붙이는 지역이 모두 붙일수있는 지역인지 확인한다. flag = True for i in range(y, y + K + 1): for j in range(x, x + K + 1): if board[i][j] == 0: flag = False break if not flag: break # 뿥일수있다면 if flag: # 붙인다. paper[K] += 1 switch(y, x, K) # 다음 재귀를 호출한다. dfs(y, x + K + 1, count + 1) # 땐다. paper[K] -= 1 switch(y, x, K) board = [list(map(int, input().split())) for _ in range(10)] paper = [0 for _ in range(5)] ans = sys.maxsize dfs(0, 0, 0) print(-1) if ans == sys.maxsize else print(ans) ================================================ FILE: BOJ/17141.연구소 2/6047198844.py ================================================ """ 첫째 줄에 연구소의 크기 N(5 ≤ N ≤ 50), 놓을 수 있는 바이러스의 개수 M(1 ≤ M ≤ 10)이 주어진다. 둘째 줄부터 N개의 줄에 연구소의 상태가 주어진다. 0은 빈 칸, 1은 벽, 2는 바이러스를 놓을 수 있는 칸이다. 2의 개수는 M보다 크거나 같고, 10보다 작거나 같은 자연수이다. 연구소의 상태가 주어졌을 때, 모든 빈 칸에 바이러스를 퍼뜨리는 최소 시간을 구해보자. """ from collections import deque from itertools import combinations def flood_fill(board, visited, V): Q = deque(visited) time = -1 while Q: for _ in range(len(Q)): y, x = Q.popleft() for dy, dx in (1, 0), (-1, 0), (0, 1), (0, -1): ny, nx = y + dy, x + dx if 0 <= ny < N and 0 <= nx < N and (board[ny][nx] == 0 or board[ny][nx] == 2) \ and (ny, nx) not in visited: visited.add((ny, nx)) Q.append((ny, nx)) time += 1 return time if len(visited) == V else -1 N, M = map(int, input().split()) board = [list(map(int, input().split())) for i in range(N)] min_time = -1 # visited 위치를 찾자 # V는 virus 를 넣어야하는 개수이다. virus = list() V = 0 for y in range(N): for x in range(N): if board[y][x] != 1: if board[y][x] == 2: virus.append((y, x)) V += 1 # start == ((0,0), (3,6), (6,0)) # virus 에서 M개를 뽑는다. for start in combinations(virus, M): visited = set(start) time = flood_fill(board, visited, V) if time != -1 and (min_time == -1 or min_time > time): min_time = time print(min_time) ================================================ FILE: BOJ/17143.낚시왕/6047198844.py ================================================ import sys from copy import deepcopy def move(): global board new_board = [[[] for _ in range(C)] for _ in range(R)] for y in range(R): for x in range(C): while board[y][x]: shark_idx = board[y][x].pop() ny, nx, nspeed, ndirection, nsize = sharks[shark_idx] # 위 , 아래 , 오른쪽 , 왼쪽 # 거리축소 if ndirection == 1 or ndirection == 2: ndistance = nspeed % (2 * (R - 1)) else: ndistance = nspeed % (2 * (C - 1)) # 거리만큼 움직인다. cnt = 0 while cnt < ndistance: # 위 if ndirection == 1: # 방 if ny == 0: ndirection = 2 continue ny -= 1 # 아래 elif ndirection == 2: # 방 if ny == R - 1: ndirection = 1 continue ny += 1 # 오른쪽 elif ndirection == 3: # 방 if nx == C - 1: ndirection = 4 continue nx += 1 # 왼쪽 elif ndirection == 4: # 방 if nx == 0: ndirection = 3 continue nx -= 1 # 움직인다. cnt += 1 sharks[shark_idx] = (ny, nx, nspeed, ndirection, nsize) new_board[ny][nx].append(shark_idx) # 모두 이동한 후에 board 에 반영한다. board = deepcopy(new_board) def remove_shark(): for y in range(R): for x in range(C): if len(board[y][x]) > 1: max_shark_idx = max(board[y][x], key=lambda idx: sharks[idx][4]) board[y][x] = [max_shark_idx] R, C, M = map(int, sys.stdin.readline().split()) sharks = [] board = [[[] for _ in range(C)] for _ in range(R)] for i in range(M): y, x, speed, direction, size = map(int, sys.stdin.readline().split()) sharks.append((y - 1, x - 1, speed, direction, size)) board[y - 1][x - 1].append(i) fisher = -1 res = 0 while True: # 낚시왕이 이동한다 fisher += 1 if fisher == C: print(res) exit() # 낚시왕 인덱스를 x 로 가지는 상어중에 가장 y 가 작은 상어 삭제. for ny in range(R): # shark 가 아닌경우. if len(board[ny][fisher]) == 0: continue # shark 인 경우 # 잡는다. shark_idx = board[ny][fisher].pop(0) res += sharks[shark_idx][4] break # 상어를 이동한다. move() # 겹치는 상어 제거한다. remove_shark() ================================================ FILE: BOJ/1718.암호/6047198844.py ================================================ # 문제 # 암호화하려는 문장 (평문)의 단어와 암호화 키를 숫자로 바꾼 다음, 평문의 단어에 암호화 키에 해당하는 숫자를 빼서 암호화하는 방식을 생각해 보자. # 제시된 평문의 첫 번째 문자인 ‘n’은 해당 암호화 키 ‘l’의 알파벳 순서가 12 이므로 알파벳상의 순서에서 ‘n’보다 12앞의 문자인 ‘b’로 변형된다. # 평문의 문자가 공백 문자인 경우는 그 공백 문자를 그대로 출력한다. # # 이와 같은 암호화를 행하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 평문이, 둘째 줄에 암호화 키가 주어진다. # # 평문은 알파벳 소문자와 공백문자(space)로만 구성되며, 암호화 키는 알파벳 소문자만으로 구성된다. 평문의 길이는 공백까지 포함해서 30000자 이하이다. # # 출력 # 첫 번째 줄에 암호문을 출력한다. plaintext = input() ciphertext = input() for idx, plain in enumerate(plaintext): if plain.isalpha(): order = ord(ciphertext[idx % len(ciphertext)]) - ord('a') + 1# 순서 print(chr(ord('a') + (ord(plain) - ord('a') - order) % 26), end='') else: print(' ', end='') ================================================ FILE: BOJ/17219.비밀번호 찾기/6047198844.py ================================================ import sys from collections import defaultdict N, M = map(int, sys.stdin.readline().split()) table = defaultdict(str) for _ in range(N): key, value = sys.stdin.readline().split() table[key] = value for _ in range(M): key = sys.stdin.readline().rstrip() print(table[key]) ================================================ FILE: BOJ/1725.히스토그램/1725_히스토그램.cpp ================================================ #include #include #include using namespace std; //index start index end 簢 ̰ ū 簢 Ѵ. int divide_and_conquer(int start, int end,vector &fence) { if (start == end) return fence[start]; //3 divideѴ. //簢 ߾ ġ ʰ ʿ ִ //簢 ߾ ġ //簢 ߾ ġ ʰ ʿ ִ int mid = (start + end) / 2; int left_side = divide_and_conquer(start, mid, fence); int right_side = divide_and_conquer(mid + 1, end, fence); int res = max(left_side, right_side); int left_index = mid; int right_index = mid + 1; int height = min(fence[left_index], fence[right_index]); res = max(res, height * 2); while (left_index > start || right_index < end) { //left_index ҽŰ , 츦 Ǵ°. if ((right_index == end)||left_index > start && fence[left_index-1] > fence[right_index+1]) { --left_index; height = min(height, fence[left_index]); } //right_index Ű else { ++right_index; height = min(height, fence[right_index]); } res = max(res, height * (right_index - left_index + 1)); } return res; } int main() { int N; cin >> N; vector fence; int num; for (int i = 0; i < N; i++) { cin >> num; fence.push_back(num); } cout << divide_and_conquer(0, N - 1, fence); } ================================================ FILE: BOJ/1725.히스토그램/sAp00n.py ================================================ from sys import stdin def sub_list(input_list): if len(input_list) == 1: return input_list[0] mid_idx = len(input_list) // 2 sub_max = max(sub_list(input_list[:mid_idx]), sub_list(input_list[mid_idx:])) start, end = mid_idx - 1, mid_idx min_val = min(input_list[start], input_list[end]) mid_max = min_val * 2 # print(f'in : {input_list}') while 0 < start or end < len(input_list) - 1: # print(f'start:{start} end: {end} mid_max:{mid_max}') if start > 0: if end == len(input_list) - 1 or input_list[start - 1] >= input_list[end + 1]: start -= 1 min_val = min(min_val, input_list[start]) mid_max = max(mid_max, min_val * (end - (start - 1))) continue end += 1 min_val = min(min_val, input_list[end]) mid_max = max(mid_max, min_val * (end - (start - 1))) # print(f'sub_max:{sub_max} mid_max:{mid_idx}') return max(sub_max, mid_max) N = int(stdin.readline()) input_list = [] for _ in range(N): input_list.append(int(stdin.readline())) print(sub_list(input_list)) ================================================ FILE: BOJ/17255.N으로 만들기/6047198844.py ================================================ N = input() ans = 0 Q = [N] while Q: num = Q.pop() if len(num) == 1: ans += 1 else: i = num[1:] j = num[:-1] Q.append(i) if i != j: Q.append(j) print(ans) ================================================ FILE: BOJ/1726.로봇/6047198844.py ================================================ # 문제 # 우리 월드 공장의 로봇은 바라보는 방향으로 궤도를 따라 움직이며, 움직이는 방향은 동, 서, 남, 북 가운데 하나이다. # 로봇의 이동을 제어하는 명령어는 다음과 같이 두 가지이다. # # 명령 1. Go k: k는 1, 2 또는 3일 수 있다. 현재 향하고 있는 방향으로 k칸 만큼 움직인다. # 명령 2. Turn dir: dir은 left 또는 right 이며, 각각 왼쪽 또는 오른쪽으로 90° 회전한다. # # 공장 내 궤도가 설치되어 있는 상태가 아래와 같이 0과 1로 이루어진 직사각형 모양으로 로봇에게 입력된다. # 0은 궤도가 깔려 있어 로봇이 갈 수 있는 지점 # 1은 궤도가 없어 로봇이 갈 수 없는 지점 # # 로봇이 (4, 2) 지점에서 남쪽을 향하고 있을 때, 이 로봇을 (2, 4) 지점에서 동쪽으로 향하도록 이동시키는 것은 아래와 같이 9번의 명령으로 가능하다. # 로봇의 현재 위치와 바라보는 방향이 주어졌을 때, 로봇을 원하는 위치로 이동시키고, 원하는 방향으로 바라보도록 하는데 최소 몇 번의 명령이 필요한지 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 공장 내 궤도 설치 상태를 나타내는 직사각형의 세로 길이 M과 가로 길이 N이 빈칸을 사이에 두고 주어진다. # 이때 M과 N은 둘 다 100이하의 자연수이다. # 이어 M줄에 걸쳐 한 줄에 N개씩 각 지점의 궤도 설치 상태를 나타내는 숫자 0 또는 1이 빈칸을 사이에 두고 주어진다. # 다음 줄에는 로봇의 출발 지점의 위치 (행과 열의 번호)와 바라보는 방향이 빈칸을 사이에 두고 주어진다. # 마지막 줄에는 로봇의 도착 지점의 위치 (행과 열의 번호)와 바라보는 방향이 빈칸을 사이에 두고 주어진다. # 방향은 동쪽이 1, 서쪽이 2, 남쪽이 3, 북쪽이 4로 주어진다. 출발지점에서 도착지점까지는 항상 이동이 가능하다. # # 출력 # 첫째 줄에 로봇을 도착 지점에 원하는 방향으로 이동시키는데 필요한 최소 명령 횟수를 출력한다. import sys from collections import deque M, N = map(int, sys.stdin.readline().split()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(M)] start = tuple(map(lambda i: i - 1, map(int, sys.stdin.readline().split()))) end = tuple(map(lambda i: i - 1, map(int, sys.stdin.readline().split()))) # 동서남북 위치를 저장할 공간 visited = set() Q = deque([start]) visited.add(start) res = 0 if start == end: print(res) exit() while Q: # 명령 res += 1 for _ in range(len(Q)): # 동 : 0 / 서 : 1 / 남 : 2 / 북 : 3 y, x, direction = Q.popleft() # 0 -> 2,3 / 1 -> 2,3 / 2 -> 0,1 / 3 -> 0,1 # 방향 전환 commands = [(y, x, 2), (y, x, 3)] if direction == 0 or direction == 1 else [(y, x, 0), (y, x, 1)] # 이동 if direction == 0: dy, dx = 0, 1 elif direction == 1: dy, dx = 0, -1 elif direction == 2: dy, dx = +1, 0 else: dy, dx = -1, 0 for ny, nx in (y + dy, x + dx), (y + (2 * dy), x + (2 * dx)), (y + (3 * dy), x + (3 * dx)): # 예외 처리: 이동할수있는 경우만 추가한다. if 0 <= ny < M and 0 <= nx < N and board[ny][nx] == 0: commands.append((ny, nx, direction)) # 가다가 이동못하면 터트려야한다. else: break for my, mx, md in commands: # 기저 사례 : 끝난 경우 if (my, mx, md) == end: print(res) exit() elif (my, mx, md) not in visited: visited.add((my, mx, md)) Q.append((my, mx, md)) ================================================ FILE: BOJ/17265.나의 인생에는 수학과 함께/6047198844.py ================================================ """ 세현이네 집에서 학교까지 가는 길은 N x N 크기의 바둑판과 같다. 그리고 각 블록은 1x1 정사각형으로 구분 지을 수 있다. 세현이는 그 블록마다 숫자와 연산자가 존재한다고 생각해서 임의의 숫자와 연산자를 각 블록에 넣어 바둑판을 만들었다. 세현이는 학교에서 집으로 가는 경로에서 만나는 숫자와 연산자의 연산 결과의 최댓값과 최솟값을 구하려고 한다. 세현이는 항상 자신의 집 (1, 1)에서 학교 (N, N)까지 최단거리로 이동한다. 최단거리로 이동하기 위해서는 오른쪽과 아래쪽으로만 이동해야 한다. 세현이는 이 길을 걸으면서 최댓값과 최솟값을 암산하다가 교통사고를 당해 현재 인하대학교 병원에 입원했다. 아픈 세현이를 위해 최댓값과 최솟값을 구해주자. """ N = int(input()) min_board = [] max_board = [] for _ in range(N): s = input() min_board.append(s.split()) max_board.append(s.split()) # 최소값 구하기. for y in range(N): for x in range(N): if (y + x) % 2 == 0: i = 9999999 k = -9999999 # 좌 if x - 1 >= 0: #좌 if x - 2 >= 0: i = min(i, int(eval(min_board[y][x - 2] + min_board[y][x - 1] + min_board[y][x]))) k = max(k, int(eval(max_board[y][x - 2] + max_board[y][x - 1] + max_board[y][x]))) #상 if y - 1 >= 0: i = min(i, int(eval(min_board[y - 1][x - 1] + min_board[y][x - 1] + min_board[y][x]))) k = max(k, int(eval(max_board[y - 1][x - 1] + max_board[y][x - 1] + max_board[y][x]))) # 상 if y - 1 >= 0: #좌 if x - 1 >= 0: i = min(i, int(eval(min_board[y - 1][x - 1] + min_board[y - 1][x] + min_board[y][x]))) k = max(k, int(eval(max_board[y - 1][x - 1] + max_board[y - 1][x] + max_board[y][x]))) #상 if y - 2 >= 0: i = min(i, int(eval(min_board[y - 2][x] + min_board[y - 1][x] + min_board[y][x]))) k = max(k, int(eval(max_board[y - 2][x] + max_board[y - 1][x] + max_board[y][x]))) if i != 9999999: min_board[y][x] = str(i) if k != -9999999: max_board[y][x] = str(k) print(max_board[N - 1][N - 1], min_board[N - 1][N - 1]) ================================================ FILE: BOJ/17298.오큰수/6047198844.cpp ================================================ #include #include #include #include using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int N; cin >> N; int num; vector vt; for (int i = 0; i < N; i++) { cin >> num; vt.push_back(num); } vector res; res.resize(vt.size()); stack st; for (int i = 0; i < N; i++) { if (!st.empty()) { while (!st.empty()&&vt[st.top()] < vt[i]) { res[st.top()] = vt[i]; st.pop(); } } st.push(i); } for (int i = 0; i < N; i++) { if (res[i]) cout << res[i] << " "; else cout << "-1" << " "; } } ================================================ FILE: BOJ/1735.분수 합/6047198844.py ================================================ import sys def gcd(a, b): if b == 0: return a return gcd(b, a % b) A, B = map(int, sys.stdin.readline().split()) C, D = map(int, sys.stdin.readline().split()) numerator = A * D + C * B denominator = B * D while True: div = gcd(numerator, denominator) if div == 1: print(numerator, denominator) exit() numerator //= div denominator //= div ================================================ FILE: BOJ/17362.수학은 체육과목 입니다2/6047198844.py ================================================ n = int(input()) res = n % 8 if res == 1: print(1) elif res == 2 or res == 0: print(2) elif res == 3 or res == 7: print(3) elif res == 4 or res == 6: print(4) else: print(5) ================================================ FILE: BOJ/1738.골목길/6047198844.cpp ================================================ #include #include #include #include #define INF INT_MAX using namespace std; bool bellman(vector < vector >> &vt, vector &res) { bool flag = true; int N = vt.size(); vector dist(N,INF); dist[0] = 0; //v w u //v는 0. //dist[w]는 v와 w간의 최단거리 for (int i = 0; i < N; i++) { for (int w = 0; w < N; w++) { for (auto k : vt[w]) { int u = k.first; // 정점 int w_u_cost = k.second; // w에서 u까지가는 경로. if (dist[w]!=INF&&dist[u] > dist[w] + w_u_cost) { dist[u] = dist[w] + w_u_cost; res[u] = w; if (i == N - 1) { for (auto r : vt[u]) { if (r.first == N - 1) flag = false; } } } } } } if (dist[N - 1] == INF) { cout << "뭐임"; } //flag = false; return flag; } int main() { int n, m; cin >> n >> m; vector < vector >> vt(n); vector res(n); int u, v, w; for (int i = 0; i < m; i++) { cin >> u >> v >> w; vt[u - 1].push_back({ v - 1,-w }); } if (bellman(vt, res)) { stack s; s.push(n); for (int idx = n - 1,cnt = 0; res[idx]; idx = res[idx],cnt++) { s.push(res[idx] + 1); } s.push(1); while (!s.empty()) { cout << s.top() << " "; s.pop(); } return 0; } cout << -1; } ================================================ FILE: BOJ/17404.RGB거리 2/6047198844.cpp ================================================ // d[N][0] = 1번집을 제외하고 N번째 집을 빨강으로 칠했을때 최대값 d[N][0] = max(d[N-1][1],d[N-1][2]) // d[N][1] = 1번집을 제외하고 N번째 집을 초록으로 칠했을때 최대값 d[N][1] = max(d[N-1][0],d[N-1][2]) // d[N][2] = 1번집을 제외하고 N번째 집을 파랑으로 칠했을때 최대값 d[N][2] = max(d[N-1][0],d[N-1][1]) #include #include #define MAX 2000000 using namespace std; int arr[1001][3]; int d[1001][3]; int ans = MAX; int dp(int n) { for (int i = 0; i < 3; i++) { d[1][0] = MAX; d[1][1] = MAX; d[1][2] = MAX; d[1][i] = arr[1][i]; for (int j = 2; j <= n; j++) { d[j][0] = min(d[j - 1][1], d[j - 1][2]) + arr[j][0]; d[j][1] = min(d[j - 1][0], d[j - 1][2]) + arr[j][1]; d[j][2] = min(d[j - 1][0], d[j - 1][1]) + arr[j][2]; } for (int k = 0; k <= 2; k++) { if (i != k) { ans = min(ans, d[n][k]); } } } return ans; } int main() { int N; cin >> N; for (int i = 1; i <= N; i++) { cin >> arr[i][0] >> arr[i][1] >> arr[i][2]; } cout << dp(N); } ================================================ FILE: BOJ/17413.단어 뒤집기2/6047198844.py ================================================ tag = '' word = '' res = '' S = input() for char in S: if char == ' ': res += word[::-1] word = '' res += char #flag가 false면 word. True면 tag라는 뜻이다. if char == '<': #쌓여있던 word를 뒤집어서 결과에 붙인다. res += word[::-1] word = '' tag += char elif char == '>': tag += char res += tag tag = '' elif tag == '': word += char else: tag += char res += word[::-1] print(res) ================================================ FILE: BOJ/17478.재귀함수가 뭔가요?/6047198844.py ================================================ import sys def func(depth, max_depth): if(depth == max_depth): print("____" * depth + '"재귀함수가 뭔가요?"') print("____" * depth + '"재귀함수는 자기 자신을 호출하는 함수라네"') print("____" * depth + '라고 답변하였지.') return print("____" * depth + '"재귀함수가 뭔가요?"') print("____" * depth + '"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.') print("____" * depth + '마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.') print("____" * depth + '그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어."') func(depth + 1, max_depth) print("____" * depth + '라고 답변하였지.') print("어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.") func(0, int(sys.stdin.readline())) ================================================ FILE: BOJ/1753. 최단 경로/rockmiin.py ================================================ import heapq V, E= map(int, input().split()) start= int(input()) INF= int(1e9) adj= [[] for _ in range(V+1)] distance= [INF] * (V+1) visited= [0]* (V+1) # 모든 간선에 대한 입력정보 입력 -> u에서 v로 가는 가중치 w인 것 for i in range(1, V+1): u, v, w= map(int, input().split()) adj[u].append([v, w]) def dijkstra(start): q= [] # 시작 노드 push, 값을 0으로 설정하여 입력 # 이렇게 입력을 하면 q에서 거리가 짧은 것이 제일 먼저 pop이 될 것이다. heapq.heappush(q, (0, start)) distance[start]= 0 while q: # 지금 상태에서 dist가 제일 작은 값 pop dist, now= heapq.heappop(q) if distance[now]< dist: continue for i in adj[now]: cost= dist+ i[1] if cost< distance[i[0]]: distance[i[0]]= cost dijkstra(start) for i in range(1, V+1): if distance[i] == INF: print('INF'); continue print(distance[i]) ================================================ FILE: BOJ/1753.최단경로/6047198844.cpp ================================================ #include #include #include #include using namespace std; #define INF INT_MAX vector > edge[20001]; vector dijkstra(int V, int K) { vector dist(V + 1, INF); dist[K] = 0; priority_queue > pq; pq.push({ 0,K }); while (!pq.empty()) { int cost = -pq.top().first; int here = pq.top().second; pq.pop(); if (cost > dist[here]) continue; for (auto neigh : edge[here]) { if (dist[neigh.first] > cost + neigh.second) { dist[neigh.first] = cost + neigh.second; pq.push({ -dist[neigh.first] ,neigh.first }); } } } return dist; } int main() { int V, E; int K; int u, v, w; cin >> V >> E; cin >> K; while (E--) { cin >> u >> v >> w; edge[u].push_back({ v,w }); } vector dist = dijkstra(V, K); for (int i = 1; i <= V; i++) { if (dist[i] == INF) cout << "INF"; else cout << dist[i]; cout << "\n"; } } ================================================ FILE: BOJ/1755.숫자놀이/6047198844.py ================================================ table = dict() table['0'] = 'zero' table['1'] = 'one' table['2'] = 'two' table['3'] = 'three' table['4'] = 'four' table['5'] = 'five' table['6'] = 'six' table['7'] = 'seven' table['8'] = 'eight' table['9'] = 'nine' table['zero'] = '0' table['one'] = '1' table['two'] = '2' table['three'] = '3' table['four'] = '4' table['five'] = '5' table['six'] = '6' table['seven'] = '7' table['eight'] = '8' table['nine'] = '9' M, N = map(int, input().split()) alphanum_list = list() for i in range(M, N + 1): alphanum = ' '.join(map(table.get, list(str(i)))) alphanum_list.append(alphanum) alphanum_list.sort() numeric_list = list() for alphanum in alphanum_list: numeric = ''.join(map(table.get, alphanum.split(' '))) numeric_list.append(numeric) for start_idx in range(0, len(numeric_list), 10): for numeric in numeric_list[start_idx:start_idx+10]: print(numeric, end=' ') print() ================================================ FILE: BOJ/1758.알바생 강호/6047198844.py ================================================ N = int(input()) tips = list() for _ in range(N): tips.append(int(input())) tips.sort(reverse=True) res = 0 i = 0 for nth in range(N): if tips[nth] - nth > 0: res += tips[nth] - nth else: break print(res) ================================================ FILE: BOJ/1759.암호만들기/6047198844.cpp ================================================ /* 자음 / 모음으로 나눈다. 전체 - 자음갯수 = 모음갯수 인데, 모음갯수는 2와 같거나 커야한다. 전채 - 모음갯수 = 자음갯수 queue에 일단 넣고 정렬한다. dfs로 구현 dfs(자음 갯수 , 모음 갯수) */ #include #include #include #include #include #include #include using namespace std; set res_st; vector jaum; vector moum; void dfs(int cnt_jaum, int cnt_total,bool blank[26],string res) { if (!cnt_total){ sort(res.begin(), res.end()); res_st.insert(res); return; } if (cnt_jaum){ for (int i = 0; i < moum.size(); i++) { if (!blank[moum[i] - 'a']) { blank[moum[i] - 'a'] = true; dfs(cnt_jaum - 1, cnt_total - 1, blank, res + moum[i]); blank[moum[i] - 'a'] = false; } } } else { int smallest = 0; if (!res.empty()) { auto it = find(jaum.begin(), jaum.end(), res.back()); if (it != jaum.end()) smallest = it - jaum.begin(); } for (int i = 0; i < jaum.size(); i++) { if (!blank[jaum[i] - 'a']) { blank[jaum[i] - 'a'] = true; dfs(cnt_jaum, cnt_total - 1, blank, res + jaum[i]); blank[jaum[i] - 'a'] = false; } } } return; } int main() { int L, C; cin >> L >> C; char w; for (int i = 0; i < C; i++) { cin >> w; if (w == 'a' || w == 'e' || w == 'i' || w == 'o' || w == 'u') moum.push_back(w); else jaum.push_back(w); } sort(moum.begin(), moum.end()); sort(jaum.begin(), jaum.end()); int moum_size = moum.size(); int moum_max_size = min(moum_size, (L - 2)); for (int i = 1; i <= moum_max_size; i++) { string res = ""; bool blank[26]; memset(blank, false, sizeof(bool) * 26); dfs(i, L, blank, res); } for (auto i = res_st.begin(); i != res_st.end(); i++) cout << *i << "\n"; } ================================================ FILE: BOJ/1761.정점들의 거리/6047198844.py ================================================ # O(NM) => 40,000 * 10,000 = 4억 # O(MlogN) => 10,000 * 200 = 2백만 import sys from collections import defaultdict sys.setrecursionlimit(10 ** 9) LOG = 21 N = int(sys.stdin.readline()) edges = defaultdict(list) for _ in range(N - 1): v, w, distance = map(int, sys.stdin.readline().split()) edges[v].append((w, distance)) edges[w].append((v, distance)) visited = [0 for _ in range(N + 1)] D = [0 for _ in range(N + 1)] P = [[0 for _ in range(LOG + 1)] for _ in range(N + 1)] C = [0 for _ in range(N + 1)] def make_tree(V, depth, cost): visited[V] = 1 C[V] = cost D[V] = depth for W, distance in edges[V]: if visited[W] != 1: P[W][0] = V make_tree(W, depth + 1, cost + distance) # 루트를 1로 잡는다. make_tree(1, 0, 0) # 공통부모 세팅 for i in range(1, LOG): for j in range(1, N + 1): P[j][i] = P[P[j][i - 1]][i - 1] def LCA(A, B): # 두노드의 높이를 맞춘다. 단 B는 항상 A 보다 높이가 낮다. if D[A] > D[B]: A, B = B, A # 역순으로 하지 않으면, 차이를 꽉 매우지 못할수도 있음. for i in range(LOG, -1, -1): if D[B] - D[A] >= 1 << i: B = P[B][i] # 두노드의 높이를 맞췄다면, 위에서 부터 공통 부모를 찾는다. # 이미 같으면 A를 반환한다. if A == B: return A for i in range(LOG, -1, -1): if P[A][i] != P[B][i]: A = P[A][i] B = P[B][i] return P[A][0] M = int(sys.stdin.readline()) for _ in range(M): v, w = map(int, sys.stdin.readline().split()) print(C[v] + C[w] - 2 * C[LCA(v, w)]) ================================================ FILE: BOJ/17626.Four Squares/6047198844.py ================================================ from itertools import combinations_with_replacement n = int(input()) squares = [i ** 2 for i in range(225)] for combinations in combinations_with_replacement(squares, 3): if sum(combinations) == n: print(len(combinations) - combinations.count(0)) exit() print(4) ================================================ FILE: BOJ/1764. 듣보잡/ms9849.cpp ================================================ #include #include using namespace std; string s[1000000]; string ans[500000]; int N,M,cnt=0; int main(void) { cin >> N >> M; for(int i=0; i> s[i]; for(int j=N; j> s[j]; sort(s,s+N+M); for(int i=1; i 1: X = str(sum(map(int, X))) cnt += 1 print(cnt) if X == '3' or X == '6' or X == '9': print('YES') else: print('NO') ================================================ FILE: BOJ/17829.222-풀링/6047198844.py ================================================ # 문제 # 정사각형에서 2번째로 큰 수만 남긴다. 여기서 2번째로 큰 수란, 정사각형의 네 원소를 크기순으로 a4 ≤ a3 ≤ a2 ≤ a1 라 했을 때, 원소 a2를 뜻한다. # 종욱이는 N×N 행렬에 222-풀링을 반복해서 적용하여 크기를 1×1로 만들었을 때 어떤 값이 남아있을지 궁금해한다. # # 입력 # 첫째 줄에 N(2 ≤ N ≤ 1024)이 주어진다. N은 항상 2의 거듭제곱 꼴이다. (N=2K, 1 ≤ K ≤ 10) # # 다음 N개의 줄마다 각 행의 원소 N개가 차례대로 주어진다. 행렬의 모든 성분은 -10,000 이상 10,000 이하의 정수이다. # # 출력 # 마지막에 남은 수를 출력한다. def polling(arr): if len(arr) == 1: return arr[0][0] new_arr = list() # 새로운 어레이 구성 for i in range(0, len(arr), 2): row = list() for j in range(0, len(arr[0]), 2): row.append(list(sorted([arr[i][j], arr[i][j + 1], arr[i + 1][j], arr[i + 1][j + 1]]))[2]) new_arr.append(row) return polling(new_arr) N = int(input()) arr = [list(map(int, input().split())) for _ in range(N)] print(polling(arr)) ================================================ FILE: BOJ/1789.수들의 합/6047198844.py ================================================ import sys S = int(sys.stdin.readline()) cnt = 0 acc = 0 i = 1 while acc <= S: acc += i i += 1 cnt += 1 print(cnt-1) ================================================ FILE: BOJ/1799.비숍/6047198844.py ================================================ # 문제 # 서양 장기인 체스에는 대각선 방향으로 움직일 수 있는 비숍(bishop)이 있다. # 비숍은 대각선 방향으로 움직여 다른 말을 잡을 수 있다. # # 그런데 체스판 위에는 비숍이 놓일 수 없는 곳이 있다. # 색칠된 부분에는 비숍이 놓일 수 없지만 지나갈 수는 있다. # # 정사각형 체스판의 한 변에 놓인 칸의 개수를 체스판의 크기라고 한다. 체스판의 크기와 체스판 각 칸에 비숍을 놓을 수 있는지 없는지에 대한 정보가 주어질 때, 서로가 서로를 잡을 수 없는 위치에 놓을 수 있는 비숍의 최대 개수를 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 체스판의 크기가 주어진다. 체스판의 크기는 10이하의 자연수이다. # 둘째 줄부터 아래의 예와 같이 체스판의 각 칸에 비숍을 놓을 수 있는지 없는지에 대한 정보가 체스판 한 줄 단위로 한 줄씩 주어진다. 비숍을 놓을 수 있는 곳에는 1, 비숍을 놓을 수 없는 곳에는 0이 빈칸을 사이에 두고 주어진다. # # 출력 # 첫째 줄에 주어진 체스판 위에 놓을 수 있는 비숍의 최대 개수를 출력한다. import sys N = int(sys.stdin.readline()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] left_visited = [False for _ in range(2 * N - 1)] right_visited = [False for _ in range(2 * N - 1)] # y, x에 비숍을 위치하거나 위치하지 않았을때 놓을수있는 비숍의 최대 개수 def backtracking(y, x): # base case : 종료 조건 if y == N: return 0 # 예외 : x 범위를 벗어남 if x >= N: return backtracking(y + 1, (x + 1) % 2) # 현재 위치에 비숍을 놓지 않는 경우 res = backtracking(y, x + 2) # 현재 위치에 비숍을 놓는 경우 if board[y][x] == 1 and left_visited[y + x] == False and right_visited[N - 1 + y - x] == False: left_visited[y + x] = right_visited[N - 1 + y - x] = True res = max(res, 1 + backtracking(y, x + 2)) left_visited[y + x] = right_visited[N - 1 + y - x] = False return res print(backtracking(0, 0) + backtracking(0, 1)) ================================================ FILE: BOJ/1806.부분합/6047198844.cpp ================================================ //투포인터 이용. #include #include #include using namespace std; int main() { int N; int S; vector vt; cin >> N >> S; vt.resize(N); for (int i = 0; i < N; i++) cin >> vt[i]; //투포인터는 양수에만 적용된다. //start는 현재합이 목표값보다 크거나 같은 경우 증가한다. //end 현재합이 목표값보다 작은 경우 증가한다. //start와 end가 같은 경우 현재합은 0이다. int part_sum = 0; int res = 100001; int end = 0; int start = 0; while(1) { if (part_sum >= S) { res = min(res, end - start); part_sum -= vt[start++]; } else if (end == N) break; else part_sum += vt[end++]; } if (res != 100001) cout << res; else cout << 0; } ================================================ FILE: BOJ/1806.부분합/6047198844.py ================================================ import math import sys N, S = map(int, sys.stdin.readline().split()) arr = list(map(int, sys.stdin.readline().split())) begin = 0 end = 0 part_sum = arr[begin] part_len = math.inf for begin in range(N): while end < N and part_sum < S: end += 1 if end != N: part_sum += arr[end] if end == N: break part_len = min(part_len, end - begin + 1) part_sum -= arr[begin] print(0) if part_len == math.inf else print(part_len) ================================================ FILE: BOJ/18108.1998년생인 내가 태국에서는 2541년생?!/6047198844.py ================================================ print(int(input())-543) ================================================ FILE: BOJ/18111.마인크래프트/6047198844.py ================================================ # 문제 # lvalue는 세로 N, 가로 M 크기의 집터를 골랐다. 집터 맨 왼쪽 위의 좌표는 (0, 0)이다. # 좌표 (i, j)의 가장 위에 있는 블록을 제거하여 인벤토리에 넣는다. # 인벤토리에서 블록 하나를 꺼내어 좌표 (i, j)의 가장 위에 있는 블록 위에 놓는다. # 1번 작업은 2초가 걸리며, 2번 작업은 1초가 걸린다. # ‘땅 고르기’ 작업에 걸리는 최소 시간과 그 경우 땅의 높이를 출력하시오. # 단, 집터 아래에 동굴 등 빈 공간은 존재하지 않으며, 집터 바깥에서 블록을 가져올 수 없다. # 또한, 작업을 시작할 때 인벤토리에는 B개의 블록이 들어 있다. 땅의 높이는 256블록을 초과할 수 없으며, 음수가 될 수 없다. # # 입력 # 첫째 줄에 N, M, B가 주어진다. (1 ≤ M, N ≤ 500, 0 ≤ B ≤ 6.4 × 107) # # 둘째 줄부터 N개의 줄에 각각 M개의 정수로 땅의 높이가 주어진다. (i + 2)번째 줄의 (j + 1)번째 수는 좌표 (i, j)에서의 땅의 높이를 나타낸다. 땅의 높이는 256보다 작거나 같은 자연수 또는 0이다. # # 출력 # 첫째 줄에 땅을 고르는 데 걸리는 시간과 땅의 높이를 출력하시오. 답이 여러 개 있다면 그중에서 땅의 높이가 가장 높은 것을 출력하시오. import math import sys N, M, B = map(int, sys.stdin.readline().split()) lands = [] for _ in range(N): for i in map(int, sys.stdin.readline().split()): lands.append(i) lands.sort(reverse=True) max_height, min_height = lands[0], lands[-1] res_time = math.inf res_height = max_height # 요구 높이. for height in range(max_height, min_height - 1, -1): inventory = B count = 0 for land in lands: # 요구 높이 보다 크다면. if land > height: # 차이 dif = land - height # 인벤토리에 추가한다. inventory += dif # 차이만큼 요금을 부과한다. count += dif * 2 elif land < height: # 차이 dif = height - land if inventory >= dif: # 차이만큼 인벤토리에서 뽑는다. inventory -= dif # 차이만큼 요금을 부과한다. count += dif # 못뽑으면 탈출한다. else: break else: if res_time > count: res_time = count res_height = height print(res_time, res_height, sep=' ') ================================================ FILE: BOJ/1817.짐 챙기는 숌/6047198844.py ================================================ N, M = map(int, input().split()) if N != 0: books = map(int, input().split()) ans = 1 cur_weight = 0 for book in books: if cur_weight + book <= M: cur_weight += book else: cur_weight = book ans += 1 print(ans) else: print(0) ================================================ FILE: BOJ/18258.큐 2/6047198844.cpp ================================================ #include using namespace std; int q[2000001]; int head = 0; int tail = 0; //empty : 큐가 비어있으면 1, 아니면 0을 출력한다. bool isEmpty() { return head == tail; } //push X : 정수 X를 큐에 넣는 연산이다. void push(int X) { q[tail++] = X; tail = tail % 2000000; } //pop : 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다.만약 큐에 들어있는 정수가 없는 경우에는 - 1을 출력한다. void pop() { if (isEmpty()) cout << "-1"; else { cout << q[head++]; head = head % 2000000; } cout << "\n"; } //size : 큐에 들어있는 정수의 개수를 출력한다. void size() { cout << abs(tail - head) << "\n"; } //front : 큐의 가장 앞에 있는 정수를 출력한다.만약 큐에 들어있는 정수가 없는 경우에는 - 1을 출력한다. void front() { if (isEmpty()) cout << -1; else cout << q[head]; cout << "\n"; return; } //back : 큐의 가장 뒤에 있는 정수를 출력한다.만약 큐에 들어있는 정수가 없는 경우에는 - 1을 출력한다. void back() { if (isEmpty()) cout << -1; else { if (tail == 0) cout << q[2000000]; else cout << q[tail - 1]; } cout << "\n"; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int N; cin >> N; while (N--) { string s; cin >> s; if (s == "push") { int X; cin >> X; push(X); } else if (s == "pop") pop(); else if (s == "size") size(); else if (s == "empty") { if (isEmpty()) cout << "1"; else cout << "0"; cout << "\n"; } else if (s == "front") front(); else back(); } } ================================================ FILE: BOJ/18312.시각/6047198844.py ================================================ # 문제 # 정수 N과 K가 입력되었을 때 00시 00분 00초부터 N시 59분 59초까지의 모든 시각 중에서 K가 하나라도 포함되는 모든 시각을 세는 프로그램을 작성하시오. 시각을 셀 때는 디지털 시계를 기준으로, 초 단위로만 시각을 구분한다. # # 예를 들어 K=3일 때, 다음의 시각들은 3이 하나 이상 포함되어 있으므로 세어야 하는 시각의 대표적인 예시이다. # # 23시 00분 00초 # 07시 08분 33초 # 반면에 다음의 시각들은 3이 하나도 포함되어 있지 않으므로 세면 안 되는 예시이다. # # 15시 02분 55초 # 18시 27분 45초 # 입력 # 첫째 줄에 정수 N과 K가 공백을 기준으로 구분되어 주어진다. (0≤N≤23, 0≤K≤9) # # 출력 # 00시 00분 00초부터 N시 59분 59초까지의 모든 시각 중에서 K가 하나라도 포함되는 시각들의 수를 출력한다. from datetime import timedelta, datetime N, K = input().split() start_time = datetime(100, 1, 1, 0, 0, 0) end_time = datetime(100, 1, 1, int(N), 59, 59) res = 0 while start_time <= end_time: res += int(K in start_time.strftime('%H%M%S')) start_time += timedelta(seconds=1) print(res) ================================================ FILE: BOJ/1834.나머지와 몫이 같은 수/6047198844.py ================================================ N = int(input()) res = 0 # 나머지이자 몫 for i in range(1, N): res += i * N + i print(res) ================================================ FILE: BOJ/18353.병사 배치하기/6047198844.py ================================================ # 문제 # N명의 병사가 무작위로 나열되어 있다. 각 병사는 특정한 값의 전투력을 보유하고 있으며, 병사를 배치할 때는 전투력이 높은 병사가 앞쪽에 오도록 내림차순으로 배치를 하고자 한다. # 다시 말해 앞쪽에 있는 병사의 전투력이 항상 뒤쪽에 있는 병사보다 높아야 한다. # 또한 배치 과정에서는 특정한 위치에 있는 병사를 열외시키는 방법을 이용한다. 그러면서도 남아있는 병사의 수가 최대가 되도록 하고 싶다. # 병사에 대한 정보가 주어졌을 때, 남아있는 병사의 수가 최대가 되도록 하기 위해서 열외해야 하는 병사의 수를 출력하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 N이 주어진다. (1 ≤ N ≤ 2,000) 둘째 줄에 각 병사의 전투력이 공백을 기준으로 구분되어 차례대로 주어진다. 각 병사의 전투력은 10,000,000보다 작거나 같은 자연수이다. # # 출력 # 첫째 줄에 남아있는 병사의 수가 최대가 되도록 하기 위해서 열외해야 하는 병사의 수를 출력한다. N = int(input()) solders = list(map(int, input().split())) memo = [1 for _ in range(N)] for i in range(N): for j in range(i): if solders[i] < solders[j]: memo[i] = max(memo[i], memo[j] + 1) print(N - max(memo)) ================================================ FILE: BOJ/18512.점프 점프/6047198844.py ================================================ X, Y, P1, P2 = map(int, input().split()) S1, S2 = P1, P2 visited = set() visited.add(S1) visited.add(S2) for _ in range(100001): S1 += X S2 += Y if S1 in visited: print(S1) break if S2 in visited: print(S2) break visited.add(S1) visited.add(S2) else: print(-1) ================================================ FILE: BOJ/1864.문어 숫자/6047198844.py ================================================ octopus = dict() octopus['-'] = 0 octopus["\\"] = 1 octopus['('] = 2 octopus['@'] = 3 octopus['?'] = 4 octopus['>'] = 5 octopus['&'] = 6 octopus['%'] = 7 octopus['/'] = -1 while True: octopus_num = input()[::-1] if octopus_num == '#': break res = 0 for idx, n in enumerate(octopus_num): res += int(octopus[n]) * (8 ** int(idx)) print(res) ================================================ FILE: BOJ/1865.웜홀/6047198844.py ================================================ import heapq import math import sys TC = int(sys.stdin.readline()) for _ in range(TC): N, M, W = map(int, sys.stdin.readline().split()) edges = [] for _ in range(M): S, E, T = map(int, sys.stdin.readline().split()) edges.append((S, E, T)) edges.append((E, S, T)) for _ in range(W): S, E, T = map(int, sys.stdin.readline().split()) edges.append((S, E, -T)) dist = [987654321 for _ in range(N+1)] for _ in range(N-1): for S, E, T in edges: if dist[E] > dist[S] + T: dist[E] = dist[S] + T for S, E, T in edges: if dist[E] > dist[S] + T: print('YES') break else: print('NO') ================================================ FILE: BOJ/1874.스택 수열/6047198844.py ================================================ import sys n = int(sys.stdin.readline()) target = [int(sys.stdin.readline()) for _ in range(n)] stack = [] ans = [] cnt = 0 i = 1 for t in target: # 넣는 값이(i) 목표치보다 작을 경우. 무조건 stack에 없는 값이므로 i의 값까지 stack 에 계속 push 한다. while i <= t: ans.append('+') stack.append(i) i += 1 # t의 값이 stack에서 나올때까지 stack에서 계속 꺼낸다. while stack: ans.append('-') if stack.pop() == t: cnt += 1 break if cnt == n: for a in ans: print(a) else: print('NO') ================================================ FILE: BOJ/18868.멀티버스 Ⅰ/6047198844.py ================================================ # 문제 # M개의 우주가 있고, 각 우주에는 1부터 N까지 번호가 매겨진 행성이 N개 있다. # 행성의 크기를 알고 있을때, 균등한 우주의 쌍이 몇 개인지 구해보려고 한다. 구성이 같은데 순서만 다른 우주의 쌍은 한 번만 센다. (조합) # # 두 우주 A와 B가 있고, 우주 A에 있는 행성의 크기는 A1, A2, ..., AN, 우주 B에 있는 행성의 크기는 B1, B2, ..., BN라고 하자. # 두 우주의 행성 크기가 모든 1 ≤ i, j ≤ N에 대해서 아래와 같은 조건을 만족한다면, 두 우주를 균등하다고 한다. # # Ai < Aj → Bi < Bj # Ai = Aj → Bi = Bj # Ai > Aj → Bi > Bj # 입력 # 첫째 줄에 우주의 개수 M과 각 우주에 있는 행성의 개수 N이 주어진다. 둘째 줄부터 M개의 줄에 공백으로 구분된 행성의 크기가 한 줄에 하나씩 1번 우주부터 차례대로 주어진다. # # 출력 # 첫째 줄에 균등한 우주의 쌍의 개수를 출력한다. # # 제한 # 2 ≤ M ≤ 10 # 3 ≤ N ≤ 100 # 1 ≤ 행성의 크기 ≤ 10,000 from itertools import combinations # 균등한지 판단하는 함수 def is_equal(a_mar, b_mar, n): for i, j in combinations(range(n), 2): if a_mar[i] < a_mar[j] and b_mar[i] < b_mar[j]: pass elif a_mar[i] == a_mar[j] and b_mar[i] == b_mar[j]: pass elif a_mar[i] > a_mar[j] and b_mar[i] > b_mar[j]: pass else: return 0 else: return 1 M, N = map(int, input().split()) mars = [list(map(int, input().split())) for _ in range(M)] res = 0 for i, j in combinations(range(M), 2): res += is_equal(mars[i], mars[j], N) print(res) ================================================ FILE: BOJ/18870.좌표 압축/6047198844.cpp ================================================ #include #include #include #include using namespace std; vector CompCoordinate(vector Coord) { vector Coord_ = Coord; sort(Coord_.begin(), Coord_.end()); Coord_.erase(unique(Coord_.begin(), Coord_.end()), Coord_.end()); map m; for (int i = 0; i < Coord_.size(); i++) m[Coord_[i]] = i; for (int i = 0; i < Coord.size(); i++) Coord[i] = m[Coord[i]]; return Coord; } int main() { int N; cin >> N; vector Coord(N); for (int i = 0; i < N; i++) cin >> Coord[i]; vector CompCoord = CompCoordinate(Coord); for (int i : CompCoord) cout << i << " "; } ================================================ FILE: BOJ/1890.점프/6047198844.cpp ================================================ #include using namespace std; long long board[100][100]; long long memo[100][100]; //memo[y][x] : y, x 좌표에서의 개수 bool check[100][100]; int N; long long dp(int y, int x) { if (x >= N || y >= N) return 0; if (y == N - 1 && x == N - 1) return 1; if (check[y][x]) return memo[y][x]; long long& res = memo[y][x]; check[y][x] = true; res = dp(y + board[y][x], x) + dp(y, x + board[y][x]); return res; } int main() { cin >> N; for (int y = 0; y < N; y++) for (int x = 0; x < N; x++) cin >> board[y][x]; cout << dp(0, 0); } ================================================ FILE: BOJ/1895.필터/6047198844.py ================================================ R, C = map(int, input().split()) pixels = [] res = 0 # 입력 for _ in range(R): pixels.append(list(map(int, input().split()))) T = int(input()) # 정제 for y in range(1, R-1): for x in range(1, C-1): filtered = list() for dy in (-1, 0, 1): for dx in (-1, 0, 1): filtered.append(pixels[y+dy][x+dx]) filtered.sort() if filtered[4] >= T: res += 1 print(res) ================================================ FILE: BOJ/1904.01타일/6047198844.cpp ================================================ #include using namespace std; int dp(int n) { int a = 1; int b = 2; int temp; for (int i = 2; i <= n; i++) { temp = b; b = (a + b) % 15746; a = temp; } return a; } int main() { int n; cin >> n; cout << dp(n); } ================================================ FILE: BOJ/1916.최소비용 구하기/1916_최소비용 구하기.cpp ================================================ #include #include #include #include using namespace std; int Dijkstra(int start, int end, vector >> cost) { //start to everywhere ּҰ. vector dist(cost.size() + 1, INT_MAX); priority_queue> pq; pq.push({ 0,start }); dist[start] = 0; while (!pq.empty()) { int mininum_cost = -pq.top().first; int that_vertex = pq.top().second; pq.pop(); if (mininum_cost > dist[that_vertex]) continue; for (auto p : cost[that_vertex]) { if (mininum_cost + p.first < dist[p.second]) { dist[p.second] = mininum_cost + p.first; pq.push({ -dist[p.second] ,p.second }); } } } return dist[end]; } int main() { int N; cin >> N; vector >> cost; cost.resize(N + 1); int M; cin >> M; int from_city; int to_city; int bus_cost; for (int i = 0; i < M; i++) { cin >> from_city >> to_city >> bus_cost; cost[from_city].push_back({ bus_cost,to_city }); } int res_from_city; int res_to_city; cin >> res_from_city >> res_to_city; cout << Dijkstra(res_from_city, res_to_city, cost); } ================================================ FILE: BOJ/1918.후위 표기식/6047198844.py ================================================ sentence = input() N = len(sentence) stack = [] res = '' def priority(op): if op == '*' or op == '/': return 2 elif op == '+' or op == '-': return 1 elif op == '(' or op == ')': return 0 return -1 for i in range(N): # 알파벳인 경우 if sentence[i].isalpha(): res += sentence[i] # 괄호인 경우 elif sentence[i] == '(': stack.append(sentence[i]) elif sentence[i] == ')': while stack and stack[-1] != '(': res += stack.pop() stack.pop() # 연산자인 경우 else: while stack and priority(stack[-1]) >= priority(sentence[i]): res += stack.pop() stack.append(sentence[i]) res += ''.join(stack[::-1]) print(res) ================================================ FILE: BOJ/1920.수 찾기/6047198844.cpp ================================================ #include #include #include using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int N; cin >> N; vector arr(N); for (int i = 0; i < N; i++) cin >> arr[i]; sort(arr.begin(), arr.end()); int M; cin >> M; for (int i = 0; i < M; i++) { int _; cin >> _; int idx = lower_bound(arr.begin(), arr.end(), _) - arr.begin(); int res = 0; if (idx != arr.size()&&arr[idx] == _) res = 1; cout << res << "\n"; } } ================================================ FILE: BOJ/19238.스타트 택시/6047198844.py ================================================ import sys from collections import deque N, M, K = map(int, sys.stdin.readline().split()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] cur_pos = tuple(map(lambda i: int(i) - 1, sys.stdin.readline().split())) customers = dict() for _ in range(M): iy, ix, jy, jx = map(lambda i: int(i) - 1, sys.stdin.readline().split()) customers[(iy, ix)] = (jy, jx) # 반복문 조건 : 연료가 0이상, 손님이 있어야 한다. while K >= 0 and customers: # 고객을 찾는다. # 방문한곳은 다시 방문하지 않는다. visited = set() visited.add(cur_pos) Q = deque() Q.append(cur_pos) shortest_customers = list() # 현재 위치에 손님이 있는 경우. if cur_pos in customers: shortest_customers.append(cur_pos) fuel = 0 # 현재위치에 손님이 위치할때까지 찾는다. while Q and not shortest_customers: fuel += 1 for _ in range(len(Q)): cur_y, cur_x = Q.popleft() for ny, nx in (cur_y - 1, cur_x), (cur_y + 1, cur_x), (cur_y, cur_x - 1), (cur_y, cur_x + 1): if 0 <= ny < N and 0 <= nx < N and (ny, nx) not in visited and board[ny][nx] == 0: Q.append((ny, nx)) visited.add((ny, nx)) if (ny, nx) in customers: shortest_customers.append((ny, nx)) # 손님이 존재한다면 if shortest_customers: shortest_customers.sort() cur_pos = shortest_customers[0] # 현재 승객위치. 단 이 승객은 row / column 이 가장 작은 승객이다. K -= fuel # 연료를 소모한다. # 도착 위치 target_y, target_x = customers.get(cur_pos) TQ = deque() TQ.append(cur_pos) target_visited = set() target_visited.add(cur_pos) is_arrived = False target_fuel = 0 # 도착 위치까지 최단 거리로 이동 while TQ and (not is_arrived): target_fuel += 1 for _ in range(len(TQ)): cur_y, cur_x = TQ.popleft() for ny, nx in (cur_y - 1, cur_x), (cur_y + 1, cur_x), (cur_y, cur_x - 1), (cur_y, cur_x + 1): if 0 <= ny < N and 0 <= nx < N and (ny, nx) not in target_visited and board[ny][nx] == 0: TQ.append((ny, nx)) target_visited.add((ny, nx)) if (ny, nx) == (target_y, target_x): is_arrived = True # 도착하면 일단 연료를 깎는다. if is_arrived: K -= target_fuel # 도착하지 못하면 끝이다. else: break # 2배 연료 충전. if K >= 0: K += 2 * target_fuel # 연료가 없을 경우. 끝이다. else: break # 승객을 제거. 현재 위치를 이동시킨다. customers.pop(shortest_customers[0]) cur_pos = (target_y, target_x) # 손님을 하나도 못태운 경우 else: break # 연료가 0 이상인데, 손님이 없는 경우 if K >= 0 and not customers: print(K) # 연료가 0 미만인 경우. 손님 유무와 상관없이 -1 / 연료가 있지만 손님도 있는 경우. else: print(-1) ================================================ FILE: BOJ/1926.그림/6047198844.py ================================================ import sys from collections import defaultdict n, m = map(int, sys.stdin.readline().split()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(n)] P = [i for i in range(n * m)] def union(A, B): PA = find(A) PB = find(B) if PA == PB: return P[PA] = PB def find(A): if A == -1 or A == P[A]: return A P[A] = find(P[A]) return P[A] for y in range(n): for x in range(m): if board[y][x] == 0: P[m * y + x] = -1 continue for ny, nx in (y + 1, x), (y, x + 1), (y - 1, x), (y, x - 1): if 0 <= ny < n and 0 <= nx < m and board[ny][nx] == 1: A = m * y + x B = m * ny + nx union(A, B) dictionary = defaultdict(int) for i in P: dictionary[find(i)] += 1 res_n = 0 res_area = 0 for key, value in dictionary.items(): if key == -1: continue res_n += 1 res_area = max(res_area, value) print(res_n) print(res_area) ================================================ FILE: BOJ/1927.최소 힙/6047198844.cpp ================================================ #include #include using namespace std; void insert_adj(vector &heap,int child_idx) { if (child_idx == 0) return; int parent_idx = (child_idx - 1) / 2; if (heap[parent_idx] > heap[child_idx]) { swap(heap[parent_idx], heap[child_idx]); insert_adj(heap, parent_idx); } return; } void insert(vector &heap, const int element) { heap.push_back(element); insert_adj(heap, heap.size() - 1); } void del_adj(vector &heap, int parent,const int max_idx) { int leftChildIndex = parent * 2 + 1; int rightChildIndex = parent * 2 + 2; if (leftChildIndex > max_idx) return; int smallElementIndex = leftChildIndex; if (leftChildIndex != max_idx && heap[leftChildIndex] > heap[rightChildIndex]) smallElementIndex = rightChildIndex; if (heap[smallElementIndex] < heap[parent]) { swap(heap[smallElementIndex], heap[parent]); del_adj(heap, smallElementIndex, max_idx); } return; } int del(vector &heap) { if (heap.empty()) return 0; int res = heap[0]; heap[0] = heap.back(); heap.pop_back(); del_adj(heap, 0, heap.size() - 1); return res; } int main() { int N; scanf("%d", &N); vector heap; int cmd; while (N--) { scanf("%d", &cmd); if (cmd) insert(heap, cmd); else printf("%d\n",del(heap)); } } ================================================ FILE: BOJ/1929.소수 구하기/6047198844.py ================================================ prime = [True] * 10000001 # 소수이면 True def sieve(): prime[1] = False for n in range(2, 10000001): if prime[n]: # n 가 소수인경우 for m in range(n + n, 10000001, n): prime[m] = False sieve() M , N = map(int, input().split()) for _ in range(M,N+1): if prime[_]: print(_) ================================================ FILE: BOJ/1931. 회의실 배정/rockmiin.py ================================================ n= int(input()) arr= [] cnt= 0 for i in range(n): arr.append(list(map(int, input().split()))) # 첫번째 원소 기준으로 정렬을 해준 뒤 두번째 원소 기준으로 정렬을 해주는 것이 핵심 # print(arr) arr.sort(key = lambda x : (x[1], x[0])) # print(arr) start, end= 0, 0 # 지금 하고 있는 회의의 종료 시점보다 arr값의 시작 값이 같거나 동일하다면 그 회의 시작, count for i in range(n): x, y= arr[i][0], arr[i][1] if x>= end: start, end= x, y # print(start, end) cnt+=1 print(cnt) ================================================ FILE: BOJ/1932.정수 삼각형/6047198844.cpp ================================================ #include #include using namespace std; int arr[501][501]; int memo[501][501]; int bottom_up(int n) { memo[1][0] = arr[1][0]; for (int j = 2; j <= n; j++) { for (int i = 0; i < j; i++) { if (i != 0) memo[j][i] = memo[j - 1][i - 1]; if (i != n - 1) memo[j][i] = max(memo[j][i], memo[j - 1][i]); memo[j][i] += arr[j][i]; } } int res = 0; for (int i = 0; i < n; i++) { res = max(res, memo[n][i]); } return res; } int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { cin >> arr[i][j]; } } cout << bottom_up(n); } ================================================ FILE: BOJ/1932.정수 삼각형/ms9849.cpp ================================================ #include using namespace std; int dp[501][501]; int arr[501][501]; int Max = 0,N; int main(void) { cin >> N; for(int i=1; i<=N; i++) //[1][1]부터 값을 입력받기 시작합니다. for(int j=1; j<=i; j++) cin >> arr[i][j]; /* 숫자들을 한쪽으로 몰아서 계단 형태로 놓고 보면, 다음 경로로 향할 때 가능한 경로는 arr[Y-1][X] 또는 arr[Y-1][X-1] 였습니다. 이 아이디어를 2차원 dp 배열에 적용시켰습니다.*/ for(int i=1; i<=N; i++) { for(int j=1; j<=i; j++) { dp[i][j] = max(dp[i-1][j],dp[i-1][j-1]) + arr[i][j]; } } for(int i=1; i<=N; i++) if(dp[N][i] > Max) Max = dp[N][i]; cout << Max; return 0; } /* ================================================ FILE: BOJ/1932.정수 삼각형/sAp00n.py ================================================ from sys import stdin triang_list = [tuple(map(int, stdin.readline().split())) for _ in range(int(stdin.readline()))] DP = [[] for _ in range(len(triang_list))] DP[0].append(triang_list[0][0]) for num_of_line in range(1, len(triang_list)): for idx in range(len(triang_list[num_of_line])): compare_list = [] if idx == 0: compare_list.append(DP[num_of_line - 1][0]) elif idx == len(triang_list[num_of_line]) - 1: compare_list.append(DP[num_of_line - 1][-1]) else: compare_list += [DP[num_of_line - 1][idx - 1], DP[num_of_line - 1][idx]] DP[num_of_line].append(max(compare_list) + triang_list[num_of_line][idx]) print(max(DP[-1])) ================================================ FILE: BOJ/1937.욕심쟁이 판다/6047198844.py ================================================ import sys sys.setrecursionlimit(10**9) def dp(y, x): if memo[y][x] != -1: return memo[y][x] cnt = 0 for ny, nx in (y + 1, x), (y - 1, x), (y, x - 1), (y, x + 1): if 0 <= ny < N and 0 <= nx < N and board[y][x] < board[ny][nx]: cnt = max(cnt, dp(ny, nx)) memo[y][x] = cnt + 1 return memo[y][x] N = int(sys.stdin.readline()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] memo = [[-1] * N for _ in range(N)] res = -1 for y in range(N): for x in range(N): res = max(res, dp(y, x)) print(res) ================================================ FILE: BOJ/1940.주몽/6047198844.py ================================================ N = int(input()) M = int(input()) shields = map(int, input().split()) table = dict() res = 0 for shield in shields: if shield in table: res += 1 elif shield < M: table[M - shield] = True print(res) ================================================ FILE: BOJ/1942.디지털시계/6047198844.py ================================================ # 문제 # # 디지털시계는 일반적으로 시각을 “hh:mm:ss”의 형태로 표현한다. hh는 00 이상 23 이하의 값을, mm과 ss는 00 이상 59 이하의 값을 가질 수 있다. # 이러한 형태의 시각에서 콜론(“:”)을 제거하면 “hhmmss”라는 정수를 얻을 수 있는데, 이러한 정수를 시계 정수라고 한다. # 이 문제에서 시간이란 시각의 구간을 나타낸다. 예를 들어 [00:59:58, 01:01:24]와 같이 시작하는 시각과 끝나는 시각으로 이루어진 구간을 우리는 시간이라고 부른다. (이러한 구간에는 시작하는 시간과 끝나는 시간도 포함된다) # 시간이 시작하는 시각과 끝나는 시각으로 주어졌을 때, 이 구간에 포함되는 시계 정수들 중, 3의 배수인 것의 개수를 구하는 프로그램을 작성하시오. # # 입력 # 세 개의 입력이 주어진다. 첫째 줄부터 세 줄에 걸쳐 시작하는 시각과 끝나는 시각이 “hh:mm:ss”의 형태로 주어진다. 시작하는 시각과 끝나는 시각 사이에는 빈 칸이 하나 있어서, 한 줄마다 (빈 칸을 포함하여) 총 17글자가 입력으로 주어진다. 시작하는 시각과 끝나는 시각은 항상 다르다. # # 출력 # 첫째 줄부터 세 개의 줄에 걸쳐 입력된 구간에 포함되는 시계 정수들 중, 3의 배수인 것의 개수를 출력한다. 입력된 순서대로 각 줄에 한 개씩 차례로 출력하면 된다. import datetime time_range = [input().split() for _ in range(3)] FMT = '%H:%M:%S' for start_time, end_time in time_range: start_time, end_time = datetime.datetime.strptime(start_time, FMT), datetime.datetime.strptime(end_time, FMT) res = int((int(str(start_time.hour).zfill(2) + str(start_time.minute).zfill(2) + str(start_time.second).zfill(2))) % 3 == 0) while start_time.hour != end_time.hour or start_time.minute != end_time.minute or start_time.second != end_time.second: start_time = start_time + datetime.timedelta(seconds=1) if (int(str(start_time.hour).zfill(2) + str(start_time.minute).zfill(2) + str(start_time.second).zfill(2))) % 3 == 0: res += 1 print(res) ================================================ FILE: BOJ/1946.신입 사원/6047198844.py ================================================ import math import sys T = int(sys.stdin.readline()) for _ in range(T): N = int(sys.stdin.readline()) hired = [0] * (N+1) for _ in range(N): rank_i, rank_j = map(int, sys.stdin.readline().split()) hired[rank_i] = rank_j m = math.inf cnt = 0 for i in range(1, N+1): if m > hired[i]: m = hired[i] cnt += 1 print(cnt) ================================================ FILE: BOJ/1946.신입 사원/rockmiin.py ================================================ def solution(): t= int(input()) for _ in range(t): n= int(input()) score= [] for i in range(n): score.append(list(map(int, input().split()))) score.sort() cnt= 1 tmp= 0 for i in range(1, n): if score[tmp][1] > score[i][1]: tmp= i; cnt+=1 print(cnt) solution() ================================================ FILE: BOJ/19532.수학은 비대면강의입니다/6047198844.py ================================================ a, b, c, d, e, f = map(int, input().split()) for x in range(-999, 999 + 1): for y in range(-999, 999 + 1): if a*x + b*y == c and d*x + e*y == f: print(x, y) ================================================ FILE: BOJ/19583.싸이버개강총회/6047198844.py ================================================ # 문제 # 누가 개강총회에 왔는지 알 수 없다. # 누가 개강총회 자리에 끝까지 남아있었는지 알 수 없다. # 어떤 사람이 개강총회 스트리밍을 단순히 틀어놓기만 했는지 알 수 없다. # 이런 문제를 해결하기 위해서, 다음과 같이 출석부를 관리하기로 결심했다. # # 개강총회를 시작하기 전에, 학회원의 입장 확인 여부를 확인한다. 학회원의 입장 여부는 개강총회가 시작한 시간 이전에 대화를 한 적이 있는 학회원의 닉네임을 보고 체크한다. 개강총회를 시작하자마자 채팅 기록을 남긴 학회원도 제 시간에 입장이 확인된 것으로 간주한다. # 개강총회를 끝내고 나서, 스트리밍을 끝낼 때까지 학회원의 퇴장 확인 여부를 확인한다. # 학회원의 퇴장 여부는 개강총회가 끝나고 스트리밍이 끝날 때까지 대화를 한 적이 있는 학회원의 닉네임을 보고 체크한다. 개강총회가 끝나자마자 채팅 기록을 남겼거나, 개강총회 스트리밍이 끝나자마자 채팅 기록을 남긴 학회원도 제 시간에 퇴장이 확인된 것으로 간주한다. # 단, 00:00부터는 개강총회를 시작하기 전의 대기 시간이며, 개강총회 스트리밍 끝난 시간 이후로 남겨져 있는 채팅 기록은 다른 스트리밍 영상의 채팅 기록으로 간주한다. # # 이 때, 입장부터 퇴장까지 모두 확인된 학회원은 전부 몇 명인가? # # 입력 # 첫번째 줄에는 개강총회를 시작한 시간 S, 개강총회를 끝낸 시간 E, 개강총회 스트리밍을 끝낸 시간 Q가 주어진다. (00:00 ≤ S < E < Q ≤ 23:59) # 각 시간은 HH:MM의 형식으로 주어진다. # # 두번째 줄부터는 HI-ARC에서 방송하는 스트리밍 영상의 채팅 기록들이 시간순으로 주어지는데, (시간) (학회원 닉네임)의 형태로 주어진다. 학회원의 닉네임은 알파벳 대소문자와 숫자, 그리고 특수 기호(., _, -)로만 구성된 문자열이며 최대 20글자이다. # # 모든 채팅 기록은 개강총회가 일어난 날에 발생한 채팅 기록이다. 즉 00:00~23:59의 시간만 주어진다. 채팅 기록은 10만 줄을 넘지 않는다. # # 출력 # 출석이 확인된 학회원의 인원 수를 출력한다. import sys from datetime import time S, E, Q = map(lambda t : time(int(t[0]), int(t[1])), map(lambda t: t.split(':'), sys.stdin.readline().rstrip().split())) check_in = set() check_out = set() lines = sys.stdin.readlines() res = 0 for line in lines: hour, minute, nickname = line.replace(':', ' ').split() time_log = time(int(hour), int(minute)) if time_log <= S: check_in.add(nickname) elif E <= time_log <= Q: if nickname not in check_out and nickname in check_in: check_out.add(nickname) res += 1 print(res) ================================================ FILE: BOJ/1963.소수 경로/6047198844.py ================================================ import collections prime = set(range(2, 9999 + 1)) #에라스토테네스의 체 def sieve(): #2부터 9999까지의 소수를 prime에 저장한다. for num in range(2, 9999 + 1): #num이 소수이면 if num in prime: for not_prime_num in range(num*2, 9999 + 1, num): prime.discard(not_prime_num) #4자리수인지 판단하는 함수 def is_four_digits(num): return int(num) // 1000 #소수인지 판단하는 함수 def is_prime(num): return int(num) in prime def bfs(base, target): convert_cnt = 0 if base == target: return convert_cnt Q = collections.deque() visited = set() Q.append(base) visited.add(base) while Q: convert_cnt += 1 for _ in range(len(Q)): num = Q.popleft() for index in range(0,4): for nn in range(0,9+1): nnum = num[:index] + str(nn) + num[index+1:] if nnum == target: return convert_cnt if is_prime(nnum) and is_four_digits(nnum) and nnum not in visited: Q.append(nnum) visited.add(nnum) print('Impossible') T = int(input()) sieve() for _ in range(T): base, target = input().split() print(bfs(base, target)) ================================================ FILE: BOJ/1966.프린터 큐/6047198844.cpp ================================================ #include #include using namespace std; int main() { int T; cin >> T; while (T--) { int N, M; cin >> N >> M; priority_queue, less > pq; queue q; int cnt = 0; int _; for (int i = 0; i < N; i++) { cin >> _; pq.push(_); q.push(_); } while (!q.empty()) { if (pq.top() == q.front()) { ++cnt; pq.pop(); q.pop(); if (M == 0) { cout << cnt << "\n"; break; } else { M--; } } else { q.push(q.front()); q.pop(); if (M == 0) M = q.size() - 1; else M--; } } } } ================================================ FILE: BOJ/19698.헛간 청약/6047198844.py ================================================ import sys N, W, H, L = map(int, sys.stdin.readline().split()) print(min(N, (W // L) * (H // L))) ================================================ FILE: BOJ/1977.완전제곱수/6047198844.py ================================================ import sys def func(i): for j in range(1, i + 1): if i // j == j and i % j == 0: return True return False M = int(sys.stdin.readline()) N = int(sys.stdin.readline()) res_sum = 0 res_min = sys.maxsize for i in range(M,N + 1): if func(i): res_sum += i res_min = min(res_min, i) if res_sum == 0: print(-1) else: print(res_sum) print(res_min) ================================================ FILE: BOJ/1978.소수 찾기/6047198844.py ================================================ prime = [True] * 1001 # 소수이면 True def sieve(): prime[1] = False for n in range(2, 1001): if prime[n]: # n 가 소수인경우 for m in range(n + n, 1001, n): prime[m] = False sieve() T = int(input()) res = 0 for n in map(int, input().split()): if prime[n]: res += 1 print(res) ================================================ FILE: BOJ/19844.단어 개수 세기/6047198844.py ================================================ # qu'est-ce qu'il mange aujourd'hui # 먼저 띄어쓰기와 하이픈을 기준으로 “단어”로 분리해 준다: qu'est / ce / qu'il / mange / aujourd'hui. # 첫 번째 “단어”인 qu'est는 qu'로 시작하고 모음인 e로 이어지기 때문에 que와 est가 만나서 줄어든 것이다. 따라서 이 단어를 분리해 준다: que / est / ce / qu'il / mange / aujourd'hui. # 세 번째 “단어” 역시 마찬가지로 분리해 준다: que / est / ce / que / il / mange / aujourd'hui. # 마지막 “단어”는 어포스트로피가 있고 모음으로 취급되는 h로 이어지지만 앞 단어가 줄어들어 생긴 어포스트로피가 아니므로, 분리하지 않고 한 단어로 둔다. # 기본적으로는 띄어쓰기나 -(하이픈) 단위로 단어를 구분한다. # 앞 단어가 ce, je, ne, me, te, se, le, la, de, que 혹은 si이고 뒤 단어가 모음(a, e, i, o, u, h)으로 시작하는 경우, 앞 단어의 마지막 모음이 사라지고, 대신 '(어포스트로피)가 붙으면서 이어진다. # 프랑스어에서 h는 언제나 묵음이므로, 이 문제에서는 일반적으로 알려진 모음 a, e, i, o, u는 물론이고 h도 모음으로 취급함에 유의하라. # c', j', n', m', t', s', l', l', d', qu' # step1 import re sentence = ' '.join(' '.join(input().split()).split('-')) # step2 cnt = 0 for word in sentence.split(): cnt += 1 front_words = ["c'", "j'", "n'", "m'", "t'", "s'", "l'", "d'", "qu'"] back_word = "[aeiouh]+" for front_word in front_words: p = re.compile(front_word + back_word) if p.match(word): cnt += 1 print(cnt) ================================================ FILE: BOJ/1987.알파벳/6047198844.py ================================================ #y,x좌표에서 중복없이 갈수있는 최대의 수. from functools import lru_cache R, C = map(int, input().split()) board = [list(input())for _ in range(R)] path = set() def dfs(y, x): res = 1 path.add(board[y][x]) for dy, dx in (-1,0), (1,0), (0,-1), (0,1): ny = y + dy nx = x + dx if 0 <= ny < R and 0 <= nx < C and board[ny][nx] not in path: res = max(res, 1 + dfs(ny, nx)) path.remove(board[y][x]) return res print(dfs(0, 0)) ================================================ FILE: BOJ/1987.알파벳/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/1987 알파벳 [풀이] 1. BFS로 풀이 => 최대길이를 조사할 떄는 DFS보다 BFS가 더 유리하다고 한다 2. set으로 queue의 역할 3. 방문여부를 조사하면서 탐색 후 거리 세기 => 이 떄의 방문여부는 좌표가 아니라 문자 ''' import sys input = sys.stdin.readline h, w = map(int, input().strip().split()) board = [input().strip() for _ in range(h)] max_move = 1 q = set([(0, 0, board[0][0])]) while q: y, x, visited = q.pop() for dy, dx in [(0, -1), (0, 1), (-1, 0), (1, 0)]: ny, nx = y + dy, x + dx if 0 <= ny < h and 0 <= nx < w and board[ny][nx] not in visited: max_move = max(max_move, len(visited)+1) q.add((ny, nx, visited+board[ny][nx])) print(max_move) ================================================ FILE: BOJ/1990.소수인펠린드롬/6047198844.py ================================================ a, b = map(int, input().split()) b = min(10000000, b) # 소수이면 True is_prime = [True] * (int(b ** 0.5) + 1) divisors = [] # 정답의 범위는 a ~ 최대 10000000 이다. # 이들의 약수중 하나는 반드시 10000000 ** 0.5의 범위안에 들어온다. for i in range(2, int(b ** 0.5) + 1): if is_prime[i]: divisors.append(i) for j in range(i + i, int(b ** 0.5) + 1, i): is_prime[j] = False # 짝수는 고려하지 않는다. if a % 2 == 0: a += 1 for i in range(a, b + 1, 2): # 팰린드롬인가? 크기가 홀수 또는 11인가? if (i == 11 or len(str(i)) % 2 == 1) and str(i) == str(i)[::-1]: for divisor in divisors: if divisor < i and i % divisor == 0: break else: print(i) print(-1) ================================================ FILE: BOJ/19939.박 터트리기/6047198844.py ================================================ """ 1. N개의 공을 K개의 바구니에 빠짐없이 나누어 담는다. 2. 각 바구니에는 1개 이상의 공이 들어 있어야 한다. 3. 각 바구니에 담긴 공의 개수는 모두 달라야 한다. 4. 가장 많이 담긴 바구니와 가장 적게 담긴 바구니의 공의 개수 차이가 최소가 되어야 한다. N개의 공을 K개의 바구니에 나눠 담을 때, 나눠 담을 수 있는지 여부를 결정하고, 담을 수 있는 경우에는 가장 많이 담긴 바구니와 가장 적게 담긴 바구니의 공의 개수 차이를 계산해서 출력하시오. 최소값을 i라고 하자. 이상적인 상황은 i, i+1, i+2, i+3, i+(K-1) 일 것이다. (마지막값이 K-1이상의 값을 가지면된다.) i는 최소 배분가능한 개수이다. i는 N / K가 초기값이 될것이다. 1까지 감소한다. 감소 조건은 끝까지 분배가 안될경우 줄여나간다. --> 로직이 틀렸다 일단 1부터 K개를 배분한다. -> 공의 개수가 모두 다르게 표현된다. 남은 공들을 K개 부터 역순으로 배분한다 -> 1부터 배분할 경우 공의 개수가 같아 질수있다. => 배분이 똑같이 이루어진다면, 차이는 K-1일것이다. (나머지가 K의 배수인 경우, 0포함) => 배분이 균일하게 이루어지지 않는다면, 차이는 K일것이다. """ N, K = map(int, input().split()) min_portion = (1 + K) * K // 2 remain = N - min_portion if remain >= 0: if remain % K == 0: print(K - 1) else: print(K) else: print(-1) ================================================ FILE: BOJ/19942.다이어트/6047198844.py ================================================ # 문제 # 식재료 N개 중에서 몇 개를 선택해서 이들의 영양분(단백질, 탄수화물, 지방, 비타민)이 일정 이상이 되어야 한다. # 아래 표에 제시된 6가지의 식재료 중에서 몇 개를 선택해서 이들의 영양분의 각각 합이 최소 100, 70, 90, 10가 되도록 하는 경우를 생각해보자. # 이 경우 모든 재료를 선택하면 쉽게 해결되지만, 우리는 조건을 만족시키면서도 비용이 최소가 되는 선택을 하려고 한다. # # 재료 단백질 지방 탄수화물 비타민 가격 # 1 30 55 10 8 100 # 2 60 10 10 2 70 # 3 10 80 50 0 50 # 4 40 30 30 8 60 # 5 60 10 70 2 120 # 6 20 70 50 4 40 # 예를 들어, 식재료 1, 3, 5를 선택하면 영양분은 100, 145, 130, 10으로 조건을 만족하지만 가격은 270이 된다. # 대신 2, 3, 4를 선택하면 영양분의 합은 110, 130, 90, 10, 비용은 180이 되므로, 앞의 방법보다는 더 나은 선택이 된다. # # 입력으로 식재료 표가 주어졌을 때, 최저 영양소 기준을 만족하는 최소 비용의 식재료 집합을 찾아야 한다. # # 입력 # 첫 줄에 식재료의 개수 N이 주어진다. # 다음 줄에는 단백질, 지방, 탄수화물, 비타민의 최소 영양성분을 나타내는 정수 mp, mf, ms, mv가 주어진다. # # 이어지는 N개의 각 줄에는 i번째 식재료의 단백질, 지방, 탄수화물, 비타민과 가격이 5개의 정수 p_i, f_i, s_i, v_i, c_i와 같이 주어진다. 식재료의 번호는 1부터 시작한다. # # 출력 # 첫 번째 줄에 최소 비용을 출력하고, 두 번째 줄에 조건을 만족하는 최소 비용 식재료의 번호를 공백으로 구분해 오름차순으로 한 줄에 출력한다. 같은 비용의 집합이 하나 이상이면 사전 순으로 가장 빠른 것을 출력한다. # # 조건을 만족하는 답이 없다면 -1을 출력하고, 둘째 줄에 아무것도 출력하지 않는다. # # 제한 # 3 <= N <= 15 # 0 <= mp, mf, ms, mv <= 500 # mp + mf + ms + mv > 0 # 0 <= p_i, f_i, s_i, v_i, c_i <= 500 from itertools import combinations N = int(input()) needs = list(map(int, input().split())) nutrients = [list(map(int, input().split())) for _ in range(N)] res = -1 res_num = list() for C in range(1, N + 1): for indexes in combinations(range(0, N), C): picked = [nutrients[index] for index in indexes] for idx, nutrient in enumerate(list(zip(*picked))[:4]): ns = sum(list(nutrient)) if needs[idx] > ns: break else: cost = sum(list(zip(*picked))[4]) if res == -1 or res >= cost: if res > cost: res_num.clear() res = cost res_num.append(indexes) print(res) if res_num: for n in sorted(res_num)[0]: print(n+1, end=' ') ================================================ FILE: BOJ/19951.태상이의 훈련소 생활/6047198844.py ================================================ """ 문제 연병장은 일렬로 이어진 N개의 칸으로 이루어져 있으며 각 칸마다 높이를 가지고 있고, 첫 번째 칸부터 순서대로 1번, 2번, 3번, ..., N번 칸으로 명칭이 붙어있다. 조교들은 총 M명이 있으며, 각 조교들은 태상이에게 a번 칸부터 b번 칸까지 높이 k만큼 흙을 덮거나 파내라고 지시한다. 흙은 주변 산에서 얼마든지 구할 수 있으므로 절대로 부족하지 않다. 태상이는 각 조교의 지시를 각각 수행하면, 다른 조교의 지시로 흙을 덮어둔 칸을 다시 파내기도 하는 비효율적인 일이 발생하는 것을 깨달았다. 그래서 태상이는 각 조교의 지시를 모아 연병장 각 칸의 최종 높이를 미리 구해 한 번에 일을 수행하려고 한다. 불쌍한 태상이를 위해 조교들의 지시를 모두 수행한 뒤 연병장 각 칸의 높이를 구하자. 입력 첫 줄에 연병장의 크기 N과 조교의 수 M이 주어진다. 둘째 줄에 연병장 각 칸의 높이 Hi가 순서대로 N개 주어진다. 셋째 줄부터 M개의 줄에 각 조교의 지시가 주어진다. 각 조교의 지시는 세 개의 정수 a, b, k로 이루어져 있다. k ≥ 0인 경우 a번 칸부터 b번 칸까지 높이가 각각 |k| 만큼 늘어나도록 흙을 덮어야 한다. k < 0인 경우 a번 칸부터 b번 칸까지 높이가 각각 |k| 만큼 줄어들도록 흙을 파내야 한다. 초기 연병장의 상태: 1 2 3 4 5 -1 -2 -3 -4 -5 첫번째 지시 (1 5 -3)를 수행 한 뒤: -2 -1 0 1 2 -1 -2 -3 -4 -5 두번째 지시 (6 10 5)를 수행한 뒤: -2 -1 0 1 2 4 3 2 1 0 세번째 지시 (2 7 2)를 수행한 뒤: -2 1 2 3 4 6 5 2 1 0 (1 5 -3) (6 10 5) (1 1 -3) , (2 5 -1) , (6 7 7) (8 10 5) 교집합은 갱신. 이외는 갱신 X -> 하지만 범위를 다시 설정한다. 교집합 """ import sys N, M = map(int, sys.stdin.readline().rstrip().split()) H = list(map(int, sys.stdin.readline().rstrip().split())) variance = [0 for _ in range(N+1)] for _ in range(M): # a부터 시작해서 b까지 증가. 이를 증감량으로 표현하면. a에서 증가 +K , b+1 에서 -K로 표현가능하다. a, b, k = tuple(map(int, sys.stdin.readline().rstrip().split())) variance[a-1] += k variance[b] += -k for i in range(1, N+1): variance[i] += variance[i-1] H[i-1] += variance[i-1] print(' '.join(map(str, H))) ================================================ FILE: BOJ/20040.사이클 게임/6047198844.py ================================================ import sys sys.setrecursionlimit(10**7) def union(A, B): PA = find(A) PB = find(B) if PA == PB: return P[PB] = PA def find(A): if P[A] == -1: return A P[A] = find(P[A]) return P[A] n, m = map(int, sys.stdin.readline().split()) P = [-1 for _ in range(n)] for i in range(1, m+1): v, w = map(int, sys.stdin.readline().split()) pv = find(v) pw = find(w) if pv == pw: print(i) break union(v, w) else: print(0) ================================================ FILE: BOJ/20053.최소, 최대 2/6047198844.py ================================================ T = int(input()) for _ in range(T): N = int(input()) nums = list(map(int, input().split())) print(min(nums), max(nums)) ================================================ FILE: BOJ/2014.소수의 곱/6047198844.py ================================================ import heapq import sys from collections import deque K, N = map(int, sys.stdin.readline().split()) primes = list(map(int, sys.stdin.readline().split())) PQ = primes.copy() head = 0 for _ in range(N): head = heapq.heappop(PQ) for prime in primes: heapq.heappush(PQ, head * prime) if head % prime == 0: break print(head) ================================================ FILE: BOJ/20154.이 구역의 승자는 누구야?!/6047198844.py ================================================ table = dict() table['A'] = 3 table['B'] = 2 table['C'] = 1 table['D'] = 2 table['E'] = 3 table['F'] = 3 table['G'] = 3 table['H'] = 3 table['I'] = 1 table['J'] = 1 table['K'] = 3 table['L'] = 1 table['M'] = 3 table['N'] = 3 table['O'] = 1 table['P'] = 2 table['Q'] = 2 table['R'] = 2 table['S'] = 1 table['T'] = 2 table['U'] = 1 table['V'] = 1 table['W'] = 2 table['X'] = 2 table['Y'] = 2 table['Z'] = 1 nums = list(map(lambda char: table[char], list(input()))) while len(nums) > 1: tmp = list() for idx in range(1, len(nums), 2): tmp.append(nums[idx-1] + nums[idx]) if len(nums) % 2 == 1: tmp.append(nums[len(nums)-1]) nums = tmp print("I'm a winner!") if nums[0] % 2 == 1 else print("You're the winner?") ================================================ FILE: BOJ/2018.수들의 합 5/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) cur = 0 small = 1 res = 0 for i in range(1, N + 1): cur += i # 현재값이 클 경우. small 값을 빼준다. small 은 1씩 증가한다. while cur > N: cur -= small small += 1 # 같으면 종류를 추가한다. if cur == N: res += 1 print(res) ================================================ FILE: BOJ/2023.신기한 소수/6047198844.py ================================================ import sys def is_prime(i): if i < 2: return False for j in range(2, i): if i % j == 0: return False return True def dfs(i, cnt): if cnt == N: print(i) return for p in range(1, 10, 2): if is_prime(i * 10 + p): dfs(i * 10 + p, cnt + 1) N = int(sys.stdin.readline()) for i in 2,3,5,7: dfs(i, 1) ================================================ FILE: BOJ/2042.구간 합 구하기/6047198844.cpp ================================================ #include #include #define LL long long using namespace std; //https://www.acmicpc.net/board/view/38941 void change(int changed_idx, LL changing_num, vector& temp,vector &idx_tree) { LL dif = changing_num - temp[changed_idx]; temp[changed_idx] = changing_num; int N = idx_tree.size() - 1; while (changed_idx <= N) { idx_tree[changed_idx] += dif; changed_idx += (changed_idx & -changed_idx); } return; } LL sum(int idx, vector& idx_tree) { LL res = 0; while (idx) { res += idx_tree[idx]; idx -= idx & (-idx); } return res; } LL prefix_sum(int from_idx, int to_idx, vector& idx_tree) { return sum(to_idx,idx_tree) - sum(from_idx - 1,idx_tree); } int main() { int N, M, K; cin >> N >> M >> K; vector temp(N + 1); for (int i = 1; i <= N; i++) cin >> temp[i]; vector idx_tree(N + 1); for (int i = 1; i <= N; i++) for (int j = i - (i & -i) + 1; j <= i; j++) idx_tree[i] += temp[j]; int C = M + K; LL a, b, c; while (C--) { cin >> a >> b >> c; if (a == 1) change(b, c, temp, idx_tree); else cout << prefix_sum(b, c, idx_tree) << "\n"; } } ================================================ FILE: BOJ/20436.ZOAC 3/6047198844.py ================================================ left_hand = {'q', 'w', 'e', 'r', 't', 'a', 's', 'd', 'f', 'g', 'z', 'x', 'c', 'v'} right_hand = {'y','u','i','o','p','h','j','k','l','b','n','m'} table = dict(tuple()) table['q'] = (0, 0) table['w'] = (0, 1) table['e'] = (0, 2) table['r'] = (0, 3) table['t'] = (0, 4) table['y'] = (0, 5) table['u'] = (0, 6) table['i'] = (0, 7) table['o'] = (0, 8) table['p'] = (0, 9) table['a'] = (1, 0) table['s'] = (1, 1) table['d'] = (1, 2) table['f'] = (1, 3) table['g'] = (1, 4) table['h'] = (1, 5) table['j'] = (1, 6) table['k'] = (1, 7) table['l'] = (1, 8) table['z'] = (2, 0) table['x'] = (2, 1) table['c'] = (2, 2) table['v'] = (2, 3) table['b'] = (2, 4) table['n'] = (2, 5) table['m'] = (2, 6) l, r = input().split() res = 0 l_position, r_position = table[l], table[r] for char in input(): x1, y1 = table[char] if char in left_hand: x2, y2 = l_position l_position = table[char] else: x2, y2 = r_position r_position = table[char] res += 1 + abs(x1-x2) + abs(y1-y2) print(res) ================================================ FILE: BOJ/20499.Darius님 한타 안함?/6047198844.py ================================================ import sys K, D, A = map(int, sys.stdin.readline().split('/')) if (K + A < D) or D == 0: print('hasu') else: print('gosu') ================================================ FILE: BOJ/20546.🐜 기적의 매매법 🐜/6047198844.py ================================================ # 문제 # # 2099년이 되어도 주식을 팔지 않을 것이다. # 준현이는 주식을 살 수 있다면 무조건 최대한 많이 산다. # 준현이는 욕심쟁이이기 때문에, 주식을 살 수 있다면 가능한 만큼 즉시 매수한다. 다음은 준현이가 현금 100원으로 A기업의 주식을 사는 경우이다. # # 1일 2일 3일 4일 5일 6일 7일 # 현금 100 20 20 6 0 0 0 # 주가 40 33 7 2 1 12 50 # 매수 가능 주식 수 2 0 2 3 0 0 0 # 매수여부 O X O O X X X # 남은 현금 20 20 6 0 0 0 0 # 보유 주식 수 2 2 4 7 7 7 7 # "주식은 타이밍이지!" # # 모니터 8개에서 뿜어져 나오는 화려한 주식 차트가 성민이를 감싼다. # 성민이는 주식이 타이밍 싸움이라 생각한다. 전형적인 단기 투자자로 생각하면 오산이다. # 이른바 33 매매법으로, 그 방법은 다음의 세 가지 룰로 이루어져있다. # # 모든 거래는 전량 매수와 전량 매도로 이루어진다. 현재 가지고 있는 현금이 100원이고 주가가 11원이라면 99원어치의 주식을 매수하는 것이다. 단, 현금이 100원 있고 주가가 101원이라면 주식을 살 수 없다. 성민이는 빚을 내서 주식을 하지는 않는다. # 3일 연속 가격이 전일 대비 상승하는 주식은 다음날 무조건 가격이 하락한다고 가정한다. 따라서 현재 소유한 주식의 가격이 3일째 상승한다면, 전량 매도한다. 전일과 오늘의 주가가 동일하다면 가격이 상승한 것이 아니다. # 3일 연속 가격이 전일 대비 하락하는 주식은 다음날 무조건 가격이 상승한다고 가정한다. 따라서 이러한 경향이 나타나면 즉시 주식을 전량 매수한다. 전일과 오늘의 주가가 동일하다면 가격이 하락한 것이 아니다. # 준현이와 성민이는 각자의 매매법 중 어떤 방법이 더 수익률이 높은지 겨뤄보기로 했다. # 오로지 MachineDuck이라는 기업의 주식만 거래가 가능하며, 내기 기간은 2021년 1월 1일부터 2021년 1월 14일까지이다. 준현이와 성민이에게 주어진 현금은 동일하다. 세기의 대결이기 때문에 이 기간에는 매일 주식 거래가 가능하다. 2021년 1월 14일에 더 많은 자산을 보유한 사람이 승리한다. 1월 14일의 자산은 (현금 + 1월 14일의 주가 × 주식 수)로 계산한다. # # 우리는 2021년 1월 1일부터 2021년 1월 14일까지의 주식 가격을 미리 알고 있다. 준현이와 성민이 중 누가 더 높은 수익률을 낼지 맞혀보자! # # 입력 # 첫 번째 줄에 준현이와 성민이에게 주어진 현금이 주어진다. # # 두 번째 줄에 2021년 1월 1일부터 2021년 1월 14일까지의 MachineDuck 주가가 공백을 두고 차례대로 주어진다. 모든 입력은 1000 이하의 양의 정수이다. # # 출력 # 1월 14일 기준 준현이의 자산이 더 크다면 "BNP"를, 성민이의 자산이 더 크다면 "TIMING"을 출력한다. # # 둘의 자산이 같다면 "SAMESAME"을 출력한다. 모든 결과 따옴표를 제외하고 출력한다. jun_money = sung_money = int(input()) jun_stock = sung_stock = 0 MachineDucks = list(map(int, input().split())) # 준현이 for MachineDuck in MachineDucks: quantity = jun_money // MachineDuck jun_money -= quantity * MachineDuck jun_stock += quantity # 성민이 for idx, MachineDuck in enumerate(MachineDucks): if idx >= 3: # 매도시점 if MachineDucks[idx - 3] < MachineDucks[idx - 2] < MachineDucks[idx - 1] < MachineDucks[idx]: sung_money += MachineDucks[idx] * sung_stock sung_stock = 0 # 매수시점 if MachineDucks[idx - 3] > MachineDucks[idx - 2] > MachineDucks[idx - 1] > MachineDucks[idx]: quantity = sung_money // MachineDuck sung_money -= quantity * MachineDuck sung_stock += quantity jun_res = jun_money + MachineDucks[13] * jun_stock sung_res = sung_money + MachineDucks[13] * sung_stock print("SAMESAME") if jun_res == sung_res else print("BNP") if jun_res > sung_res else print("TIMING") ================================================ FILE: BOJ/20551.Sort 마스터 배지훈의 후계자/6047198844.py ================================================ # 1 <= N <= 2*10^5 # 1 <= M <= 2-10^5 import sys N, M = map(int, input().split()) A = list() for _ in range(N): A.append(int(sys.stdin.readline())) A.sort() for _ in range(M): question = int(sys.stdin.readline()) begin = 0 end = N while begin < end: mid = (begin + end) // 2 if A[mid] >= question: end = mid else: begin = mid + 1 if 0 <= begin < N and A[begin] == question: print(begin) else: print(-1) ================================================ FILE: BOJ/20944.팰린드롬 척화비/6047198844.py ================================================ N = int(input()) if N % 2 == 0: print('a'*N) else: print('a'*(N//2) + 'b' + 'a'*(N//2)) ================================================ FILE: BOJ/2096.내려가기/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) max_num_list = [0, 0, 0] min_num_list = [0, 0, 0] for _ in range(N): i, j, k = map(int, sys.stdin.readline().split()) max_num_list[0], max_num_list[1], max_num_list[2] = max(max_num_list[0] + i, max_num_list[1] + i), max( max_num_list[0] + j, max_num_list[1] + j, max_num_list[2] + j), max(max_num_list[1] + k, max_num_list[2] + k) min_num_list[0], min_num_list[1], min_num_list[2] = min(min_num_list[0] + i, min_num_list[1] + i), min( min_num_list[0] + j, min_num_list[1] + j, min_num_list[2] + j), min(min_num_list[1] + k, min_num_list[2] + k) print(max(max_num_list), min(min_num_list)) ================================================ FILE: BOJ/2098.외판원 순회/6047198844.py ================================================ import math import sys from collections import defaultdict ''' 2 ≤ N ≤ 16 DP + 비트마스킹 사이클이므로 어디서 시작하든 결과는 같다. 0번째 부터 시작한다. TCP(visited, current) = visited 가 전부 가득 찼을 경우 -> 기저사례 current -> 원점이 불가한 경우 무한대 아닌 경우 간선 크기 반환 가득 차지 않은 경우 -> min(TCP(visited U {k}, k) + edge[current][k]), k 는 visited의 여집합) visited 는 비트마스킹으로 처리한다. 집합을 표현하기 편함. ''' N = int(sys.stdin.readline()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] memo = [[-1 for _ in range(1 << N)] for _ in range(N)] def TSP(current, visited): # 모두 방문 한 경우 if visited == (1 << N) - 1: if board[current][0] == 0: return math.inf else: return board[current][0] # 메모가 있는 경우 if memo[current][visited] != -1: return memo[current][visited] res = math.inf # 모두 방문되지 않은 경우. 여집합을 방문한다. for k in range(N): if (visited & (1 << k)) != 0: continue if board[current][k] == 0: continue res = min(res, TSP(k, visited | (1 << k)) + board[current][k]) memo[current][visited] = res return memo[current][visited] print(TSP(0, 0 | (1 << 0))) ================================================ FILE: BOJ/2104.부분배열/sAp00n.py ================================================ from sys import stdin def sub_list(input_list): if len(input_list) == 0: return 0 if len(input_list) == 1: return input_list[0] * input_list[0] mid_idx = len(input_list) // 2 sub_max = max(sub_list(input_list[:mid_idx]), sub_list(input_list[mid_idx:])) start, end = mid_idx, mid_idx mid_max = input_list[start] * input_list[start] min_val = input_list[start] sum_of_list = input_list[start] while 0 < start or end < len(input_list) - 1: if start > 0: if end == len(input_list) - 1 or input_list[start - 1] >= input_list[end + 1]: start -= 1 min_val = min(min_val, input_list[start]) sum_of_list += input_list[start] mid_max = max(mid_max, sum_of_list * min_val) continue end += 1 min_val = min(min_val, input_list[end]) sum_of_list += input_list[end] mid_max = max(mid_max, sum_of_list * min_val) return max(sub_max, mid_max) N = int(stdin.readline()) input_list = list(map(int, stdin.readline().split())) print(sub_list(input_list)) ================================================ FILE: BOJ/2108.통계학/6047198844.cpp ================================================ #include #include #include #include using namespace std; int main() { int N; cin >> N; vector arr(N); map fr_mp; double average = 0; int sum = 0; int center = 0; //최빈값의 빈도횟수 int frequency = 0; //최빈값 int frequency_value = 0; int range = 0; for (int i = 0; i < N; i++) { cin >> arr[i]; sum += arr[i]; fr_mp[arr[i]]++; if (frequency < fr_mp[arr[i]]) frequency = fr_mp[arr[i]]; } sort(arr.begin(), arr.end()); //average = sum<0 ? ((sum * 10) / N - 5) / 10 : ((sum * 10) / N + 5) / 10; average = sum / double(N); center = arr[N / 2]; vector fr_vt; for (map::iterator it=fr_mp.begin(); it != fr_mp.end(); it++) { if (it->second == frequency) fr_vt.push_back(it->first); } sort(fr_vt.begin(), fr_vt.end()); if (fr_vt.size() == 1) frequency_value = fr_vt[0]; else frequency_value = fr_vt[1]; range = arr[N - 1] - arr[0]; printf("%.0f\n", average); cout << center << "\n" << frequency_value << "\n" << range; } ================================================ FILE: BOJ/2110 공유기 설치/rockmiin.py ================================================ n, c= map(int, input().split()) home= [int(input()) for _ in range(n)] home.sort() start, end= 1, home[-1]- home[0] result= 0 while start <= end: mid= (start+ end)// 2 val= home[0] cnt= 1 for i in range(1, len(home)): if home[i] >= val+ mid: cnt+=1 val= home[i] if cnt >= c: result= mid start= mid+ 1 else: end= mid -1 print(result) ================================================ FILE: BOJ/2110.공유기 설치/6047198844.cpp ================================================ #include #include #include using namespace std; int main() { int N, C; cin >> N >> C; vector arr(N); for (int i = 0; i < N; i++) cin >> arr[i]; sort(arr.begin(), arr.end()); //간격에 대해서 이분 탐색 int begin = 1; int end = arr[N - 1] - arr[0] + 1; while (begin + 1 < end) { int mid = (begin + end) / 2; int tmp = arr[0]; int res = 1; while (1) { vector::iterator it = lower_bound(arr.begin(), arr.end(), tmp + mid); if (it == arr.end()) break; else res++; tmp = *it; } if (res < C) { end = mid; } else { begin = mid; } } cout << begin; } ================================================ FILE: BOJ/21312.홀짝 칵테일/6047198844.py ================================================ # 문제 # 음료들은 정수로 표현되는 고유 번호를 가지고 있다. 정진이는 이 음료들을 섞어 만든 칵테일을 만든다. # 홀짝 칵테일은 칵테일에 들어가는 음료들의 고유 번호의 곱에 해당하는 맛을 가진다. # # 맛이 홀수인 칵테일이 맛이 짝수인 칵테일보다는 무조건 맛있다고 느낀다. # 또한, 똑같이 홀수이거나 짝수인 맛을 가진 칵테일끼리는 맛이 더 큰 칵테일을 더 맛있다고 느낀다. # # 음료 셋의 고유 번호가 주어졌을 때 정진이가 이 음료들을 조합해 만들 수 있는 칵테일 중 가장 맛있다고 느끼는 칵테일의 맛을 알려주자. # 칵테일을 만들 때는, 반드시 모든 음료를 사용할 필요는 없지만, 적어도 하나의 음료는 사용해야 한다. 하나의 음료만 사용하는 경우 칵테일의 맛은 사용한 음료의 고유 번호와 같다. # 또한, 주어지는 세 음료는 서로 다른 고유 번호를 가지고 있다. # # 입력 # 첫째 줄에는 주어진 세 음료의 고유번호 A, B, C가 주어진다. # # 출력 # 첫째 줄에 만들 수 있는 홀짝 칵테일 중 가장 정진이가 맛있다고 느끼는 홀짝 칵테일의 맛을 출력한다. A, B, C = map(int, input().split()) drinks = [A, B, C, A * B, A * C, B * C, A * B * C] res = 0 for drink in drinks: # res가 짝수, drink 홀수면 교체, 아니면 크면 교체 if res % 2 == 0 and (drink % 2 == 1 or res < drink): res = drink # res가 홀수, drink가 홀수이면서 크면 교체 elif drink % 2 == 1 and res < drink: res = drink print(res) ================================================ FILE: BOJ/21313.문어/6047198844.py ================================================ N = int(input()) octopuses = [[True for _ in range(8)] for _ in range(N)] res = [] for idx, cur_octopus in enumerate(octopuses): # 다음 문어가 존재하는지 next_octopus = octopuses[(idx + 1) % N] for leg in range(8): if cur_octopus[leg] and next_octopus[leg]: cur_octopus[leg] = next_octopus[leg] = False res.append(leg+1) break for leg in res: print(leg, end=' ') ================================================ FILE: BOJ/2143.두 배열의 합/6047198844.py ================================================ import math import sys from collections import Counter, defaultdict def arr_sum(acc, arr, dictionary, limit): for i in range(limit): for j in range(i, limit): if i == j: acc[i][j] = arr[i] else: acc[i][j] = acc[i][j - 1] + arr[j] dictionary[acc[i][j]] += 1 T = int(sys.stdin.readline()) n = int(sys.stdin.readline()) A_arr = list(map(int, sys.stdin.readline().split())) m = int(sys.stdin.readline()) B_arr = list(map(int, sys.stdin.readline().split())) A_acc = [[math.inf for _ in range(n)] for _ in range(n)] B_acc = [[math.inf for _ in range(m)] for _ in range(m)] A_dict = defaultdict(int) B_dict = defaultdict(int) arr_sum(A_acc, A_arr, A_dict, n) arr_sum(B_acc, B_arr, B_dict, m) res = 0 for i in A_dict: if T - i in B_dict: res += A_dict.get(i) * B_dict.get(T - i) print(res) ================================================ FILE: BOJ/2156.포도주 시식/rockmiin.py ================================================ n= int(input()) wine=[0] dp=[0 for _ in range((n+1))] for i in range(n): wine.append(int(input())) # print(wine) for i in range(1, n+1): if i<3: dp[i]= sum(wine[:i+1]); continue dp[i]= max(dp[i-1], dp[i-2]+ wine[i], dp[i-3]+ wine[i-1]+ wine[i]) print(dp[-1]) ================================================ FILE: BOJ/2160.그림 비교/6047198844.py ================================================ # 문제 # N(2 ≤ N ≤ 50)개의 그림이 있다. 각각의 그림은 5×7의 크기이고, 두 가지 색으로 되어 있다. # 이때 두 가지의 색을 각각 ‘X’와 ‘.’으로 표현하기로 하자. # 이러한 그림들이 주어졌을 때, 가장 비슷한 두 개의 그림을 찾아내는 프로그램을 작성하시오. # 두 개의 그림에서 다른 칸의 개수가 가장 적을 때, 두 개의 그림이 가장 비슷하다고 하자. # # 입력 # 첫째 줄에 N이 주어진다. 다음 5×N개의 줄에 7개의 문자로 각각의 그림이 주어진다. # # 출력 # 첫째 줄에 가장 비슷한 두 그림의 번호를 출력한다. 그림의 번호는 입력되는 순서대로 1, 2, …, N이다. 번호를 출력할 때에는 작은 것을 먼저 출력한다. 입력은 항상 답이 한 가지인 경우만 주어진다. # N 입력 import sys from itertools import combinations N = int(sys.stdin.readline()) pictures = list() # 그림 입력 for i in range(N): picture = list() for j in range(5): picture.append(sys.stdin.readline().rstrip()) pictures.append(picture) res_dif = 36 res_combination = tuple() # 조합 차이 계산 def picture_dif(i, j): picture_a, picture_b = pictures[i], pictures[j] diff = 0 for y in range(5): for x in range(7): diff += int(picture_a[y][x] != picture_b[y][x]) return diff # 조합 for i, j in combinations(range(N), 2): # 둘의 차이 계산 dif = picture_dif(i, j) if res_dif > dif: res_combination = (i+1, j+1) res_dif = dif print(res_combination[0], res_combination[1]) ================================================ FILE: BOJ/2161.카드1/6047198844.py ================================================ from collections import deque N = int(input()) arr = deque(list(range(1, N+1))) while arr: print(arr.popleft(), end=' ') if arr: t = arr.popleft() arr.append(t) ================================================ FILE: BOJ/21610.마법사 상어와 비바라기/6047198844.py ================================================ # 문제 # 오늘 새로 배운 마법은 비바라기이다. 비바라기를 시전하면 하늘에 비구름을 만들 수 있다. # 오늘은 비바라기를 크기가 N×N인 격자에서 연습하려고 한다. 격자의 각 칸에는 바구니가 하나 있고, 바구니는 칸 전체를 차지한다. # 바구니에 저장할 수 있는 물의 양에는 제한이 없다. (r, c)는 격자의 r행 c열에 있는 바구니를 의미하고, A[r][c]는 (r, c)에 있는 바구니에 저장되어 있는 물의 양을 의미한다. # # 격자의 가장 왼쪽 윗 칸은 (1, 1)이고, 가장 오른쪽 아랫 칸은 (N, N)이다. # N번 행의 아래에는 1번 행이, 1번 행의 위에는 N번 행이 있고, 1번 열의 왼쪽에는 N번 열이, N번 열의 오른쪽에는 1번 열이 있다. # # 비바라기를 시전하면 (N, 1), (N, 2), (N-1, 1), (N-1, 2)에 비구름이 생긴다. 구름은 칸 전체를 차지한다. 이제 구름에 이동을 M번 명령하려고 한다. # i번째 이동 명령은 방향 di과 거리 si로 이루어져 있다. 방향은 총 8개의 방향이 있으며, 8개의 정수로 표현한다. 1부터 순서대로 ←, ↖, ↑, ↗, →, ↘, ↓, ↙ 이다. 이동을 명령하면 다음이 순서대로 진행된다. # # 모든 구름이 di 방향으로 si칸 이동한다. # 각 구름에서 비가 내려 구름이 있는 칸의 바구니에 저장된 물의 양이 1 증가한다. # 구름이 모두 사라진다. # 2에서 물이 증가한 칸 (r, c)에 물복사버그 마법을 시전한다. 물복사버그 마법을 사용하면, 대각선 방향으로 거리가 1인 칸에 물이 있는 바구니의 수만큼 (r, c)에 있는 바구니의 물이 양이 증가한다. # 이때는 이동과 다르게 경계를 넘어가는 칸은 대각선 방향으로 거리가 1인 칸이 아니다. # 예를 들어, (N, 2)에서 인접한 대각선 칸은 (N-1, 1), (N-1, 3)이고, (N, N)에서 인접한 대각선 칸은 (N-1, N-1)뿐이다. # 바구니에 저장된 물의 양이 2 이상인 모든 칸에 구름이 생기고, 물의 양이 2 줄어든다. 이때 구름이 생기는 칸은 3에서 구름이 사라진 칸이 아니어야 한다. # M번의 이동이 모두 끝난 후 바구니에 들어있는 물의 양의 합을 구해보자. # # 입력 # 첫째 줄에 N, M이 주어진다. # # 둘째 줄부터 N개의 줄에는 N개의 정수가 주어진다. r번째 행의 c번째 정수는 A[r][c]를 의미한다. # # 다음 M개의 줄에는 이동의 정보 di, si가 순서대로 한 줄에 하나씩 주어진다. # # 출력 # 첫째 줄에 M번의 이동이 모두 끝난 후 바구니에 들어있는 물의 양의 합을 출력한다. import sys from collections import deque N, M = map(int, sys.stdin.readline().split()) board = [] for i in range(N): board.append(list(map(int, sys.stdin.readline().split()))) clouds = [(N - 1, 0), (N - 1, 1), (N - 2, 0), (N - 2, 1)] d = [(0, 0), (0, -1), (-1, -1), (-1, 0), (-1, +1), (0, +1), (+1, +1), (+1, 0), (+1, -1)] for _ in range(M): di, si = map(int, sys.stdin.readline().split()) # 구름이 이동한다. for i in range(len(clouds)): clouds[i] = ((clouds[i][0] + d[di][0] * si) % N, (clouds[i][1] + d[di][1] * si) % N) # 이동한 구름에 비가 내린다. for my, mx in clouds: board[my][mx] += 1 # 구름이 모두 사라진다. # 물이 증가한 칸에 물복사를 한다. for my, mx in clouds: for dy, dx in (-1, -1), (-1, +1), (+1, -1), (+1, +1): ny, nx = my + dy, mx + dx # 대각선 방향으로 거리가 1인 칸에 물이 있는 바구니의 수만큼 (r, c)에 있는 바구니의 물이 양이 증가한다. if 0 <= ny < N and 0 <= nx < N and board[ny][nx] >= 1: board[my][mx] += 1 new_clouds = [] # 바구니에 저장된 물의 양이 2 이상인 모든 칸에 구름이 생기고, 물의 양이 2 줄어든다. for y in range(N): for x in range(N): if board[y][x] >= 2 and (y, x) not in clouds: board[y][x] -= 2 new_clouds.append((y, x)) clouds = new_clouds print(sum([sum(board[i]) for i in range(N)])) ================================================ FILE: BOJ/2164.카드2/6047198844.cpp ================================================ #include #include using namespace std; int main() { int N; cin >> N; queue q; for (int i = 1; i <= N; i++) { q.push(i); } while (q.size() != 1) { q.pop(); q.push(q.front()); q.pop(); } cout << q.front(); } ================================================ FILE: BOJ/2164.카드2/6047198844.py ================================================ from collections import deque N = int(input()) cards = deque(range(1, N+1)) while len(cards) > 1: cards.popleft() cards.rotate(-1) print(cards.pop()) ================================================ FILE: BOJ/2167.2차원 배열의 합/6047198844.py ================================================ # 문제 # 2차원 배열이 주어졌을 때 (i, j) 위치부터 (x, y) 위치까지에 저장되어 있는 수들의 합을 구하는 프로그램을 작성하시오. 배열의 (i, j) 위치는 i행 j열을 나타낸다. # # 입력 # 첫째 줄에 배열의 크기 N, M(1 ≤ N, M ≤ 300)이 주어진다. 다음 N개의 줄에는 M개의 정수로 배열이 주어진다. # 배열에 포함되어 있는 수는 절댓값이 10,000보다 작거나 같은 정수이다. 그 다음 줄에는 합을 구할 부분의 개수 K(1 ≤ K ≤ 10,000)가 주어진다. # 다음 K개의 줄에는 네 개의 정수로 i, j, x, y가 주어진다(1 ≤ i ≤ x ≤ N, 1 ≤ j ≤ y ≤ M). # # 출력 # K개의 줄에 순서대로 배열의 합을 출력한다. 배열의 합은 2^31-1보다 작거나 같다. import sys N, M = map(int, input().split()) arr = [[0 for _ in range(M + 1)]] + [[0] + list(map(int, sys.stdin.readline().split())) for _ in range(N)] # 부분합을 memo에 저장한다. # memo[y][x] 를 (0, 0) ~ (y, x) 이라고 하자. memo = [[0 for _ in range(M + 1)] for _ in range(N + 1)] for y in range(1, N + 1): for x in range(1, M + 1): memo[y][x] = memo[y-1][x] + memo[y][x-1] - memo[y-1][x-1] + arr[y][x] K = int(input()) for _ in range(K): i, j, y, x = map(int, input().split()) print(memo[y][x] - memo[i-1][x] - memo[y][j-1] + memo[i-1][j-1]) ================================================ FILE: BOJ/2170.선 긋기/6047198844.py ================================================ import math import sys N = int(sys.stdin.readline()) lines = [tuple(map(int, sys.stdin.readline().split())) for _ in range(N)] lines.sort() res = 0 left = -1000000001 right = -1000000001 for line in lines: begin, end = line # 이전과 이을수없는 경우. if right < begin: # 이전의 거리를 계산한다. res += right - left # 새로운 선으로 교체한다. left, right = begin, end # 이전과 이을수있는 경우 else: right = max(right, end) print(res + right - left) ================================================ FILE: BOJ/2174.로봇 시뮬레이션/6047198844.py ================================================ import sys # 5, 4 X, Y = map(lambda i: int(i) - 1, sys.stdin.readline().split()) N, M = map(int, sys.stdin.readline().split()) robots = [] for _ in range(N): x, y, d = sys.stdin.readline().split() robots.append((Y - int(y) + 1, int(x) - 1, d)) for _ in range(M): robot_idx, command, repeat = sys.stdin.readline().split() robot = robots[int(robot_idx) - 1] for _ in range(int(repeat)): if command == 'F': if robot[2] == 'N': robot = (robot[0] - 1, robot[1], 'N') elif robot[2] == 'W': robot = (robot[0], robot[1] - 1, 'W') elif robot[2] == 'E': robot = (robot[0], robot[1] + 1, 'E') elif robot[2] == 'S': robot = (robot[0] + 1, robot[1], 'S') elif command == 'L': if robot[2] == 'N': robot = (robot[0], robot[1], 'W') elif robot[2] == 'W': robot = (robot[0], robot[1], 'S') elif robot[2] == 'E': robot = (robot[0], robot[1], 'N') elif robot[2] == 'S': robot = (robot[0], robot[1], 'E') elif command == 'R': if robot[2] == 'N': robot = (robot[0], robot[1], 'E') elif robot[2] == 'W': robot = (robot[0], robot[1], 'N') elif robot[2] == 'E': robot = (robot[0], robot[1], 'S') elif robot[2] == 'S': robot = (robot[0], robot[1], 'W') y, x, pos = robot # 벽 위치 if y < 0 or y > Y or x < 0 or x > X: print(f"Robot {robot_idx} crashes into the wall") exit() for i in range(len(robots)): if i != int(robot_idx) - 1: y, x, pos = robot if y == robots[i][0] and x == robots[i][1]: print(f"Robot {robot_idx} crashes into robot {i+1}") exit() robots[int(robot_idx) - 1] = robot print('OK') ================================================ FILE: BOJ/21756.지우개/6047198844.py ================================================ N = int(input()) arr = list(range(1, N + 1)) while len(arr) > 1: for idx in range(0, len(arr) // 2 + len(arr) % 2): del arr[idx] print(arr[0]) ================================================ FILE: BOJ/2178.미로 탐색/rockmiin.py ================================================ from collections import deque def bfs(v): q= deque([v]) visited[0][0]= 1 # 초기 값 설정 while q: x, y= q.popleft() # print(q) if x==n-1 and y==m-1: return visited[x][y] # n, m의 위치에 도달했을 때 return for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: # 상하좌우 이동 tmp_x, tmp_y= x+dx, y+dy if 0<=tmp_x #include #include using namespace std; int main() { int N; cin >> N; vector vt(N); for (int i = 0; i < N; i++) cin >> vt[i]; sort(vt.begin(), vt.end()); int size = vt.size(); int res_max = 0; for (int i = 0; i < N; i++) res_max = max(res_max,vt[i] * (size - i)); cout << res_max; } ================================================ FILE: BOJ/2217.로프/6047198844.py ================================================ N = int(input()) ropes = list() for _ in range(N): ropes.append(int(input())) ropes.sort(reverse=True) print(max([(idx + 1) * rope for idx, rope in enumerate(ropes)])) ================================================ FILE: BOJ/2217.로프/rockmiin.py ================================================ n= int(input()) row=sorted([int(input()) for i in range(n)]) max_weight= 0 for i in range(n): if row[i]*(n-i) > max_weight: max_weight= row[i]*(n-i) print(max_weight) # 입력받은 row를 무게 기준으로 정렬을 한 뒤에 비교 (row를 전부 쓸 필요가 없기 때문에 row를 일부만 사용하는 경우 고려) # 예제 입력 # 2 # 10 # 15 # # 예제 출력 # 20 ================================================ FILE: BOJ/2231.분해합/6047198844.cpp ================================================ #include using namespace std; int brute_force(int N){ for(int i = 1; i <= 1000000; i++){ int res = i; int temp = i; while(temp){ res += temp % 10; temp /= 10; } if(res==N) return i; } return 0; } int main() { int N; cin >> N; cout << brute_force(N); return 0; } ================================================ FILE: BOJ/2239.스도쿠/6047198844.py ================================================ # 개요 # 스도쿠 풀기 import sys board = [list(map(int, list(sys.stdin.readline().rstrip()))) for _ in range(9)] # area (y // 3) * 3 + x // 3 area = [set() for _ in range(9)] row = [set() for _ in range(9)] column = [set() for _ in range(9)] # 초기화 for y in range(9): for x in range(9): if board[y][x] != 0: row[y].add(board[y][x]) column[x].add(board[y][x]) area[(y // 3) * 3 + x // 3].add(board[y][x]) # 현재 위치가 y, x 때 경우의 수를 다 놓는 함수. def func(y, x): # 예외: x가 범위를 벗어 났을때. y로 옮겨서 탐색 지속 if x == 9: return func(y + 1, 0) # base case: y가 범위를 벗어 난 경우. 프로그램 종료. if y == 9: for line in board: print(''.join(map(str, line))) exit() # 예외2: 이미 배치된 경우. 탐색 계속 if board[y][x] != 0: return func(y, x + 1) # backtracking for i in range(1, 9 + 1): # 예외3 : 같은 행/열/구역에 이미 배치된 경우. 탐색 종료 if i in row[y] or i in column[x] or i in area[(y // 3) * 3 + x // 3]: continue board[y][x] = i row[y].add(i) column[x].add(i) area[(y // 3) * 3 + x // 3].add(i) func(y, x + 1) area[(y // 3) * 3 + x // 3].remove(i) column[x].remove(i) row[y].remove(i) board[y][x] = 0 func(0, 0) ================================================ FILE: BOJ/2240.자두나무/6047198844.py ================================================ import math import sys T, W = map(int, sys.stdin.readline().split()) arr = [0] + [int(sys.stdin.readline()) for _ in range(T)] memo = [[[0 for _ in range(T + 1)] for _ in range(W + 2)] for _ in range(2 + 1)] # memo[나무][이동횟수][시간] # 시간 for i in range(1, T + 1): # 이동횟수 for j in range(1, W + 2): # 현재 값이 1인 경우 if arr[i] == 1: # 1에 대해. # 이전이 1 인경우 / 이전이 2 인경우 memo[1][j][i] = max(memo[1][j][i - 1], memo[2][j - 1][i - 1]) + 1 # 2에 대해. # 이전이 0 인경우 / 이전이 1 인경우 memo[2][j][i] = max(memo[1][j - 1][i - 1], memo[2][j][i - 1]) # 현재 값이 2인 경우 else: # 이동횟수 1번 / 떨어지는 초가 1인 경우 if i == 1 and j == 1: continue # 1에 대해. # 이전이 1 인경우 / 이전이 2 인경우 memo[1][j][i] = max(memo[1][j][i - 1], memo[2][j - 1][i - 1]) # 2에 대해. # 이전이 0 인경우 / 이전이 1 인경우 memo[2][j][i] = max(memo[1][j - 1][i - 1], memo[2][j][i - 1]) + 1 ans = -math.inf for i in range(1, W + 2): ans = max(memo[1][i][T], memo[2][i][T]) print(ans) ================================================ FILE: BOJ/2243.사탕상자/6047198844.py ================================================ # 문제 # 각각의 사탕은 그 맛의 좋고 나쁨이 1부터 1,000,000까지의 정수로 구분된다. # 1이 가장 맛있는 사탕을 의미하며, 1,000,000은 가장 맛없는 사탕을 의미한다. # 수정이는 동생이 말을 잘 들은 정도에 따라서, 사탕상자 안에 있는 사탕들 중 몇 번째로 맛있는 사탕을 꺼내주곤 한다. # 예를 들어 말을 매우 잘 들었을 때에는 사탕상자에서 가장 맛있는 사탕을 꺼내주고, 말을 조금 잘 들었을 때에는 사탕상자에서 여섯 번째로 맛있는 사탕을 꺼내주는 식이다. # # 수정이가 보관하고 있는 사탕은 매우 많기 때문에 매번 사탕상자를 뒤져서 꺼낼 사탕을 골라내는 일은 매우 어렵다. 수정이를 도와주는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 수정이가 사탕상자에 손을 댄 횟수 n(1 ≤ n ≤ 100,000)이 주어진다. # 다음 n개의 줄에는 두 정수 A, B, 혹은 세 정수 A, B, C가 주어진다. A가 1인 경우는 사탕상자에서 사탕을 꺼내는 경우이다. 이때에는 한 정수만 주어지며, B는 꺼낼 사탕의 순위를 의미한다. # 이 경우 사탕상자에서 한 개의 사탕이 꺼내지게 된다. 또, A가 2인 경우는 사탕을 넣는 경우이다. 이때에는 두 정수가 주어지는데, B는 넣을 사탕의 맛을 나타내는 정수이고 C는 그러한 사탕의 개수이다. # C가 양수일 경우에는 사탕을 넣는 경우이고, 음수일 경우에는 빼는 경우이다. 맨 처음에는 빈 사탕상자에서 시작한다고 가정하며, 사탕의 총 개수는 2,000,000,000을 넘지 않는다. 또한 없는 사탕을 꺼내는 경우와 같은 잘못된 입력은 주어지지 않는다. # # 출력 # A가 1인 모든 입력에 대해서, 꺼낼 사탕의 맛의 번호를 출력한다. import sys MAX = 1000000 tree = [0] * (4 * MAX) def update(sgi, begin, end, i, diff): tree[sgi] += diff if begin == end: return mid = (begin + end) // 2 if i <= mid: update(sgi * 2, begin, mid, i, diff) else: update(sgi * 2 + 1, mid + 1, end, i, diff) def sum(sgi, begin, end, left, right): if end < left or right < begin: return 0 if left <= begin and end <= right: return tree[sgi] mid = (begin + end) // 2 return sum(sgi * 2, begin, mid, left, right) + sum(sgi * 2 + 1, mid + 1, right, left, right) n = int(sys.stdin.readline()) for _ in range(n): cmd = list(map(int, sys.stdin.readline().split())) if len(cmd) == 2: # 순위 B = cmd[1] # 순위를 어떻게 구해야하나? # 이분 탐색해보자 begin, end, sgi = 1, MAX, 1 while begin < end: mid = (begin + end) // 2 left, right = tree[sgi*2], tree[sgi*2 + 1] # 왼쪽을 택하는 경우. if B <= left: # 순위는 그대로 # 범위는 좁아진다. end = mid sgi *= 2 # 오른쪽을 택하는 경우. else: # 순위는 낮아진다. B -= tree[sgi*2] begin = mid + 1 sgi = sgi * 2 + 1 # 실수함.ㅠ sgi *= 2 + 1 print(begin) update(1, 1, MAX, begin, -1) else: update(1, 1, MAX, cmd[1], cmd[2]) ================================================ FILE: BOJ/2252.줄 세우기/6047198844.cpp ================================================ #include #include #include using namespace std; vector> adj; void makeGraph() { int N; cin >> N; adj = vector >(N + 1); int M; cin >> M; int A, B; while (M--) { cin >> A >> B; adj[A].push_back(B); } return; } vector order; vector seen; void dfs(int here) { seen[here] = 1; for (int there : adj[here]) if (!seen[there]) dfs(there); order.push_back(here); } vector topologicalSort() { int N = adj.size(); seen = vector(N, 0); order.clear(); for (int i = 1; i < N; i++) if (!seen[i])dfs(i); reverse(order.begin(), order.end()); return order; } int main() { makeGraph(); vector res = topologicalSort(); for (int i : res) cout << i << " "; } ================================================ FILE: BOJ/2252.줄 세우기/6047198844.py ================================================ import sys from collections import deque, defaultdict N, M = map(int, sys.stdin.readline().split()) edges = defaultdict(list) indegrees = [0 for _ in range(N+1)] for _ in range(M): V, W = map(int, sys.stdin.readline().split()) # V 에 연결된 간선들을 나타내게 된다. edges[V].append(W) indegrees[W] += 1 # indegree 가 없는 정점들의 집합. Q = deque([]) for V in range(1, N + 1): if indegrees[V] == 0: Q.append(V) res = [] while Q: V = Q.popleft() # 결과에 삽입한다. res.append(V) # 자신으로부터 나가는 간선을 제거한다. 간선 제거후 연결된 정점에 대해서 indegree 감소를 시키며, 이떄의 정점이 0이되면 Q에 추가한다. for W in edges[V]: indegrees[W] -= 1 if indegrees[W] == 0: Q.append(W) for i in res: print(i, end=' ') ================================================ FILE: BOJ/22864.피로도/6047198844.py ================================================ # 문제 # 하루에 한 시간 단위로 일을 하거나 일을 쉬어도 된다. 하루에 한 시간 일하면 피로도는 A 만큼 쌓이고 일은 B 만큼 처리할 수 있다. # 만약에 한 시간을 쉰다면 피로도는 C 만큼 줄어든다. 단, 피로도가 음수로 내려가면 0으로 바뀐다. 당연히 일을 하지 않고 쉬었기 때문에 처리한 일은 없다. # 피로도를 최대한 M 을 넘지 않게 일을 하려고 한다. M 를 넘기면 일하는데 번아웃이 와서 이미 했던 일들도 다 던져버리고 일을 그만두게 된다. # 번아웃이 되지 않도록 일을 할때 하루에 최대 얼마나 일을 할 수 있는지 구해보자. 하루는 24시간이다. # # 입력 # 첫 번째 줄에 네 정수 A, B, C, M이 공백으로 구분되어 주어진다. # 맨 처음 피로도는 0이다. # # 출력 # 하루에 번 아웃이 되지 않도록 일을 할 때 최대 얼마나 많은 일을 할 수 있는지 출력한다. A, B, C, M = map(int, input().split()) tired = 0 time = 0 res = 0 while time < 24: if tired + A > M: tired -= C if tired < 0: tired = 0 else: tired += A res += B time += 1 print(res) ================================================ FILE: BOJ/2293.동전 1/6047198844.cpp ================================================ /* d[0] = 1; 1 2 3 4 5 6 7 8 9 10 1 1 1 1 1 1 1 1 1 1 1 d[0] d[1] d[2] d[3] d[4] d[5] d[6] d[7] d[8] d[9] 2 1 2 2 3 3 4 4 5 5 6 d[0] d[1] d[2] d[3] d[4] d[5] d[6] d[7] d[8] 5 1 2 2 3 4 5 6 7 8 10 d[0] d[1] d[2] d[3] d[4] d[5] 3 10 1 2 5 */ #include #include using namespace std; int value[10001] = { 1 }; int coin[100]; int dp(int n, int k) { /* for (int coin_idx = 0; coin_idx < n; coin_idx++) for (int value_idx = 1; value_idx <= k; value_idx++) { if(value_idx - coin[coin_idx]>=0) value[value_idx] += value[value_idx - coin[coin_idx]]; } */ for (int coin_idx = 0; coin_idx < n; coin_idx++) for (int a = coin[coin_idx]; a <= k; a++) value[a] += value[a - coin[coin_idx]]; return value[k]; } int main() { int n; int k; cin >> n >> k; for (int i = 0; i < n; i++) cin >> coin[i]; cout << dp(n, k); } ================================================ FILE: BOJ/2303.숫자 게임/6047198844.py ================================================ from itertools import combinations N = int(input()) res_person = 1 res_num = 0 for i in range(1, N+1): for j in combinations(map(int, input().split()), 3): s = sum(j) if s % 10 >= res_num: res_num = s % 10 res_person = i print(res_person) ================================================ FILE: BOJ/2338.긴자리 계산/6047198844.py ================================================ import sys A = int(sys.stdin.readline()) B = int(sys.stdin.readline()) print(A+B) print(A-B) print(A*B) ================================================ FILE: BOJ/2342.Dance Dance Revolution/6047198844.py ================================================ import math commands = list(map(int, input().split())) memo = [[[math.inf for _ in range(5)] for _ in range(5)] for _ in range(len(commands))] memo[0] = [[0 for _ in range(5)] for _ in range(5)] for idx, command in enumerate(commands[:-1]): # 초기 상태라면 , 항상 비용이 2가 든다. if idx == 0: memo[idx + 1][0][command] = 2 memo[idx + 1][command][0] = 2 continue # 왼발이 움직이는 경우. # 이전 오른발의 초기상태. 오른발은 고정이다. for fix in range(4 + 1): if fix == command: continue # 이전 왼발의 상태. 왼발은 움직인다. for move in range(4 + 1): if move == command: dn = 1 elif move == 0: dn = 2 elif ((move == 1 or move == 3) and (command == 2 or command == 4)) or ( (move == 2 or move == 4) and (command == 1 or command == 3)): dn = 3 else: dn = 4 memo[idx + 1][command][fix] = min(memo[idx + 1][command][fix], memo[idx][move][fix] + dn) memo[idx + 1][fix][command] = min(memo[idx + 1][fix][command], memo[idx][fix][move] + dn) res = math.inf for r in memo[-1]: res = min(res, min(r)) print(res) ================================================ FILE: BOJ/2346.풍선 터트리기/6047198844.py ================================================ # 1번부터 N번까지 N개의 풍선이 원형으로 놓여 있고. i번 풍선의 오른쪽에는 i+1번 풍선이 있고, 왼쪽에는 i-1번 풍선이 있다. # 단, 1번 풍선의 왼쪽에 N번 풍선이 있고, N번 풍선의 오른쪽에 1번 풍선이 있다. 각 풍선 안에는 종이가 하나 들어있고, 종이에는 -N보다 크거나 같고, N보다 작거나 같은 정수가 하나 적혀있다. # 이 풍선들을 다음과 같은 규칙으로 터뜨린다. # # 우선, 제일 처음에는 1번 풍선을 터뜨린다. 다음에는 풍선 안에 있는 종이를 꺼내어 그 종이에 적혀있는 값만큼 이동하여 다음 풍선을 터뜨린다. # 양수가 적혀 있을 경우에는 오른쪽으로, 음수가 적혀 있을 때는 왼쪽으로 이동한다. 이동할 때에는 이미 터진 풍선은 빼고 이동한다. # # 예를 들어 다섯 개의 풍선 안에 차례로 3, 2, 1, -3, -1이 적혀 있었다고 하자. # 이 경우 3이 적혀 있는 1번 풍선, -3이 적혀 있는 4번 풍선, -1이 적혀 있는 5번 풍선, 1이 적혀 있는 3번 풍선, 2가 적혀 있는 2번 풍선의 순서대로 터지게 된다. from collections import deque N = int(input()) balloons = list(enumerate(map(int, input().split()))) idx = 0 while balloons: idx %= len(balloons) # 풍선을 터트린다. # 위치 / 종이 pos, balloon = balloons.pop(idx) print(pos + 1) # 양수 방향으로 이동할경우 -1을 해준다. if balloon > 0: idx -= 1 idx += balloon ================================================ FILE: BOJ/2357.최솟값과 최댓값/6047198844.py ================================================ # 문제 # N(1 ≤ N ≤ 100,000)개의 정수들이 있을 때, a번째 정수부터 b번째 정수까지 중에서 제일 작은 정수, 또는 제일 큰 정수를 찾는 것은 어려운 일이 아니다. 하지만 이와 같은 a, b의 쌍이 M(1 ≤ M ≤ 100,000)개 주어졌을 때는 어려운 문제가 된다. 이 문제를 해결해 보자. # # 여기서 a번째라는 것은 입력되는 순서로 a번째라는 이야기이다. 예를 들어 a=1, b=3이라면 입력된 순서대로 1번, 2번, 3번 정수 중에서 최소, 최댓값을 찾아야 한다. 각각의 정수들은 1이상 1,000,000,000이하의 값을 갖는다. # # 입력 # 첫째 줄에 N, M이 주어진다. 다음 N개의 줄에는 N개의 정수가 주어진다. 다음 M개의 줄에는 a, b의 쌍이 주어진다. # # 출력 # M개의 줄에 입력받은 순서대로 각 a, b에 대한 답을 최솟값, 최댓값 순서로 출력한다. # sgi 를 초기화한다. sgi의 구간은 left, right 이다. import math import sys N, M = map(int, sys.stdin.readline().split()) arr = [0] + [int(sys.stdin.readline()) for _ in range(N)] # 최소값 / 최대값 segment_tree = [(math.inf, -math.inf)] * (N * 4) def init(sgi, left, right): # 리프노드에 도달 if left == right: segment_tree[sgi] = (min(arr[left:right + 1]), max(arr[left:right + 1])) else: mid = (left + right) // 2 min_left_child, max_left_child = init(sgi * 2, left, mid) min_right_child, max_right_child = init(sgi * 2 + 1, mid + 1, right) segment_tree[sgi] = (min(min_left_child, min_right_child), max(max_left_child, max_right_child)) return segment_tree[sgi] init(1, 1, N) # 현재 sgi 구간 left ~ right # 찾고자하는 구간 begin ~ end def find(sgi, left, right, begin, end): # 현재 구간이 찾고자하는 구간이 아닌 경우 if end < left or right < begin: return math.inf, -math.inf # 현재 구간이 안에 들어와 있는 경우 if begin <= left and right <= end: return segment_tree[sgi] # 현재 구간이 걸친 경우 mid = (left + right) // 2 min_left_child, max_left_child = find(sgi * 2, left, mid, begin, end) min_right_child, max_right_child = find(sgi * 2 + 1, mid + 1, right, begin, end) return min(min_left_child, min_right_child), max(max_left_child, max_right_child) for _ in range(M): a, b = map(int, sys.stdin.readline().split()) min_value, max_value = find(1, 1, N, a, b) print(min_value, max_value) ================================================ FILE: BOJ/23795.사장님 도박은 재미로 하셔야 합니다/6047198844.py ================================================ import sys res = 0 while True: N = int(sys.stdin.readline()) if N == -1: print(res) exit() res += N ================================================ FILE: BOJ/23825.SASA 모형을 만들어보자/6047198844.py ================================================ import sys N, M = map(int, sys.stdin.readline().split()) print(min(N//2, M//2)) ================================================ FILE: BOJ/24039.2021은 무엇이 특별할까/6047198844.py ================================================ import sys primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103] N = int(sys.stdin.readline()) for i in range(len(primes) - 1): mul = primes[i] * primes[i+1] if mul > N: print(mul) exit() ================================================ FILE: BOJ/2407.조합/6047198844.py ================================================ n, m = map(int, input().split()) res = 1 for i in range(m): res *= (n-i) for i in range(1, m+1): res //= i print(res) ================================================ FILE: BOJ/2420.사파리월드/6047198844.py ================================================ import sys N, M = map(int, sys.stdin.readline().split()) print(abs(N-M)) ================================================ FILE: BOJ/2422.한윤정이 이탈리아에 가서 아이스크림을 사먹는데/6047198844.py ================================================ from collections import defaultdict from itertools import combinations N, M = map(int, input().split()) not_allowed = defaultdict(set) for _ in range(M): A, B = map(int, input().split()) not_allowed[A].add(B) not_allowed[B].add(A) res = 0 for i in combinations(range(1, N + 1), 3): for j in i: if not_allowed[j].intersection(i): break else: res += 1 print(res) ================================================ FILE: BOJ/24262.알고리즘 수업 - 알고리즘의 수행 시간 1/6047198844.py ================================================ print(1) print(0) ================================================ FILE: BOJ/2437.저울/6047198844.cpp ================================================ #include #include #include #include #define INF INT_MAX; using namespace std; int main() { int N; cin >> N; vector vt(N + 1); vector sum(N); for (int i = 0; i < N; i++) cin >> vt[i]; vt[N] = INF; sort(vt.begin(), vt.end()); int res = 0; for (int i = 0; i <= N; i++) { //res는 만들수있는 정수의 최대값이다. if (res + 2 <= vt[i]) { cout << res + 1; return 0; } res += vt[i]; } } ================================================ FILE: BOJ/2444.별 찍기 - 7/6047198844.py ================================================ # 1, 3, 5, 7, 9, 7, 3, 1 N = int(input()) for i in range(1, N + 1): print(' ' * (N - i) + '*' * ((i - 1) * 2 + 1)) for i in range(1, N + 1): print(' ' * i + '*' * ((N - i - 1) * 2 + 1)) ================================================ FILE: BOJ/2447.별찍기 - 10/6047198844.cpp ================================================ #include #include using namespace std; void printStar(vector>& arr) { int x_size = arr[0].size(); int y_size = arr.size(); for (int y = 0; y < y_size; y++) { for (int x = 0; x < x_size; x++) printf("%c", arr[y][x]); printf("\n"); } return; } void makeStar(vector>& arr, int y, int x, int size) { if (size == 1) { arr[y][x] = '*'; return; } int resize = size / 3; for (int dy = 0; dy < 3; dy++) { for (int dx = 0; dx < 3; dx++) { if (dy == 1 && dx == 1) continue; makeStar(arr, y + dy * resize, x + dx * resize, resize); } } } int main() { int N; cin >> N; vector < vector> arr(N, vector(N, ' ')); makeStar(arr, 0, 0, N); printStar(arr); } ================================================ FILE: BOJ/2457.공주님의 정원/6047198844.py ================================================ import datetime import sys N = int(input()) flowers = list() for _ in range(N): start_month, start_day, end_month, end_day = map(int, sys.stdin.readline().split()) start = datetime.date(2020, start_month, start_day) if end_month == 12: end = datetime.date(2020, end_month, 1) else: end = datetime.date(2020, end_month, end_day) flowers.append((start, end)) flowers.append((datetime.date(2020, 12, 31), datetime.date(2020, 12, 31))) flowers.sort() # 첫꽃은 3월 1일에 피어야한다. cur_flower = (datetime.date(2020, 1, 1), datetime.date(2020, 3, 1)) last_flower = (datetime.date(2020, 1, 1), datetime.date(2020, 3, 1)) res = 0 for i in range(len(flowers)): # 범위 사이에 존재하는 경우. if flowers[i][0] <= cur_flower[1] <= flowers[i][1] and flowers[i][1] > last_flower[1]: last_flower = flowers[i] # 범위안에 존재하는 경우. elif cur_flower[0] <= flowers[i][0] and flowers[i][1] <= cur_flower[1]: pass # 범위 사이에 존재하지 않는 경우. else: # 갱신이 안된 경우. if cur_flower == last_flower: print(0) exit() # 갱신 cur_flower = last_flower res += 1 # 갱신 된 꽃 사이에 존재하면 갱신. if flowers[i][0] <= cur_flower[1] <= flowers[i][1]: last_flower = flowers[i] cur_flower = last_flower # 마지막꽃은 12월 1일 이후에 져야한다. if cur_flower[1] <= datetime.date(2020, 11, 30): print(0) exit() print(res) ================================================ FILE: BOJ/2467.용액/6047198844.py ================================================ # 개요 # 같은 양의 두 용액을 혼합한 용액의 특성값은 혼합에 사용된 각 용액의 특성값의 합으로 정의한다. # 산성 용액과 알칼리성 용액의 특성값이 정렬된 순서로 주어졌을 때, 이 중 두 개의 서로 다른 용액을 혼합하여 특성값이 0에 가장 가까운 용액을 만들어내는 두 용액을 찾는 프로그램을 작성하시오. # # 입력 # 전체 용액의 수 N이 입력된다. 2 <= N <= 100,000 이하의 정수이다. # 용액의 특성값을 나타내는 N개의 정수가 빈칸을 사이에 두고 오름차순으로 입력 -1,000,000,000 <= i <= 1,000,000,000 # N개의 용액들의 특성값은 모두 서로 다르다 # # 출력 # 첫째 줄에 특성값이 0에 가장 가까운 용액을 만들어내는 두 용액의 특성값을 출력한다. # 출력해야 하는 두 용액은 특성값의 오름차순으로 출력한다. # 특성값이 0에 가장 가까운 용액을 만들어내는 경우가 두 개 이상일 경우에는 그 중 아무것이나 하나를 출력한다. import math import sys N = int(input()) arr = list(map(int, sys.stdin.readline().split())) begin, end = 0, N - 1 rb, red = begin, end target = 0 diff = math.inf while begin < end: s = arr[begin] + arr[end] if abs(s) < diff: rb, re = begin, end diff = abs(s) if s < target: begin += 1 else: end -= 1 print(arr[rb], arr[re]) ================================================ FILE: BOJ/2467.용액/ms9849.cpp ================================================ #include #include #include #include using namespace std; int N,num,Front,Back,ans = INT_MAX; vector v; int ans_Front, ans_Back; int main(void) { cin >> N; for(int i=0; i> num; v.push_back(num); } Front = 0; Back = N-1; while(Front #include #include #include using namespace std; int board[100][100]; bool board_01[100][100]; //¿ int dx[4] = { -1,1,0,0 }; int dy[4] = { 0,0,-1,1 }; bool range(int n, int y, int x) { if (0 > y || y >= n) return false; if (0 > x || x >= n) return false; return true; } int bfs(int under_value,int n) { for (int y = 0; y < n; y++) for (int x = 0; x < n; x++) board_01[y][x] = board[y][x] <= under_value ? false : true; int cnt = 0; for (int y = 0; y < n; y++) { for (int x = 0; x < n; x++) { if (board_01[y][x]) { cnt++; queue > q; q.push({ y,x }); while (!q.empty()) { int y = q.front().first; int x = q.front().second; q.pop(); for (int di = 0; di < 4; di++) { int check_y = dy[di] + y; int check_x = dx[di] + x; if (range(n,check_y,check_x)&&board_01[check_y][check_x]) { q.push({ check_y,check_x }); board_01[check_y][check_x] = false; } } } } } } return cnt; } int main() { int n; cin >> n; int max_value = 0; for (int y = 0; y < n; y++) for (int x = 0; x < n; x++) { cin >> board[y][x]; max_value = max(board[y][x], max_value); } int res_result = 0; for (int i = 0; i <= max_value; i++) { res_result = max(res_result, bfs(i,n)); } cout << res_result; } ================================================ FILE: BOJ/2468.안전 영역/rockmiin.py ================================================ from collections import deque def bfs(v): q= deque([v]) visited[v[0]][v[1]]= 1 while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tx, ty= x+ dx, y+ dy if 0<= tx< n and 0<= ty< n: if adj[tx][ty] > h and not visited[tx][ty]: q.append([tx, ty]) visited[tx][ty]= 1 n= int(input()) adj=[list(map(int, input().split())) for _ in range(n)] res= 0 height= 0 for i in range(n): for j in range(n): if adj[i][j]> height: height= adj[i][j] # print("height :", height) for h in range(height): cnt= 0 visited = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): if not visited[i][j] and adj[i][j]> h: bfs([i, j]) cnt += 1 if visited[i][j]==0: cnt= 0; continue; res= max(res, cnt) print(res) # 시간복잡도를 계산할 때 높이가 1이상 100이하라는 작은 범위였기 때문에 완전탐색이 가능했다. ================================================ FILE: BOJ/2473.세 용액/6047198844.py ================================================ # 문제 # 같은 양의 세 가지 용액을 혼합한 용액의 특성값은 혼합에 사용된 각 용액의 특성값의 합으로 정의한다. # 이 연구소에서는 같은 양의 세 가지 용액을 혼합하여 특성값이 0에 가장 가까운 용액을 만들려고 한다. # 참고로, 세 종류의 알칼리성 용액만으로나 혹은 세 종류의 산성 용액만으로 특성값이 0에 가장 가까운 혼합 용액을 만드는 경우도 존재할 수 있다. # 산성 용액과 알칼리성 용액이 주어졌을 때, 이 중 같은 양의 세 개의 서로 다른 용액을 혼합하여 특성값이 0에 가장 가까운 용액을 만들어내는 세 용액을 찾는 프로그램을 작성하시오. # # 입력 # 첫째 줄에는 전체 용액의 수 N이 입력된다. N은 3 이상 5,000 이하의 정수이다. # 둘째 줄에는 용액의 특성값을 나타내는 N개의 정수가 빈칸을 사이에 두고 주어진다. 이 수들은 모두 -1,000,000,000 이상 1,000,000,000 이하이다. # N개의 용액들의 특성값은 모두 다르고, 산성 용액만으로나 알칼리성 용액만으로 입력이 주어지는 경우도 있을 수 있다. import math import sys N = int(sys.stdin.readline()) arr = list(map(int, sys.stdin.readline().rstrip().split())) arr.sort() # O(N^2) min_diff = math.inf res = (arr[0], arr[1], arr[2]) for k in range(N): begin, end = 0, N - 1 while begin < end: if k == begin: begin += 1 if k == end: end -= 1 if begin >= end: break s = arr[begin] + arr[end] + arr[k] if abs(s) < min_diff: res = (arr[begin], arr[end], arr[k]) min_diff = abs(s) # target 만들기 if s < 0: begin += 1 else: end -= 1 for i in sorted(res): print(i, end=' ') ================================================ FILE: BOJ/2475.검증수/6047198844.py ================================================ numbers = map(int, input().split()) cnt = 0 for number in numbers: cnt += number**2 print(cnt % 10) ================================================ FILE: BOJ/2476.주사위 게임/6047198844.py ================================================ import sys def func(i, j, k): if i == j == k: return 10000 + i * 1000 elif i == j or j == k: return 1000 + j * 100 elif i == k: return 1000 + i * 100 return max(i, j, k) * 100 N = int(sys.stdin.readline()) res = -1 for _ in range(N): A = list(map(int, sys.stdin.readline().split())) res = max(res, func(A[0], A[1], A[2])) print(res) ================================================ FILE: BOJ/2480.주사위 세개/6047198844.py ================================================ a, b, c = map(int, input().split()) if a == b == c: print(10000 + a * 1000) elif a == b or a == c: print(1000 + a * 100) elif b == c: print(1000 + b * 100) else: print(max(a, b, c) * 100) ================================================ FILE: BOJ/2485.가로수/6047198844.py ================================================ def gcd(a, b): while b != 0: a, b = b, a % b return a N = int(input()) arr = list(sorted([int(input()) for _ in range(N)])) intervals = list(set([arr[i] - arr[i - 1] for i in range(1, N)])) if len(intervals) >= 2: gcd_num = gcd(intervals[0], intervals[1]) for i in range(2, len(intervals)): gcd_num = gcd(gcd_num, intervals[i]) else: gcd_num = intervals[0] start = arr[0] end = arr[-1] min_cnt = (end - start) // gcd_num print(min_cnt - N + 1) ================================================ FILE: BOJ/2490.윷놀이/6047198844.py ================================================ from collections import Counter for _ in range(3): s = input().split() zero_cnt = Counter(s).get('0') if zero_cnt == 1: print('A') elif zero_cnt == 2: print('B') elif zero_cnt == 3: print('C') elif zero_cnt == 4: print('D') elif zero_cnt == None: print('E') ================================================ FILE: BOJ/2493.탑/6047198844.py ================================================ # 문제 # 실험을 위하여 일직선 위에 N개의 높이가 서로 다른 탑을 수평 직선의 왼쪽부터 오른쪽 방향으로 차례로 세우고, 각 탑의 꼭대기에 레이저 송신기를 설치하였다. # 모든 탑의 레이저 송신기는 레이저 신호를 지표면과 평행하게 수평 직선의 왼쪽 방향으로 발사하고, 탑의 기둥 모두에는 레이저 신호를 수신하는 장치가 설치되어 있다. # 하나의 탑에서 발사된 레이저 신호는 가장 먼저 만나는 단 하나의 탑에서만 수신이 가능하다. # # 예를 들어 높이가 6, 9, 5, 7, 4인 다섯 개의 탑이 수평 직선에 일렬로 서 있고, 모든 탑에서는 주어진 탑 순서의 반대 방향(왼쪽 방향)으로 동시에 레이저 신호를 발사한다고 하자. # 그러면, 높이가 4인 다섯 번째 탑에서 발사한 레이저 신호는 높이가 7인 네 번째 탑이 수신을 하고, 높이가 7인 네 번째 탑의 신호는 높이가 9인 두 번째 탑이, 높이가 5인 세 번째 탑의 신호도 높이가 9인 두 번째 탑이 수신을 한다. # 높이가 9인 두 번째 탑과 높이가 6인 첫 번째 탑이 보낸 레이저 신호는 어떤 탑에서도 수신을 하지 못한다. # # 탑들의 개수 N과 탑들의 높이가 주어질 때, 각각의 탑에서 발사한 레이저 신호를 어느 탑에서 수신하는지를 알아내는 프로그램을 작성하라. # # 입력 # 첫째 줄에 탑의 수를 나타내는 정수 N이 주어진다. N은 1 이상 500,000 이하이다. # 둘째 줄에는 N개의 탑들의 높이가 직선상에 놓인 순서대로 하나의 빈칸을 사이에 두고 주어진다. # 1 <= 탑들의 높이 <= 100,000,000 # # 출력 # 첫째 줄에 주어진 탑들의 순서대로 각각의 탑들에서 발사한 레이저 신호를 수신한 탑들의 번호를 하나의 빈칸을 사이에 두고 출력한다. 만약 레이저 신호를 수신하는 탑이 존재하지 않으면 0을 출력한다. import sys N = int(sys.stdin.readline()) arr = list(map(int, sys.stdin.readline().split())) stack = [] for i in range(N): while stack and arr[stack[-1]] <= arr[i]: stack.pop() if stack: print(stack[-1] + 1) else: print(0) stack.append(i) ================================================ FILE: BOJ/2504.괄호의 값/6047198844.py ================================================ # () 닫을때 현재값 x 2 # [] 닫을때 현재값 x 3 s = list(input()) stack = [] tmp = 1 res = 0 for i in range(len(s)): if s[i] == '(': tmp *= 2 stack.append('(') elif s[i] == '[': tmp *= 3 stack.append('[') elif s[i] == ')': if stack and stack[-1] == '(': if s[i - 1] == '(': res += tmp stack.pop() tmp = tmp // 2 else: print(0) exit() elif s[i] == ']': if stack and stack[-1] == '[': if s[i - 1] == '[': res += tmp stack.pop() tmp = tmp // 3 else: print(0) exit() print(res) ================================================ FILE: BOJ/25083.새싹/6047198844.py ================================================ print(''' ,r'"7 r`-_ ,' ,/ \. ". L_r' `~\/ | | ''') ================================================ FILE: BOJ/2517.달리기/6047198844.cpp ================================================ #include #include #include #include #include using namespace std; map mp; int N; void update(int idx, vector& res) { while (idx <= N) { res[idx] += 1; idx += idx & (-idx); } return; } int prefix_sum(int idx, vector& res) { int sum = 0; while (idx > 0) { sum += res[idx]; idx -= idx & (-idx); } return sum; } int main() { cin >> N; vector index_tree_rank(N + 1); vector temp(N + 1); vector res(N + 1); for (int i = 1; i <= N; i++) { cin >> index_tree_rank[i]; temp[i] = index_tree_rank[i]; } sort(temp.begin(), temp.end()); for (int i = 1; i <= N; i++) mp.insert({ temp[i],i }); for (int i = 1; i <= N; i++) { update(mp[index_tree_rank[i]], res); cout << i - prefix_sum(mp[index_tree_rank[i]] - 1, res) << "\n"; } } ================================================ FILE: BOJ/25191.치킨댄스를 추는 곰곰이를 본 임스/6047198844.py ================================================ import sys N = int(input()) A, B = map(int, sys.stdin.readline().split()) print(min(A//2 + B, N)) ================================================ FILE: BOJ/2523.별찍기-13/6047198844.py ================================================ n = int(input()) for i in range(1,n+1): print('*'*i) for j in range(n-1, 0, -1): print('*'*j) ================================================ FILE: BOJ/2525.오븐 시계/6047198844.py ================================================ start_hour, start_minute = map(int, input().split()) need_minute = int(input()) end_minute, need_hour = (start_minute + need_minute) % 60, (start_minute + need_minute) // 60 end_hour = (start_hour + need_hour) % 24 print(end_hour, end_minute) ================================================ FILE: BOJ/2526.전깃줄/sAp00n.py ================================================ """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 1 초 128 MB 11185 5219 4136 47.102% 문제 두 전봇대 A와 B 사이에 하나 둘씩 전깃줄을 추가하다 보니 전깃줄이 서로 교차하는 경우가 발생하였다. 합선의 위험이 있어 이들 중 몇 개의 전깃줄을 없애 전깃줄이 교차하지 않도록 만들려고 한다. 예를 들어, <그림 1>과 같이 전깃줄이 연결되어 있는 경우 A의 1번 위치와 B의 8번 위치를 잇는 전깃줄, A의 3번 위치와 B의 9번 위치를 잇는 전깃줄, A의 4번 위치와 B의 1번 위치를 잇는 전깃줄을 없애면 남아있는 모든 전깃줄이 서로 교차하지 않게 된다. 전깃줄이 전봇대에 연결되는 위치는 전봇대 위에서부터 차례대로 번호가 매겨진다. 전깃줄의 개수와 전깃줄들이 두 전봇대에 연결되는 위치의 번호가 주어질 때, 남아있는 모든 전깃줄이 서로 교차하지 않게 하기 위해 없애야 하는 전깃줄의 최소 개수를 구하는 프로그램을 작성하시오. 입력 첫째 줄에는 두 전봇대 사이의 전깃줄의 개수가 주어진다. 전깃줄의 개수는 100 이하의 자연수이다. 둘째 줄부터 한 줄에 하나씩 전깃줄이 A전봇대와 연결되는 위치의 번호와 B전봇대와 연결되는 위치의 번호가 차례로 주어진다. 위치의 번호는 500 이하의 자연수이고, 같은 위치에 두 개 이상의 전깃줄이 연결될 수 없다. 출력 첫째 줄에 남아있는 모든 전깃줄이 서로 교차하지 않게 하기 위해 없애야 하는 전깃줄의 최소 개수를 출력한다. """ # LIS 유형입니다 # 처음 접해보아 깔끔한 코드가 나오지 않아 고민하다가 솔루션을 보고 풀이했습니다. # 코드가 짧게 나올꺼 같아 숏코딩을 해보았는데 뭔가 아쉽네요 더 줄일 수 있었을꺼 같은데. from sys import stdin list_of_lines = sorted([tuple(map(int, stdin.readline().split())) for _ in range(int(stdin.readline()))]) vector = [0] * len(list_of_lines) vector[0] = 1 for i in range(1, len(list_of_lines)): min_value = 0 for j in range(i): if list_of_lines[i][-1] > list_of_lines[j][-1]: min_value = max(vector[j], min_value) vector[i] = min_value + 1 print(len(list_of_lines) - max(vector)) ================================================ FILE: BOJ/2529.부등호/6047198844.py ================================================ from itertools import permutations N = int(input()) sign = input().split() number = list(map(int, range(10))) res = [] for i in permutations(number, N+1): flag = True for idx in range(1,N+1): if sign[idx-1] == '<' and i[idx-1] > i[idx]: flag = False break if sign[idx-1] == '>' and i[idx-1] < i[idx]: flag = False break if flag: res.append(i) for _ in res[-1]: print(_, end='') print() for _ in res[0]: print(_, end='') ================================================ FILE: BOJ/2533.사회망 서비스(SNS)/6047198844.py ================================================ import sys sys.setrecursionlimit(10 ** 9) # 소셜인 경우와 소셜이 아닌 경우를 계산한다. def func(root): # 방문 처리 visited[root] = 1 # 방문한 경우 memo[root][True] = 1 for child in edge[root]: # 자식인 경우 if visited[child] == 0: # 자식 계산 func(child) memo[root][True] += min(memo[child][True], memo[child][False]) memo[root][False] += memo[child][True] N = int(sys.stdin.readline()) edge = [[] for _ in range(N + 1)] memo = [[0, 0] for _ in range(N + 1)] visited = [0 for _ in range(N + 1)] for _ in range(N - 1): V, W = map(int, sys.stdin.readline().split()) edge[V].append(W) edge[W].append(V) func(1) print(min(memo[1][True], memo[1][False])) ================================================ FILE: BOJ/2553.마지막 펙토리얼 수/6047198844.cpp ================================================ #include #include using namespace std; // ڸ Ѵ. int factorial(int n) { long long mul = 1; for (int i = 1; i <= n; i++) { mul *= i; mul %= 1000000000; while (!(mul % 10)) mul /= 10; } return mul % 10; } int main() { int n; cin >> n; cout << factorial(n); } ================================================ FILE: BOJ/2565.전깃줄/6047198844.cpp ================================================ #include #include #include using namespace std; int cache[100]; int dp(vector& vt, int idx,int size) { int& res = cache[idx]; if (res) return res; res = 1; for (int dx = 1; idx + dx <= size; dx++) { if (vt[idx] < vt[idx + dx]) { res = max(res, 1 + dp(vt, idx + dx, size)); } } return res; } int main() { int N; cin >> N; pair p; vector> vt; while (N--) { cin >> p.first >> p.second; vt.push_back(p); } sort(vt.begin(), vt.end()); int size = vt.size(); vector lis; lis.push_back(-1); for (int i = 0; i < size; i++) { lis.push_back(vt[i].second); } cout << size - (dp(lis, 0, size) - 1); } ================================================ FILE: BOJ/2568.전깃줄 - 2/6047198844.py ================================================ import sys from bisect import bisect_right from collections import deque N = int(sys.stdin.readline()) wires = [tuple(map(int, sys.stdin.readline().split())) for _ in range(N)] wires.sort() memo = [] idx_memo = [] for wire in wires: left, right = wire idx = bisect_right(memo, right) if idx == len(memo): memo.append(right) else: memo[idx] = right idx_memo.append(idx) print(len(wires) - len(memo)) i = len(memo) - 1 j = len(idx_memo) - 1 res = [] while j >= 0: if idx_memo[j] == i: i -= 1 else: res.append(wires[j][0]) j -= 1 for i in res[::-1]: print(i) ================================================ FILE: BOJ/2576.홀수/6047198844.py ================================================ import sys arr = [] for _ in range(7): i = int(input()) if i % 2 == 1: arr.append(i) if arr: print(sum(arr)) print(min(arr)) else: print(-1) ================================================ FILE: BOJ/2580.스도쿠/6047198844.cpp ================================================ #include using namespace std; bool flag = false; int arr[9][9]; int res[9][9]; void checkArea(const int &y, const int &x, bool* numberCheck) { int dy = (y / 3) * 3; int dx = (x / 3) * 3; for (int y = 0; y < 3; y++) for (int x = 0; x < 3; x++) numberCheck[arr[y + dy][x + dx]] = true; return; } void checkRow(const int &y, bool *numberCheck) { for (int i = 0; i < 9; i++) numberCheck[arr[y][i]] = true; return; } void checkCol(const int &x, bool* numberCheck) { for (int i = 0; i < 9; i++) numberCheck[arr[i][x]] = true; return; } //y , x 부터 시작해서 스도쿠를 완성한다. void dfs(int y, int x) { if (flag) return; if (y == 9) { flag = true; copy(&arr[0][0], &arr[0][0] + 9 * 9, &res[0][0]); return; } if (arr[y][x]) { if (x == 8) return dfs(y + 1, 0); else return dfs(y, x + 1); } bool numberCheck[10]; // 1부터 9까지 있으면 true fill_n(numberCheck, 10, false); //가로 검사 checkRow(y, numberCheck); //세로 검사 checkCol(x, numberCheck); //네모칸 검사 checkArea(y, x, numberCheck); for (int i = 1; i < 10; i++) { if (!numberCheck[i]&&!flag) { arr[y][x] = i; if (x == 8) dfs(y + 1, 0); else dfs(y, x + 1); arr[y][x] = 0; } } return; } int main() { for (int y = 0; y < 9; y++) for (int x = 0; x < 9; x++) scanf(" %d", &arr[y][x]); dfs(0, 0); for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { printf("%d ", res[y][x]); } printf("\n"); } } ================================================ FILE: BOJ/2581.소수/6047198844.py ================================================ prime = [True] * 10001 # 소수이면 True def sieve(): prime[1] = False for n in range(2, 10001): if prime[n]: # n 가 소수인경우 for m in range(n + n, 10001, n): prime[m] = False sieve() M = int(input()) N = int(input()) prime_list = [i for i in range(M,N+1) if prime[i]] if prime_list: print(sum(prime_list)) print(min(prime_list)) else: print(-1) ================================================ FILE: BOJ/2583.영역 구하기/rockmiin.py ================================================ from collections import deque def bfs(v): q= deque([v]) area[v[0]][v[1]]= 1 count= 1 while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+ dx, y+ dy if 0<= tmp_x< m and 0<= tmp_y< n and area[tmp_x][tmp_y]==0: q.append([tmp_x, tmp_y]) area[tmp_x][tmp_y]= 1 count+=1 return count # print(count) # for i in area: # print(i) m, n, k= map(int, input().split()) # m이 세로, n이 가로 area= [[0 for _ in range(n)] for _ in range(m)] cnt= [] # 블록 색칠 for i in range(k): x1, y1, x2, y2= list(map(int, input().split())) for j in range(y1, y2): # slicing할 떄 주의점 좌 우의 개수를 맞춰줘야 함 area[j][x1:x2]=[2]*(x2-x1) # for i in area: # print(i) for i in range(m): for j in range(n): if area[i][j]==0: cnt.append(bfs([i, j])) print(len(cnt)) for i in (sorted(cnt)): print(i, end=" ") # 입력 # 5 7 3 # 0 2 4 4 # 1 1 2 5 # 4 0 6 2 # 출력 # 3 # 1 7 13 ================================================ FILE: BOJ/2589.보물섬/6047198844.py ================================================ # 문제 # 보물섬 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. # 각 칸은 육지(L)나 바다(W)로 표시되어 있다. # 이 지도에서 이동은 상하좌우로 이웃한 육지로만 가능하며, 한 칸 이동하는데 한 시간이 걸린다. # 보물은 서로 간에 최단 거리로 이동하는데 있어 가장 긴 시간이 걸리는 육지 두 곳에 나뉘어 묻혀있다. # 육지를 나타내는 두 곳 사이를 최단 거리로 이동하려면 같은 곳을 두 번 이상 지나가거나, 멀리 돌아가서는 안 된다. # # # # 예를 들어 위와 같이 지도가 주어졌다면 보물은 아래 표시된 두 곳에 묻혀 있게 되고, 이 둘 사이의 최단 거리로 이동하는 시간은 8시간이 된다. # # # # 보물 지도가 주어질 때, 보물이 묻혀 있는 두 곳 간의 최단 거리로 이동하는 시간을 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에는 보물 지도의 세로의 크기와 가로의 크기가 빈칸을 사이에 두고 주어진다. 이어 L과 W로 표시된 보물 지도가 아래의 예와 같이 주어지며, 각 문자 사이에는 빈 칸이 없다. 보물 지도의 가로, 세로의 크기는 각각 50이하이다. # # 출력 # 첫째 줄에 보물이 묻혀 있는 두 곳 사이를 최단 거리로 이동하는 시간을 출력한다. import math from collections import deque L, W = map(int, input().split()) board = [list(input()) for _ in range(L)] res = -math.inf for y in range(L): for x in range(W): visited = set() if board[y][x] == 'L': visited.add((y, x)) Q = deque([(y,x)]) cnt = -1 while Q: for _ in range(len(Q)): yy, xx = Q.popleft() for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny, nx = yy + dy, xx + dx if 0 <= ny < L and 0 <= nx < W and (ny, nx) not in visited and board[ny][nx] == 'L': visited.add((ny, nx)) Q.append((ny, nx)) cnt += 1 res = max(res, cnt) print(res) ================================================ FILE: BOJ/2606.바이러스/6047198844.cpp ================================================ #include #include #include using namespace std; bool check[101]; vector vt[101]; int bfs(int computer_num) { int res = 0; memset(check, false, sizeof(bool) * 101); check[1] = true; queue q; q.push(1); while (!q.empty()) { int computer = q.front(); q.pop(); int size = vt[computer].size(); for (int i = 0; i < size; i++) { if (!check[vt[computer][i]]) { q.push(vt[computer][i]); check[vt[computer][i]] = true; res++; } } } return res; } int main() { int computer_num; int line; cin >> computer_num; cin >> line; int line_a; int line_b; for (int i = 0; i < line; i++) { cin >> line_a >> line_b; vt[line_a].push_back(line_b); vt[line_b].push_back(line_a); } cout << bfs(computer_num); } ================================================ FILE: BOJ/2606.바이러스/rockmiin.py ================================================ from collections import deque n= int(input()) m= int(input()) def bfs(v): q= deque([v]) cnt= 0 visited[v]=1 while q: v= q.popleft() for i in arr[v]: if not visited[i]: q.append(i) visited[i]=1 cnt+=1 return cnt-1 arr=[[] for _ in range(n+1)] # print(arr) for i in range(m): x, y= map(int, input().split()) arr[x].append(y) arr[y].append(x) # 정점 크기 순서대로 정렬 for i in arr: i.sort() visited=[0 for _ in range(n+1)] print(bfs(1)) # 입력 예시 # 7 # 6 # 1 2 # 2 3 # 1 5 # 5 2 # 5 6 # 4 7 # 출력 4 ================================================ FILE: BOJ/2606.바이러스/sAp00n.py ================================================ from sys import stdin from collections import deque def search_connected_computer(input_graph): # for Node Num 01 visit = {} stack = deque() for i in graph[1]: stack.append(i) number_of_connected_computer = -1 while len(stack) > 0: #print(f'stack: {stack}\nvisit: {visit}') current_node = stack.popleft() if current_node in visit: continue visit[current_node] = True number_of_connected_computer += 1 connected_list = graph[current_node] for connected_node in connected_list: if connected_node in visit: continue stack.append(connected_node) return number_of_connected_computer Num_of_computers = int(stdin.readline()) Num_of_connection = int(stdin.readline()) graph = {} for i in range(1, Num_of_computers + 1): graph[i] = [] for i in range(Num_of_connection): computer01, computer02 = list(map(int, stdin.readline().split())) graph[computer01].append(computer02) graph[computer02].append(computer01) #print(graph) num_of_com = search_connected_computer(graph) print(num_of_com) ================================================ FILE: BOJ/2606.바이러스/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/2606 바이러스 [풀이] 1. 각 노드간의 관계를 표현하기 위해 defaultdict 사용 2. 방문관계를 나타내기 위한 visited 선언 => 1번 노드부터 바이러스가 퍼지므로 1번은 방문한 것으로 초기화 => 0번 노드는 인덱스간의 비교를 위한 용도로만 사용 3. DFS : 스택에서 뽑은 기준노드 그리고 기준노드와 연결되어있는 노드 조사 => 연결노드를 이미 방문했다면 패스 => 연결노드를 방문하지 않았다면 방문 마킹 => 연결노드와 또 연결된 노드들을 조사하기 위해 stack에 append 4. 1을 제외한 감염 컴퓨터 반환 ''' from collections import defaultdict n, m = map(int, [input(), input()]) dic = defaultdict(list) for _ in range(m): a, b = map(int, input().split()) dic[a].append(b) dic[b].append(a) visited = [0, 1] + [0] * (n-1) stack = [1] while stack: idx = stack.pop() for node in dic[idx]: if not visited[node]: visited[node] = 1 stack.append(node) print(visited.count(1)-1) ================================================ FILE: BOJ/2618.경찰차/6047198844.py ================================================ import sys sys.setrecursionlimit(10 ** 9) def distance(ay, ax, by, bx): return abs(ay - by) + abs(ax - bx) N = int(sys.stdin.readline()) W = int(sys.stdin.readline()) # arr[idx] 경찰차가 idx를 택했을때의 위치 arr = [(0, 0)] + [tuple(map(int, sys.stdin.readline().split())) for _ in range(W)] # memo[A][B] 0번 경찰차가 A, 1번 경찰차가 B를 택했을때 이동하는 거리의 합 memo = [[-1 for _ in range(W + 1)] for _ in range(W + 1)] path = [[-1 for _ in range(W + 1)] for _ in range(W + 1)] # A와 B는 각각 0번/1번 경찰차가 어디 idx 에 있는지 나타낸다. # func(A,B)는 0번/1번 경찰차가 arr[A], arr[B] 위치에 있을때, 두대의 경찰차가 이동하는 거리의 최소 합이다. # 핵심 아이디어는 A,B 중 가장 큰수가 갱신된 수라는 점이다. def func1(A, B): # base case: 범위 체크 if A == W or B == W: return 0 # base case2: 메모 되었는가 if memo[A][B] != -1: return memo[A][B] # 다음 스텝 -> 가장 최근것에 1 더한다. next = max(A, B) + 1 # A를 이동 시킨다. # 이전거리 -> 이동거리 if A == 0: move_a = distance(1, 1, arr[next][0], arr[next][1]) else: move_a = distance(arr[A][0], arr[A][1], arr[next][0], arr[next][1]) # B를 이동 시킨다. if B == 0: move_b = distance(N, N, arr[next][0], arr[next][1]) else: move_b = distance(arr[B][0], arr[B][1], arr[next][0], arr[next][1]) a_result = func1(next, B) + move_a b_result = func1(A, next) + move_b memo[A][B] = min(a_result, b_result) return memo[A][B] # 루트를 구하는 함수. 이미 메모는 완성되어있는상태 (func1이 반드시 선행된다.). def func2(A, B): if A == W or B == W: return next = max(A, B) + 1 # A를 이동 시킨다. # 이전거리 -> 이동거리 if A == 0: move_a = distance(1, 1, arr[next][0], arr[next][1]) else: move_a = distance(arr[A][0], arr[A][1], arr[next][0], arr[next][1]) # B를 이동 시킨다. if B == 0: move_b = distance(N, N, arr[next][0], arr[next][1]) else: move_b = distance(arr[B][0], arr[B][1], arr[next][0], arr[next][1]) # 재귀 타지 않고 어떤게 최선인지 바로 구할수있음. # A를 택하는게 최선인 경우 if memo[next][B] + move_a < memo[A][next] + move_b: print(1) func2(next, B) else: print(2) func2(A, next) func1(0, 0) print(memo[0][0]) func2(0, 0) ================================================ FILE: BOJ/2623.음악프로그램/6047198844.py ================================================ import sys from collections import defaultdict, deque N, M = map(int, sys.stdin.readline().split()) P = [i for i in range(N + 1)] lines = [list(map(int, sys.stdin.readline().split()))[1:] for _ in range(M)] edges = defaultdict(list) indegrees = [0 for _ in range(N + 1)] for line in lines: for idx in range(len(line) - 1): V, W = line[idx], line[idx + 1] edges[V].append(W) indegrees[W] += 1 # 위상정렬 결과 res = [] # 위상정렬을 위한 큐 Q = deque([]) # indegree 가 0 인 vertex 만 큐에 넣는다. for i in range(1, N + 1): if indegrees[i] == 0: Q.append(i) while Q: V = Q.popleft() res.append(V) for W in edges[V]: indegrees[W] -= 1 if indegrees[W] == 0: Q.append(W) if len(res) != N: print(0) else: for r in res: print(r) ================================================ FILE: BOJ/2628.종이자르기/6047198844.py ================================================ import math import sys width, height = map(int, sys.stdin.readline().split()) N = int(sys.stdin.readline()) cut_width = list() cut_height = list() for _ in range(N): i, j = map(int, sys.stdin.readline().split()) if i == 0: cut_height.append(j) else: cut_width.append(j) cut_height.append(0) cut_height.append(height) cut_width.append(0) cut_width.append(width) cut_width.sort() cut_height.sort() res = -math.inf for i in range(len(cut_height) - 1): for j in range(len(cut_width) - 1): res = max(res, (cut_height[i+1] - cut_height[i]) * (cut_width[j+1] - cut_width[j])) print(res) ================================================ FILE: BOJ/2630.색종이 만들기/6047198844.cpp ================================================ //분할 정복 알고리즘 연습 /* 첫째 줄에는 전체 종이의 한 변의 길이 N이 주어져 있다. N은 2, 4, 8, 16, 32, 64, 128 중 하나이다. 색종이의 각 가로줄의 정사각형칸들의 색이 윗줄부터 차례로 둘째 줄부터 마지막 줄까지 주어진다. 하얀색으로 칠해진 칸은 0, 파란색으로 칠해진 칸은 1로 주어지며, 각 숫자 사이에는 빈칸이 하나씩 있다. */ #include using namespace std; int paper[128][128]; int white_cnt = 0; int blue_cnt = 0; void divide_and_conquer(int from_y, int from_x, int d) { bool flag = false; int check_arr = paper[from_y][from_x]; for (int y = from_y; y < from_y + d && !flag; y++) { for (int x = from_x; x < from_x + d; x++) { if (check_arr != paper[y][x]) { flag = !flag; break; } } } if (flag) { divide_and_conquer(from_y, from_x, d / 2); divide_and_conquer(from_y, from_x + d / 2, d / 2); divide_and_conquer(from_y + d / 2, from_x, d / 2); divide_and_conquer(from_y + d / 2, from_x + d / 2, d / 2); } else { if (check_arr) blue_cnt++; else white_cnt++; } return; } int main() { int N; cin >> N; for (int y = 0; y < N; y++) for (int x = 0; x < N; x++) cin >> paper[y][x]; divide_and_conquer(0, 0, N); cout << white_cnt << "\n" << blue_cnt; } ================================================ FILE: BOJ/2636.치즈/6047198844.py ================================================ import sys from collections import deque # 세로/가로 M, N = map(int, sys.stdin.readline().split()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(M)] # 겉 def func(): Q = deque() Q.append((0, 0)) board[0][0] = 3 while Q: y, x = Q.popleft() for ny, nx in (y + 1, x), (y - 1, x), (y, x - 1), (y, x + 1): if 0 <= ny < M and 0 <= nx < N and board[ny][nx] == 0: Q.append((ny, nx)) board[ny][nx] = 3 # 녹는곳 -> 상하좌우 한면이라도 노출되어있는곳 def melt(): Q = deque() for y in range(M): for x in range(N): for ny, nx in (y + 1, x), (y - 1, x), (y, x - 1), (y, x + 1): if board[y][x] == 1 and 0 <= ny < M and 0 <= nx < N and board[ny][nx] == 3: Q.append((y, x)) board[y][x] = 5 break for y in range(M): for x in range(N): if board[y][x] == 3 or board[y][x] == 5: board[y][x] = 0 return len(Q) res = 0 cnt = 0 while True: func() tmp = melt() if tmp == 0: print(cnt) print(res) break cnt += 1 res = tmp ================================================ FILE: BOJ/2636.치즈/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/2636 치즈 [풀이] 1. main 1-1. 사전 세팅 => 재귀제한을 2000으로 늘려줘야 한다 => 반복적인 입력이 최대 만번이므로 sys.stdin.readline을 사용 => 가로와 세로를 저장할 w, h 그리고 모양을 저장할 board를 선언 => 탐색을 위한 move, 녹아 없어지는 시간 time, 치즈 개수 prev_cheese를 선언 1-2. 공기 구별 => 2. check_air 에서 확인한다 => 치즈 바깥쪽에 있는 공기와 안쪽에 있는 공기를 구별해야 한다 => 바깥쪽에 있는 공기는 -1로 바꿔주도록 한다 확인 조건은, 주변 원소가 -1 이거나 벽과 닿아있으면. => 중요한 점은, 탐색이 모두 끝난후에 바꿔야 한다는 점. 따라서, set을 사용해서 중복을 제거하며 미리 넣어두고 탐색이 끝난 후 하나씩 꺼내면서 치환 1-3. 출력 조건 => 공기를 구별하기 위해 조건을 확인하면서 치즈 개수도 센다 => 치환 후에 치즈 개수가 0이면, 모든 치즈가 녹기 한 시간전의 치즈 개수 prev_cheese를 반환 1-4. 녹는 조건 => check_melt() 함수로 확인 => 자신을 기준, 상하좌우로 -1을 가진 공기가 있다면 자신은 녹는다. 2. check_air 2-1. flag = 0으로 선언. => 인자로 받은 좌표가 바깥쪽에 있는 공기로 판단되면 flag가 1 이상의 값을 가진다 2-2. 바깥쪽에 있는 공기 판단 조건 => 벽에 닿아있거나, 주변 공기가 -1 2-3. 만약, 자신이 0인 공기면서 outer_air에 포함되어있지 않으면 자신을 중심으로 다시 check_air => 이 때 outer_air는 set() 자료형으로 방문여부를 확인하는 기능 => 또, 아직은 0인 공기지만 추후에 -1인 공기로 밝혀진다면 이 때 모든 air를 치환할 수 있도록 방문했던 공기를 기억해주는 역할. ''' def check_air(board, y, x): flag = 0 for dy, dx in move: ny, nx = dy+y, dx+x if ny < 0 or ny >= h or nx < 0 or nx >= w: flag += 1 continue if board[ny][nx] == -1: flag += 1 continue if board[ny][nx] == 0 and (ny, nx) not in outer_air: outer_air.add((ny, nx)) flag += check_air(board, ny, nx) return flag def check_melt(y, x): for dy, dx in move: ny, nx = dy + y, dx + x if board[ny][nx] == -1: return True return False import sys sys.setrecursionlimit(2000) input = sys.stdin.readline h, w = map(int, input().strip().split()) board = [list(map(int, input().strip().split())) for _ in range(h)] move = [(0, -1), (0, 1), (-1, 0), (1, 0)] time = 0 prev_cheese = 0 while True: total_cheese = 0 for y in range(h): for x in range(w): outer_air = set() if board[y][x] == 0 and (y, x) not in outer_air: outer_air.add((y, x)) flag = check_air(board, y, x) if flag > 0: for ny, nx in list(outer_air): board[ny][nx] = -1 elif board[y][x] == 1: total_cheese += 1 if total_cheese == 0: print(time) print(prev_cheese) break melt = set() for y in range(h): for x in range(w): if board[y][x] == 1: if check_melt(y, x): melt.add((y, x)) for ny, nx in list(melt): board[ny][nx] = -1 time += 1 prev_cheese = total_cheese ================================================ FILE: BOJ/2638.치즈/6047198844.py ================================================ import sys from collections import deque N, M = map(int, sys.stdin.readline().split()) board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] def bfs(board): check_board = [[True for _ in range(M)] for _ in range(N)] check_board[0][0] = False visited = set() visited.add((0, 0)) Q = deque([(0, 0)]) while Q: y, x = Q.popleft() for ny, nx in (y + 1, x), (y, x + 1), (y, x - 1), (y - 1, x): if 0 <= ny < N and 0 <= nx < M and (ny, nx) not in visited and board[ny][nx] == 0: check_board[ny][nx] = False Q.append((ny, nx)) visited.add((ny, nx)) res = False for y in range(N): for x in range(M): if board[y][x] == 0: continue res = True cnt = 0 for ny, nx in (y + 1, x), (y, x + 1), (y, x - 1), (y - 1, x): if 0 <= ny < N and 0 <= nx <= M and check_board[ny][nx] == False: cnt += 1 if cnt >= 2: board[y][x] = 0 return res res = 0 while bfs(board): res += 1 print(res) ================================================ FILE: BOJ/2644.촌수 계산/rockmiin.py ================================================ from collections import deque def bfs(start, end): q= deque([start]) while q: v= q.popleft() if v== end: break; for i in adj[v]: if not visited[i]: q.append(i) visited[i]= visited[v]+1 if visited[end]==0: return -1 return visited[end] n= int(input()) start, end= map(int, input().split()) m= int(input()) adj= [[] for _ in range(n+1)] for i in range(1, m+1): x, y= map(int, input().split()) adj[x].append(y) adj[y].append(x) # print(adj) visited = [0 for _ in range(n + 1)] print(bfs(start, end)) # idea # 처음에 부모 -> 자식 일방향 탐색으로 생각을 했는데 노드에 양쪽으로 넣어 준 다음 간단하게 시작점과 끝점을 지정해줘서 # 그 위치에 도달하게 되면 bfs를 빠져나와 그 때의 촌 수를 출력해주면 됨 # 방문 여부와 촌 수를 같이 계산해주는 visited list를 사용하였음 # 방문을 하지 않았을 경우에는 즉 visited==0이라면 -1로 출력하는 예외 처리를 해줘야 함 ================================================ FILE: BOJ/2644.촌수계산/6047198844.cpp ================================================ #include #include #include using namespace std; vector vt[101]; bool check[101]; int bfs(int x, int y) { queue q; q.push(x); check[x] = true; int cnt = 0; int q_size; while (!q.empty()) { q_size = q.size(); while (q_size--) { int point = q.front(); q.pop(); int point_size = vt[point].size(); if (point == y) return cnt; for (int i = 0; i < point_size; i++) { if (!check[vt[point][i]]) { q.push(vt[point][i]); check[vt[point][i]] = true; } } } cnt++; } return -1; } int main() { int n; cin >> n; int a; int b; cin >> a >> b; int m; cin >> m; int x; int y; while (m--) { cin >> x >> y; vt[x].push_back(y); vt[y].push_back(x); } cout << bfs(a, b); } ================================================ FILE: BOJ/2651.자동차경주대회/2651_자동차경주대회.cpp ================================================ #include #include using namespace std; int max_length; int end_stage; int distance_w[102]; int cost[102]; int memo[102]; int memo_spot[102]; // n ð. int dp(int n) { if (memo[n]) return memo[n]; if (n == end_stage) return 0; int res_min = 0; int cnt_distance = 0; for (int i = n + 1; i <= end_stage; i++) { cnt_distance += distance_w[i]; if (cnt_distance > max_length) break; int temp = cost[n] + dp(i); if (!res_min || res_min > temp) { res_min = temp; memo_spot[n] = i; } } return memo[n] = res_min; } int main() { cin >> max_length; cin >> end_stage; end_stage++; distance_w[0] = 0; for (int i = 1; i <= end_stage; i++) cin >> distance_w[i]; for (int i = 1; i < end_stage; i++) cin >> cost[i]; cost[0] = cost[end_stage] = 0; cout << dp(0) << "\n"; vector vt; for (int i = memo_spot[0];i!= end_stage; i = memo_spot[i]) vt.push_back(i); cout << vt.size() << "\n"; for (int i : vt) cout << i << " "; } ================================================ FILE: BOJ/2659.십자카드 문제/6047198844.cpp ================================================ #include #include #include #include #include using namespace std; set card; int clock_num(int card_num) { vector temp; for (int i = 0; i < 4; i++) { temp.push_back(card_num); card_num = card_num / 10 + (card_num % 10) * 1000; } return *min_element(temp.begin(), temp.end()); } void make_card() { for (int card_num = 1111; card_num <= 9999; card_num++) { int n = card_num; while (n % 10) n = n / 10; if (n) continue; card.insert(clock_num(card_num)); } } int main() { make_card(); int res = 0; int num; for (int i = 1000; i > 0; i /= 10) { cin >> num; res += num * i; } vector qwer; copy(card.begin(), card.end(), back_inserter(qwer)); cout << find(qwer.begin(),qwer.end(),clock_num(res)) - qwer.begin() + 1; } ================================================ FILE: BOJ/2660.회장뽑기/6047198844.cpp ================================================ #include #include #include #include using namespace std; //해당 노드에 연결된 간선을 모두 검사한다. bool check[51]; vector edge[51]; int bfs(int node, int n) { int level = 0; memset(check + 1, false, n + 1); check[node] = true; queue q; for (int i = 0; i < edge[node].size(); i++) { q.push(edge[node][i]); check[edge[node][i]] = true; } while (!q.empty()) { level++; int q_size = q.size(); for (int i = 0; i < q_size; i++) { int node = q.front(); q.pop(); int node_size = edge[node].size(); for (int j = 0; j < node_size; j++) { if (!check[edge[node][j]]) { q.push(edge[node][j]); check[edge[node][j]] = true; } } } } return level; } bool compare(pair a, pair b) { if (a.second != b.second) return a.second < b.second; return a.first < b.first; } int main() { int N; cin >> N; int a; int b; while (1) { cin >> a >> b; if (a == -1 && b == -1) break; edge[a].push_back(b); edge[b].push_back(a); } vector > res; for (int i = 1; i <= N; i++) { int num = bfs(i, N); res.push_back({ i,num }); } sort(res.begin(), res.end(), compare); int candidate = res[0].second; vector va; int num = 0; for (auto c : res) { if (c.second != candidate) break; num++; va.push_back(c.first); } cout << candidate << " " << num << "\n"; for (int i : va) cout << i << " "; } ================================================ FILE: BOJ/2667. 단지번호붙이기/rockmiin.py ================================================ from collections import deque def bfs(v): q= deque([v]) visited[v[0]][v[1]]= 1 node_cnt=1 while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+dx, y+dy # x, y값이 범위 내에 있으며 방문하지 않았고, 입력 값이 1이라면 q에 넣고, 방문 처리하고, 노드의 수를 count if 0<=tmp_x #include #include #include using namespace std; int main() { int N; cin >> N; int arr[101]; bool check[101]; memset(check, false, 1+N); for (int i = 1; i <= N; i++) cin >> arr[i]; vector res; for (int i = 1; i <= N; i++) { vector vt; int idx = i; while (!check[idx]) { vt.push_back(idx); check[idx] = true; idx = arr[idx]; } auto it = find(vt.begin(), vt.end(), idx); while (it != vt.end()) { res.push_back(*it); it++; } } sort(res.begin(), res.end()); cout << res.size() << "\n"; for (auto i : res) { cout << i << "\n"; } } ================================================ FILE: BOJ/2669.직사각형 네개의 합집합의 면적 구하기/2669_직사각형 네개의 합집합의 면적 구하기.cpp ================================================ #include #include #include using namespace std; int main() { int arr[100][100]; memset(arr[0], 0, sizeof(int) * 100 * 100); int start_x, start_y, end_x, end_y; for (int cnt = 0; cnt < 4; cnt++) { cin >> start_x >> start_y >> end_x >> end_y; for (int x = start_x; x < end_x; x++) for (int y = start_y; y < end_y; y++) arr[y][x] = 1; } cout << count(arr[0], arr[0] + 100 * 100, 1); } //memset ּ óϸ ƴѵ ?? ================================================ FILE: BOJ/2670.연속부분최대곱/6047198844.py ================================================ import sys N = int(input()) ropes = list() for _ in range(N): ropes.append(float(sys.stdin.readline())) res = 0 for i in range(N): tmp = ropes[i] res = res if res > tmp else tmp for j in range(i + 1, N): tmp *= ropes[j] res = res if res > tmp else tmp print(round(res, 3)) ================================================ FILE: BOJ/2693.N번째 큰 수/6047198844.py ================================================ T = int(input()) for _ in range(T): print(sorted(list(map(int, input().split())))[-3]) ================================================ FILE: BOJ/2729.이진수 덧셈/6047198844.py ================================================ T = int(input()) for _ in range(T): A, B = input()[::-1].split() acc = ['0'] for idx in range(max(len(A), len(B))): cur = int(acc[idx]) if idx < len(A): cur += int(A[idx]) if idx < len(B): cur += int(B[idx]) acc[idx] = str(cur % 2) acc.append(str(cur // 2)) while len(acc) > 1 and acc[-1] == '0': acc.pop() print(''.join(acc[::-1])) ================================================ FILE: BOJ/2729.이진수 덧셈/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/2729 이진수 덧셈 [풀이] 1. int(x, 2)는 이진수를 십진수로 변환 2. format(num, 'b')는 num을 이진수(=binary)로 변환 ''' import sys input = sys.stdin.readline N = int(input().strip()) for _ in range(N): a, b = map(lambda x : int(x, 2), input().strip().split()) print(format(a+b, 'b')) ================================================ FILE: BOJ/2740.행렬곱셈/sAp00n.py ================================================ import sys class Matrix: def __init__(self): N, M = sys.stdin.readline().split() N, M = int(N), int(M) data = {} for j in range(N): row = sys.stdin.readline().split() for i in range(M): data[(i, j)] = int(row[i]) self._N, self._M = N, M self._data = data def __str__(self): string = ('「' + (' ' * (self._M + 1)) + '┐') for j in range(self._N): row = '│ ' for i in range(self._M): minus_check = False row += str(self._data[(i, j)]) if self._data[(i, j)] < 0: minus_check = True if i < self._M - 1: if minus_check: row += ' ' else: row += ' ' row += ' │' string += ('\n' + row) string += ('\n' + '└' + (' ' * (self._M + 1)) + '┘') return string def dotmult(matrixA, matrixB): return_mat = '' for i in range(matrixA._N): row = '' for j in range(matrixB._M): ele = 0 for k in range(matrixA._M): ele += (matrixA._data[(k, i)] * matrixB._data[(j, k)]) row += (str(ele) + ' ') return_mat += (row + '\n') return return_mat def solution(): matrixA = Matrix() matrixB = Matrix() print(f'N,M = {matrixA._N}, {matrixA._M}\ndata = {matrixA._data}') print(f'N,M = {matrixB._N}, {matrixB._M}\ndata = {matrixB._data}') print(f'matrixA:\n{matrixA}') print(f'matrixB:\n{matrixB}') print(dotmult(matrixA, matrixB)) solution() ================================================ FILE: BOJ/2744.대소문자 바꾸기/6047198844.py ================================================ print(input().swapcase()) ================================================ FILE: BOJ/2745.진법 변환/6047198844.py ================================================ # 문제 # B진법 수 N이 주어진다. 이 수를 10진법으로 바꿔 출력하는 프로그램을 작성하시오. # # 10진법을 넘어가는 진법은 숫자로 표시할 수 없는 자리가 있다. 이런 경우에는 다음과 같이 알파벳 대문자를 사용한다. # # A: 10, B: 11, ..., F: 15, ..., Y: 34, Z: 35 # # 입력 # 첫째 줄에 N과 B가 주어진다. (2 ≤ B ≤ 36) # # B진법 수 N을 10진법으로 바꾸면, 항상 10억보다 작거나 같다. # # 출력 # 첫째 줄에 B진법 수 N을 10진법으로 출력한다. N, B = input().split() B = int(B) res = 0 for idx, number in enumerate(N[::-1]): if str.isdigit(number): res += int(number) * B ** idx else: res += int(ord(number) - 55) * B ** idx print(res) ================================================ FILE: BOJ/2747.피보나치 수/6047198844.cpp ================================================ #include int memo[46] = { 0,1 }; using namespace std; //0 0 1° 1 int dp(int n) { if (n <= 0) return 0; if (memo[n]) return memo[n]; int& res = memo[n]; res = dp(n - 1) + dp(n - 2); return res; } int main() { int n; cin >> n; cout << dp(n); } ================================================ FILE: BOJ/2747.피보나치 수/sangmandu.py ================================================ n = int(input()) a, b = 0, 1 for _ in range(n): a, b = b, a+b print(a) ================================================ FILE: BOJ/2748.피보나치 수/sangmandu.py ================================================ n = int(input()) a, b = 0, 1 for _ in range(n): a, b = b, a+b print(a) ================================================ FILE: BOJ/2752.세수정렬/6047198844.py ================================================ from _curses import endwin arr = sorted(list(map(int, input().split()))) for i in arr: print(i, end=' ') ================================================ FILE: BOJ/2776.암기왕/6047198844.py ================================================ import sys T = int(sys.stdin.readline()) for _ in range(T): N = int(sys.stdin.readline()) memo1 = set(map(int, sys.stdin.readline().split())) M = int(sys.stdin.readline()) memo2 = list(map(int, sys.stdin.readline().split())) for integer in memo2: print(int(integer in memo1)) ================================================ FILE: BOJ/2792.보석 상자/6047198844.py ================================================ import heapq import sys N, M = map(int, sys.stdin.readline().split()) colors = [] for _ in range(M): marble = int(sys.stdin.readline().rstrip()) heapq.heappush(colors, (-marble, marble)) for _ in range(N-M): max_color = heapq.heappop(colors)[1] heapq.heappush(colors, (-(max_color // 2 + max_color % 2), max_color // 2 + max_color % 2)) heapq.heappush(colors, (-(max_color // 2), max_color // 2)) print(heapq.heappop(colors)[1]) ================================================ FILE: BOJ/2798.블랙잭/6047198844.cpp ================================================ #include #include #include using namespace std; int N, M; //첫째 줄에 M을 넘지 않으면서 M에 최대한 가까운 카드 3장의 합을 출력한다. //index + 1을 선택했을때의 수와 index + 1을 선택하지 않았을때의 수 int brute_force(vector &arr, int idx, int cnt, int sum) { //index + 1의 선택을 고려하지않는수. 이미 조건 만족. 더이상 고려할것이없다 -> base case if (cnt == 0 && sum <= M) return sum; //idx+1을 선택했을때의 수와 idx+1을 선택하지 않았을때의 수를 고려하는 수. if (cnt < 0 || sum > M || idx + 1 >= N) return 0; return max(brute_force(arr, idx + 1, cnt, sum), brute_force(arr, idx + 1, cnt - 1, sum + arr[idx + 1])); } int main() { cin >> N >> M; vector arr(N); for (int i = 0; i < N; i++) { cin >> arr[i]; } int res; res = brute_force(arr, -1, 3, 0); cout << res; } ================================================ FILE: BOJ/2798.블랙잭/6047198844.java ================================================ package algorithm.bruteforce; import java.util.Scanner; import java.util.Vector; public class BOJ_2798_ { //迭 ũ static int N; //ִġ static int M; //idx / ʾƼ ִ M ִ static int brute_force(int sum, int idx, int remain, Vector arr) { // ϷȰ if(remain==0&&sum<=M) return sum; //ÿϷ // ϴ if(idx>=N||sum>M) return Integer.MIN_VALUE; int res = 0; //ϴ res = brute_force(sum+arr.get(idx), idx+1, remain-1, arr); //þϴ res = Math.max(res, brute_force(sum, idx+1, remain, arr)); return res; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); M = sc.nextInt(); Vector arr = new Vector(N); for(int i = 0 ; i < N; i++) { int e = sc.nextInt(); arr.add(e); } System.out.println(brute_force(0,0,3,arr)); } } ================================================ FILE: BOJ/2805.나무 자르기/6047198844.cpp ================================================ #include #include #include using namespace std; int main() { int N, M; cin >> N >> M; vector arr(N); for (int i = 0; i < N; i++) { cin >> arr[i]; } sort(arr.begin(), arr.end(), greater()); long long start = 0; long long end = arr[0]; while (start + 1 < end) { long long mid = (start + end) / 2; long long h = 0; for (int i = 0; i < N; i++) { long long dif = arr[i] - mid; if (dif <= 0) break; h += dif; } if (h < M) { end = mid; } else { start = mid; } } cout << start; } ================================================ FILE: BOJ/2812.크게 만들기/6047198844.py ================================================ N, K = map(int, input().split()) num = list(input()) k, stack = K, [] for i in range(N): while k > 0 and stack and stack[-1] < num[i]: stack.pop() k -= 1 stack.append(num[i]) print(''.join(stack[:N-K])) ================================================ FILE: BOJ/2822.점수 계산/6047198844.py ================================================ import heapq PQ = [] for i in range(1, 8+1): heapq.heappush(PQ, (-int(input()), i)) res = [] s = 0 for i in range(5): k, l = heapq.heappop(PQ) res.append(l) s -= k print(s) res.sort() for i in res: print(i, end=' ') ================================================ FILE: BOJ/2828.사과 담기 게임/6047198844.py ================================================ import sys N, M = map(int, sys.stdin.readline().split()) J = int(sys.stdin.readline()) positions = [int(sys.stdin.readline()) for _ in range(J)] left = 1 right = M distance = 0 for position in positions: while position < left: left -= 1 right -= 1 distance += 1 while position > right: left += 1 right += 1 distance += 1 print(distance) ================================================ FILE: BOJ/2839.설탕 배달/6047198844.py ================================================ N = int(input()) three = 0 five = 0 while N % 5 and N >= 0: N -= 3 three += 1 five = N // 5 print(-1) if N < 0 else print(three + five) ================================================ FILE: BOJ/2839.설탕 배달/pul8219.js ================================================ // BOJ // 2389번 문제: 설탕 배달 var n = Number(require('fs').readFileSync('/dev/stdin')); // BOJ 제출용 코드. 입력값을 받는 코드이며 입력값을 숫자로 받기 위해 Number로 감쌈 // 초기 n은 봉지에 나눠담을 설탕 n킬로그램을 의미 let three = 0; // 3kg짜리 봉지 개수 let five = Math.floor(n / 5); // 5kg짜리 봉지 개수 n %= 5; while(five >= 0){ if(n % 3 == 0){ // 5kg 봉지에 담고 남은 나머지 설탕의 무게가 3kg 봉지에 딱 나눠떨어지게 담긴다면 three = Math.floor(n / 3); // 3kg짜리 봉지 개수 갱신 n %= 3; // n은 0일 것 // 봉지에 담아야할 설탕을 모두 담았음 break; } five--; // 5kg 봉지에 담고 남은 나머지 설탕의 무게가 3kg 봉지에 딱 떨어지게 담길 수 없다면 five를 감소시킴(5kg 짜리 봉지수를 한 개 감소시키는 것) n += 5; // 5kg 봉지를 감소시켰으니 남은 설탕의 무게도 +5 해줌 } if (n==0){ // 봉지에 모두 잘 담겼다면 console.log(five + three); // 봉지개수 출력 } else{ // 정확하게 N킬로그램을 만들 수 없다면 console.log(-1); // -1 출력 } ================================================ FILE: BOJ/2839.설탕 배달/rockmiin.py ================================================ n= int(input()) min= 5000 for i in range((n//5)+1): if n%3==0 and n//3 < min: min= (n//3) + i n-=5 if min== 5000: min= -1 print(min) ================================================ FILE: BOJ/2845.파티가 끝나고 난 뒤/6047198844.py ================================================ import sys L, P = map(int, sys.stdin.readline().split()) C = L * P for i in map(int, sys.stdin.readline().split()): print(i-C, end=' ') ================================================ FILE: BOJ/2847.게임을 만든 동준이/6047198844.py ================================================ import sys #input N = int(sys.stdin.readline()) levels = list() for _ in range(N): levels.append(int(sys.stdin.readline())) #뒤집어서 생각 levels.reverse() #로직 -> 이전 값보다 1작게 . 이전값보다 이미 작으면 그대로. res = 0 for idx in range(1,len(levels)): # 현재값이 크면안된다. 현재값은 이전값 -1 보다 같거나 작아야한다. if levels[idx-1] - 1 < levels[idx]: #현재값 - (이전값 - 1) 을 res에 더한다. res += levels[idx] - (levels[idx-1] - 1) #현재값을 이전값 -1 로 맞춘다. levels[idx] = levels[idx-1] - 1 #output print(res) ================================================ FILE: BOJ/2851.슈퍼마리오/sAp00n.py ================================================ import sys mush_list = [] temp = 0 for _ in range(10): mush_list += [int(sys.stdin.readline())] '''from random import randint mush_list = [] temp = 0 for _ in range(10): mush_list += [randint(0,100)] print(f'mush_list = {mush_list}')''' score = 0 i = 0 for idx in range(10): if score + mush_list[idx] > 100: break score += mush_list[idx] i += 1 if i < 10: temp = score + mush_list[idx] #print(f'i : {i}') #print(f'score = {score} diff form 100 = {abs(100 - score)} \ntemp = {temp} diff from 100 = {abs(100 - temp)}') if abs(100 - score) == abs(100 -temp): print(temp) elif abs(100 - score) > abs(100 - temp): print(temp) else: print(score) ================================================ FILE: BOJ/2863.이게 분수?/6047198844.py ================================================ import sys A, B = map(int, sys.stdin.readline().split()) C, D = map(int, sys.stdin.readline().split()) arr = [] arr.append(A / C + B / D) arr.append(C / D + A / B) arr.append(D / B + C / A) arr.append(B / A + D / C) print(arr.index(max(arr))) ================================================ FILE: BOJ/2869.달팽이는 올라가고 싶다/6047198844.py ================================================ A, B, V = map(int, input().split()) print((V - B - 1) // (A - B) + 1) ================================================ FILE: BOJ/2887.행성 터널/6047198844.py ================================================ import heapq import math import sys from collections import deque N = int(sys.stdin.readline()) x_vertexes = [] y_vertexes = [] z_vertexes = [] for i in range(N): x, y, z = map(int, sys.stdin.readline().split()) x_vertexes.append((x, i)) y_vertexes.append((y, i)) z_vertexes.append((z, i)) edges = [] x_vertexes.sort() y_vertexes.sort() z_vertexes.sort() for i in range(1, N): x1, V = x_vertexes[i] x2, W = x_vertexes[i - 1] edges.append((abs(x1 - x2), V, W)) y1, V = y_vertexes[i] y2, W = y_vertexes[i - 1] edges.append((abs(y1 - y2), V, W)) z1, V = z_vertexes[i] z2, W = z_vertexes[i - 1] edges.append((abs(z1 - z2), V, W)) edges.sort() P = [i for i in range(N)] def union(V, W): PV = find(V) PW = find(W) if PV == PW: return False P[PW] = PV return True def find(V): if P[V] == V: return P[V] P[V] = find(P[V]) return P[V] res = 0 for dist, V, W in edges: if not union(V, W): continue res += dist print(res) ================================================ FILE: BOJ/2914.저작권/6047198844.py ================================================ A, B = map(int, input().split()) print(A * (B - 1) + 1) ================================================ FILE: BOJ/2935.소음/6047198844.py ================================================ A = int(input()) cal = str(input()) B = int(input()) if cal == '*': print(A*B) else: print(A+B) ================================================ FILE: BOJ/2960.에라토스테네스의 체/6047198844.py ================================================ ''' 문제 에라토스테네스의 체는 N보다 작거나 같은 모든 소수를 찾는 유명한 알고리즘이다. 이 알고리즘은 다음과 같다. 2부터 N까지 모든 정수를 적는다. 아직 지우지 않은 수 중 가장 작은 수를 찾는다. 이것을 P라고 하고, 이 수는 소수이다. P를 지우고, 아직 지우지 않은 P의 배수를 크기 순서대로 지운다. 아직 모든 수를 지우지 않았다면, 다시 2번 단계로 간다. N, K가 주어졌을 때, K번째 지우는 수를 구하는 프로그램을 작성하시오. 입력 첫째 줄에 N과 K가 주어진다. (1 ≤ K < N, max(1, K) < N ≤ 1000) 출력 첫째 줄에 K번째 지워진 수를 출력한다. ''' from collections import deque N, K = map(int, input().split()) sieve = [True for _ in range(N+1)] cnt = 0 for i in range(2, N+1): if sieve[i]: j = i while j <= N: if sieve[j]: sieve[j] = False cnt += 1 if cnt == K: print(j) exit() j += i ================================================ FILE: BOJ/2961.도영이가 만든 맛있는 음식/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/2961 도영이가 만든 맛있는 음식 [풀이] 1. 조합될 수 있는 모든 경우를 구한다 2. 조합마다 신맛과 쓴맛의 차를 구한다 ''' import sys input = sys.stdin.readline N = int(input().strip()) cook = [tuple(map(int, input().strip().split())) for _ in range(N)] foods = [] for sour, bitter in cook: temp = [] for food in foods: temp.append(food + [[sour, bitter]]) temp.append([[sour, bitter]]) foods.extend(temp) min_diff = abs(cook[0][0]-cook[0][1]) for food in foods: sour, bitter = 1, 0 for s, b in food: sour *= s bitter += b min_diff = min(min_diff, abs(sour-bitter)) print(min_diff) ================================================ FILE: BOJ/2981.검문/6047198844.cpp ================================================ #include #include #include using namespace std; void print_fnc(int n) { cout << n << " "; } int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } int main() { int N; cin >> N; vector arr(N); for (int i = 0; i < N; i++) cin >> arr[i]; sort(arr.begin(), arr.end()); int g = arr[1] - arr[0]; for (int i = 2; i < N; i++) g = gcd(g, arr[i] - arr[i - 1]); //10억의 제곱근 = 3~4만 vector res; for (int i = 1; i * i <= g; i++) { if (g % i) continue; res.push_back(i); res.push_back(g / i); } sort(res.begin(), res.end()); res.erase(unique(res.begin(), res.end()), res.end()); for_each(res.begin() + 1, res.end(),print_fnc); } ================================================ FILE: BOJ/3009.네 번째 점/6047198844.cpp ================================================ #include #include using namespace std; int main() { int x[3]; int y[3]; int N = 3; while (N--) { cin >> x[N] >> y[N]; } sort(x, x + 3); sort(y, y + 3); x[0] == x[1] ? cout << x[2] : cout << x[0]; cout << " "; y[0] == y[1] ? cout << y[2] : cout << y[0]; } ================================================ FILE: BOJ/3015.오아시스 재결합/6047198844.py ================================================ # 문제 # 오아시스의 재결합 공연에 N명이 한 줄로 서서 기다리고 있다. # 이 역사적인 순간을 맞이하기 위해 줄에서서 기다리고 있던 백준이는 갑자기 자기가 볼 수 있는 사람의 수가 궁금해 졌다. # 두 사람 A와 B가 서로 볼 수 있으려면, 두 사람 사이에 A 또는 B보다 키가 큰 사람이 없어야 한다. # 줄에 서있는 사람의 키가 주어졌을 때, 서로 볼 수 있는 쌍의 수를 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 줄에서 기다리고 있는 사람의 수 N이 주어진다. (1 ≤ N ≤ 500,000) # 둘째 줄부터 N개의 줄에는 각 사람의 키가 나노미터 단위로 주어진다. 모든 사람의 키는 231 나노미터 보다 작다. # 사람들이 서 있는 순서대로 입력이 주어진다. # # 출력 # 서로 볼 수 있는 쌍의 수를 출력한다. import sys N = int(sys.stdin.readline()) left, right = 0, 0 arr = [int(sys.stdin.readline()) for _ in range(N)] stack = [] res = 0 for i in arr: # 좌측보다 작은 경우. if stack and stack[-1] > i: res += 1 # 좌측보다 같거나 큰 경우. else: while stack and stack[-1] < i: stack.pop() res += 1 # 같은 경우가 있을 수 있다. 따라서 upper bound 를 통해. 개수를 알아낸다. if stack: begin = 0 end = len(stack) target = i while begin < end: mid = (begin + end) // 2 # 타겟이 더 큰경우 -> 타겟이 mid보다 왼쪽에 있다는뜻 if stack[mid] > target: begin = mid + 1 else: end = mid res += len(stack) - begin if stack[end - 1] > target: res += 1 stack.append(i) print(res) ================================================ FILE: BOJ/3029.경고/6047198844.py ================================================ from datetime import datetime start_time = datetime.strptime(input(), '%H:%M:%S') end_time = datetime.strptime(input(), '%H:%M:%S') total_sec = (end_time - start_time).seconds m, s = divmod(total_sec, 60) h, m = divmod(m, 60) # 적어도 1초를 기다린다. if h == 0 and m == 0 and s == 0: h = 24 print('{:02d}:{:02d}:{:02d}'.format(h, m, s)) ================================================ FILE: BOJ/3036.링/6047198844.cpp ================================================ #include #include using namespace std; int gcf(int a, int b) { if (b == 0) return a; return gcf(b, a % b); } int main() { int N; cin >> N; vector arr(N); for (int i = 0; i < N; i++) cin >> arr[i]; for (int i = 1; i < N; i++) { int f = gcf(arr[0], arr[i]); cout << arr[0] / f << "/" << arr[i] / f << "\n"; } } ================================================ FILE: BOJ/3040.백설 공주와 일곱 난쟁이/6047198844.py ================================================ # 문제 # 아홉 난쟁이의 모자에 쓰여 있는 수가 주어졌을 때, 일곱 난쟁이를 찾는 프로그램을 작성하시오. (아홉 개의 수 중 합이 100이 되는 일곱 개의 수를 찾으시오) # # 입력 # 총 아홉개 줄에 1보다 크거나 같고 99보다 작거나 같은 자연수가 주어진다. 모든 숫자는 서로 다르다. 또, 항상 답이 유일한 경우만 입력으로 주어진다. # # 출력 # 일곱 난쟁이가 쓴 모자에 쓰여 있는 수를 한 줄에 하나씩 출력한다. from itertools import combinations dwalfs = [int(input()) for _ in range(9)] for combi in combinations(dwalfs, 7): if sum(combi) == 100: for dwalf in combi: print(dwalf) break ================================================ FILE: BOJ/3053.택시 기하학/6047198844.cpp ================================================ #define _USE_MATH_DEFINES #include #include using namespace std; int main() { double R; scanf("%lf", &R); printf("%.6lf\n%.6lf", (R * R * M_PI), (R * R * 2)); } ================================================ FILE: BOJ/3055.탈출/rockmiin.py ================================================ from collections import deque def bfs(q): global res tmp= deque() while q: x, y= q.popleft() if visited[x][y]==0 : visited[x][y]= 1 if adj[x][y]== '*': continue if x== end[0] and y==end[1]: # print(visited[x][y]); res= visited[x][y]; break; for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+ dx, y+ dy # 범위 내에 있고 방문하지 않고, ., D인 경우에 tmp에 넣어주고 return if 0<= tmp_x< r and 0<= tmp_y< c and not visited[tmp_x][tmp_y]: if adj[tmp_x][tmp_y]== '.' or adj[tmp_x][tmp_y]== 'D' and adj[x][y]!='*': tmp.append([tmp_x, tmp_y]) visited[tmp_x][tmp_y]= visited[x][y]+ 1 return tmp def water_bfs(q): tmp= deque() while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+ dx, y+ dy if 0<= tmp_x< r and 0<= tmp_y< c and adj[tmp_x][tmp_y]!= '*': if adj[tmp_x][tmp_y]!= 'D' and adj[tmp_x][tmp_y]!='X': tmp.append([tmp_x, tmp_y]) adj[tmp_x][tmp_y]= '*' return tmp r, c= map(int, input().split()) adj= [] res= 0 for i in range(r): adj.append(list(input())) water= deque() now= deque() for i in range(r): for j in range(c): if adj[i][j]== 'D': end= [i, j] elif adj[i][j]== 'S': now.append([i, j]) elif adj[i][j]== '*': water.append([i, j]) visited=[[0 for _ in range(c)] for _ in range(r)] while now: now= bfs(now) water= water_bfs(water) # print("n", now) # print("w", water) if res !=0: print(res-1); break; if res==0: print('KAKTUS') ================================================ FILE: BOJ/3085.사탕 게임/6047198844.py ================================================ from itertools import permutations N = int(input()) board = list() for _ in range(N): board.append(list(input())) cord = range(0, N) res = 0 def bom(board): # 빨간색은 C, 파란색은 P, 초록색은 Z, 노란색은 Y로 주어진다. cnt = 0 for row in board: for color in ('C', 'P', 'Z', 'Y'): tmp = 0 for element in row: if element == color: tmp += 1 else: cnt = max(cnt, tmp) tmp = 0 cnt = max(cnt, tmp) for column in zip(board): for color in ('C', 'P', 'Z', 'Y'): tmp = 0 for element in column: if element == color: tmp += 1 else: cnt = max(cnt, tmp) tmp = 0 cnt = max(cnt, tmp) return cnt for ay, ax in permutations(cord, 2): for by, bx in permutations(cord, 2): if board[ay][ax] != board[by][bx]: board[ay][ax], board[by][bx] = board[by][bx], board[ay][ax] res = max(res, bom(board)) board[ay][ax], board[by][bx] = board[by][bx], board[ay][ax] print(res) ================================================ FILE: BOJ/3135.라디오/6047198844.py ================================================ import sys A, B = map(int, sys.stdin.readline().split()) N = int(sys.stdin.readline()) res = abs(A-B) for _ in range(N): i = int(sys.stdin.readline()) res = min(abs(B-i)+1, res) print(res) ================================================ FILE: BOJ/3176.도로 네트워크/6047198844.py ================================================ # 문제 # N개의 도시와 그 도시를 연결하는 N-1개의 도로로 이루어진 도로 네트워크가 있다. # # 모든 도시의 쌍에는 그 도시를 연결하는 유일한 경로가 있고, 각 도로의 길이는 입력으로 주어진다. # # 총 K개의 도시 쌍이 주어진다. 이때, 두 도시를 연결하는 경로 상에서 가장 짧은 도로의 길이와 가장 긴 도로의 길이를 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 N이 주어진다. (2 ≤ N ≤ 100,000) # # 다음 N-1개 줄에는 도로를 나타내는 세 정수 A, B, C가 주어진다. A와 B사이에 길이가 C인 도로가 있다는 뜻이다. 도로의 길이는 1,000,000보다 작거나 같은 양의 정수이다. # # 다음 줄에는 K가 주어진다. (1 ≤ K ≤ 100,000) # # 다음 K개 줄에는 서로 다른 두 자연수 D와 E가 주어진다. D와 E를 연결하는 경로에서 가장 짧은 도로의 길이와 가장 긴 도로의 길이를 구해서 출력하면 된다. # # 출력 # 총 K개 줄에 D와 E를 연결하는 경로에서 가장 짧은 도로의 길이와 가장 긴 도로의 길이를 출력한다. import math import sys from collections import defaultdict, deque LOG = 20 N = int(sys.stdin.readline()) PV = [[0] * LOG for _ in range(N + 1)] PC = [[(math.inf, -math.inf)] * LOG for _ in range(N + 1)] D = [0] * (N + 1) edges = defaultdict(list) for _ in range(N - 1): A, B, C = map(int, sys.stdin.readline().split()) edges[A].append((B, C)) edges[B].append((A, C)) def make_tree(root): visited = set() visited.add(root) Q = deque() Q.append(root) depth = 0 while Q: depth += 1 for _ in range(len(Q)): V = Q.popleft() for W, C in edges[V]: if W not in visited: visited.add(W) Q.append(W) PV[W][0] = V PC[W][0] = (C, C) D[W] = depth make_tree(1) for i in range(1, LOG): for W in range(1, N + 1): PV[W][i] = PV[PV[W][i - 1]][i - 1] mina, maxa = PC[PV[W][i - 1]][i - 1] minb, maxb = PC[W][i - 1] PC[W][i] = min(mina, minb), max(maxa, maxb) def LCA(A, B): # B가 항상 더 깊도록한다. if D[A] > D[B]: A, B = B, A MNA, MXA = math.inf, -math.inf MNB, MXB = math.inf, -math.inf # 본래 정점. for i in range(LOG - 1, -1, -1): if D[B] - D[A] >= 1 << i: MNB, MXB = min(PC[B][i][0], MNB), max(PC[B][i][1], MXB) B = PV[B][i] if A != B: # 높이가 같다. 최소 부모의 위치를 찾자. for i in range(LOG - 1, -1, -1): if PV[A][i] != PV[B][i]: MNA, MXA = min(PC[A][i][0], MNA), max(PC[A][i][1], MXA) MNB, MXB = min(PC[B][i][0], MNB), max(PC[B][i][1], MXB) A = PV[A][i] B = PV[B][i] MNA, MXA = min(PC[A][0][0], MNA), max(PC[A][0][1], MXA) MNB, MXB = min(PC[B][i][0], MNB), max(PC[B][i][1], MXB) print(min(MNA, MNB), max(MXA, MXB)) else: print(MNB, MXB) K = int(sys.stdin.readline()) for _ in range(K): q, w = map(int, sys.stdin.readline().split()) LCA(q, w) ================================================ FILE: BOJ/3182.한동이는 공부가 하기 싫어!/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/3182 한동이는 공부가 하기 싫어! [풀이] 1. 인덱스를 맞춰주기 위해 입력값 - 1을 리스트에 저장 2. 각자 연결되는 사람 수를 저장하기 위한 cost 리스트 3. 모든 사람을 기준으로 한사람씩 연결되는 사람수를 계산하기 위한 반복문 ''' n = int(input()) lst = [int(input())-1 for _ in range(n)] cost = [0] * n for idx in range(n): stack = [idx] visited = [0] * n visited[idx] = 1 while stack: src = stack.pop() dst = lst[src] if not visited[dst]: visited[dst] = 1 stack.append(dst) cost[idx] += 1 print(cost.index(max(cost))+1) ================================================ FILE: BOJ/3190.뱀/rockmiin.py ================================================ n= int(input()) k= int(input()) apple=[list(map(int, input().split())) for _ in range(k)] # (1, 1)에는 사과가 없음 l= int(input()) dir_change= [input().split() for _ in range(l)] snake= [[0, 0]] dir= 'R' board=[[0]*n for _ in range(n)] directions= ['R', 'L', 'U', 'D'] d= [[0, 1], [0, -1], [-1, 0], [1, 0]] cnt= 0 x, y= 0, 0 for a, b in apple: board[a-1][b-1]= 2 while True: cnt+=1 # 방향 전환 후 전진 for i in range(len(directions)): if dir == directions[i]: tx, ty = x + d[i][0], y + d[i][1] if 0 <= tx < n and 0 <= ty < n and board[tx][ty] != 1: if board[tx][ty]==2: # print([tx, ty], "apple") snake.append([tx, ty]); board[tx][ty] = 1 apple.pop(0) else: px, py = snake.pop(0) snake.append([tx, ty]) board[tx][ty] = 1 board[px][py] = 0 else: break; x, y = tx, ty # print(snake) # print(cnt, dir) # for i in board: # print(i) # print() # 방향 전환 if dir_change != [] and cnt== int(dir_change[0][0]): if dir=='R': if dir_change[0][1]== 'L': dir='U' else: dir='D' elif dir=='L': if dir_change[0][1]== 'L': dir='D' else: dir='U' elif dir=='U': if dir_change[0][1]=='L': dir='L' else: dir= 'R' elif dir=='D': if dir_change[0][1]=='L': dir='R' else: dir= 'L' dir_change.pop(0) print(cnt) ================================================ FILE: BOJ/3273.두 수의 합/6047198844.py ================================================ n = int(input()) LIST = list(map(int, input().split())) LIST.sort() x = int(input()) begin, end = 0, len(LIST) - 1 res = 0 while begin < end: m1, m2 = LIST[begin], LIST[end] sum = m1 + m2 if sum < x: begin += 1 elif sum > x: end -= 1 else: while m1 == LIST[begin]: begin += 1 res += 1 while m2 == LIST[end]: end -= 1 res += 1 res -= 1 print(res) ================================================ FILE: BOJ/3980.선발 명단/6047198844.py ================================================ # 11명의 선수가 0 ~ 100 import sys input = sys.stdin.readline def solve(y, total, memo): if y == 11: return total answer = 0 for x in range(11): if memo[x]: continue if players[y][x] == 0: continue total += players[y][x] memo[x] = True answer = max(answer, solve(y + 1, total, memo)) total -= players[y][x] memo[x] = False return answer C = int(input()) for _ in range(C): players = [list(map(int, input().split())) for _ in range(11)] memo = [False for _ in range(11)] print(solve(0, 0, memo)) ================================================ FILE: BOJ/3986.좋은 단어/6047198844.py ================================================ def is_good_word(word) -> bool: stack = [] for char in word: if stack and stack[-1] == char: stack.pop() else: stack.append(char) return not bool(stack) N = int(input()) res = 0 for _ in range(N): if is_good_word(input()): res += 1 print(res) ================================================ FILE: BOJ/4101.크냐?/6047198844.py ================================================ import sys while True: A, B = map(int, sys.stdin.readline().split()) if A == B == 0: break if A > B: print("Yes") else: print("No") ================================================ FILE: BOJ/4150.피보나치 수 7/sangmandu.py ================================================ n = int(input()) a, b = 0, 1 for _ in range(n): a, b = b, a+b print(a) ================================================ FILE: BOJ/4195.친구 네트워크/6047198844.py ================================================ import sys def union(A, B): PA = find(A) PB = find(B) if PA != PB: P[PB] = PA N[PA] += N[PB] return N[PA] def find(A): if P[A] == A: return P[A] P[A] = find(P[A]) return P[A] T = int(sys.stdin.readline()) for _ in range(T): F = int(sys.stdin.readline()) P = {} N = {} for _ in range(F): A, B = sys.stdin.readline().split() if A not in P: P[A] = A N[A] = 1 if B not in P: P[B] = B N[B] = 1 print(union(A, B)) ================================================ FILE: BOJ/4195.친구네트워크/dosimpact.py ================================================ import sys sys.setrecursionlimit(10**6) input = sys.stdin.readline T = int(input()) for _ in range(T): F = int(input()) names = dict() names_cnt = 0 # 이름 > 번호로 변경 parent = [i for i in range(F*2+1)] childNum = [1 for i in range(F*2+1)] def getNumber(name: str): global names_cnt if name in names: return names[name] else: names[name] = names_cnt names_cnt += 1 return names[name] def getP(x: int): if parent[x] == x: return x parent[x] = getP(parent[x]) return parent[x] def union(x: int, y: int): px, py = getP(x), getP(y) if px == py: return if px > py: parent[px] = py childNum[py] += childNum[px] else: parent[py] = px childNum[px] += childNum[py] for _ in range(F): u, v = input().strip().split() un, vn = getNumber(u), getNumber(v) union(un, vn) pn = getP(un) print(childNum[pn]) # print(f"childNum : {childNum} u,v ={u} {v} , un vn = {un} {vn} ") """ 1 6 Fred Barney Betty Wilma Barney Betty Fred Barney Barney Betty Betty Wilma """ ================================================ FILE: BOJ/4358.생태학/6047198844.py ================================================ # 문제 # 미국 전역의 나무들이 주어졌을 때, 각 종이 전체에서 몇 %를 차지하는지 구하는 프로그램을 만들어야 한다. # # 입력 # 프로그램은 여러 줄로 이루어져 있으며, 한 줄에 하나의 나무 종 이름이 주어진다. 어떤 종 이름도 30글자를 넘지 않으며, 입력에는 최대 10,000개의 종이 주어지고 최대 1,000,000그루의 나무가 주어진다. # # 출력 # 주어진 각 종의 이름을 사전순으로 출력하고, 그 종이 차지하는 비율을 백분율로 소수점 4째자리까지 반올림해 함께 출력한다. import sys from collections import Counter trees = sys.stdin.readlines() N = len(trees) trees = sorted(Counter(trees).items()) for tree, counter in trees: print(tree.rstrip(), "%0.4f" % (counter/N*100)) ================================================ FILE: BOJ/4386.별자리 만들기/6047198844.py ================================================ import heapq import sys sys.setrecursionlimit(10 ** 7) def union(A, B): PA = find(A) PB = find(B) if PA == PB: return P[PB] = PA def find(A): if P[A] == -1: return A P[A] = find(P[A]) return P[A] n = int(sys.stdin.readline()) P = [-1 for _ in range(n)] V = [] for _ in range(n): x, y = map(float, sys.stdin.readline().split()) V.append((x, y)) Q = [] for i in range(n): for j in range(i + 1, n): ix, iy = V[i] jx, jy = V[j] heapq.heappush(Q, (((ix - jx) ** 2 + (iy - jy) ** 2) ** 0.5, i, j)) res = 0 while Q: cost, v, w = heapq.heappop(Q) pv = find(v) pw = find(w) if pv == pw: continue union(v, w) res += cost print(round(res, 2)) ================================================ FILE: BOJ/4485.녹색 옷 입은 애가 젤다지/6047198844.cpp ================================================ #include #include #include #include #include using namespace std; int arr[126][126]; int memo[126][126]; int dy[4] = { -1,+1,0,0 }; int dx[4] = { 0,0,-1,+1 }; bool range_check(int x, int y, int n) { if (x < 0 || x >= n) return false; if (y < 0 || y >= n) return false; return true; } int Dijkstra(int N) { priority_queue > > pq; pq.push({ -arr[0][0], { 0,0 } }); memo[0][0] = arr[0][0]; while (!pq.empty()) { int here_y = pq.top().second.first; int here_x = pq.top().second.second; int here_cost = -pq.top().first; pq.pop(); if (here_y == N - 1 && here_x == N - 1) return here_cost; for (int i = 0; i < 4; i++) { int there_y = here_y + dy[i]; int there_x = here_x + dx[i]; if (range_check(there_y, there_x,N)) { int there_cost = arr[there_y][there_x]; if (memo[there_y][there_x] == -1 || memo[there_y][there_x] > here_cost + there_cost) { memo[there_y][there_x] = here_cost + there_cost; pq.push({ -(here_cost + there_cost),{there_y,there_x} }); } } } } } int main() { int N = -1; for (int cnt = 1; N != 0; cnt++) { cin >> N; if (N == 0) return 0; memset(memo, -1, sizeof(memo)); for (int y = 0; y < N; y++) for (int x = 0; x < N; x++) cin >> arr[y][x]; cout << "Problem " << cnt << ": " << Dijkstra(N) << "\n"; } } ================================================ FILE: BOJ/4659.비밀번호 발음하기/6047198844.py ================================================ moem = ['a', 'e', 'i', 'o', 'u'] while True: line = input() if line == 'end': break moem_cnt = 0 jaem_cnt = 0 for i in range(len(line)): if i > 1 and line[i] == line[i-1] and not (line[i] == 'e' or line[i] == 'o'): print(f'<{line}> is not acceptable') break if line[i] in moem: moem_cnt += 1 jaem_cnt = 0 else: moem_cnt = 0 jaem_cnt += 1 if moem_cnt == 3 or jaem_cnt == 3: print(f'<{line}> is not acceptable') break else: for m in moem: if m in line: print(f'<{line}> is acceptable') break else: print(f'<{line}> is not acceptable') ================================================ FILE: BOJ/4690.완전 세제곱 /6047198844.py ================================================ from itertools import combinations res = [] for b, c, d in combinations(range(1,101),3): a = (b ** 2 + c ** 2 + d ** 2) ** (0.5) if 100 >= a == int(a): res.append((int(a), b, c, d)) res.sort() for a, b, c, d in res: print(f'Cube = {a}, Triple = ({b},{c},{d})') ================================================ FILE: BOJ/4796.캠핑/6047198844.py ================================================ import sys i = 0 while True: i += 1 L, P, V = map(int, sys.stdin.readline().split()) if L == 0 and P == 0 and V == 0: break print('Case {}: {}'.format(i, (V // P) * L + min(V % P, L))) ================================================ FILE: BOJ/4803.트리/6047198844.py ================================================ # 문제 # 그래프는 정점과 간선으로 이루어져 있다. 두 정점 사이에 경로가 있다면, 두 정점은 연결되어 있다고 한다. # 연결 요소는 모든 정점이 서로 연결되어 있는 정점의 부분집합이다. 그래프는 하나 또는 그 이상의 연결 요소로 이루어져 있다. # # 트리는 사이클이 없는 연결 요소이다. 트리에는 여러 성질이 있다. 예를 들어, 트리는 정점이 n개, 간선이 n-1개 있다. 또, 임의의 두 정점에 대해서 경로가 유일하다. # # 그래프가 주어졌을 때, 트리의 개수를 세는 프로그램을 작성하시오. # # 입력 # 입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 n ≤ 500과 m ≤ n(n-1)/2을 만족하는 정점의 개수 n과 간선의 개수 m이 주어진다. # 다음 m개의 줄에는 간선을 나타내는 두 개의 정수가 주어진다. 같은 간선은 여러 번 주어지지 않는다. 정점은 1번부터 n번까지 번호가 매겨져 있다. 입력의 마지막 줄에는 0이 두 개 주어진다. # # 출력 # 입력으로 주어진 그래프에 트리가 없다면 "No trees."를, 한 개라면 "There is one tree."를, T개(T > 1)라면 "A forest of T trees."를 테스트 케이스 번호와 함께 출력한다. import sys INF = 987654321 # i 와 j 의 부모를 합친다. # 이미 합쳐져 있는 경우 부모가 -INF 이 된다. def union(i, j): pi = find(i) pj = find(j) if pi == -INF or pj == -INF: if pi != -INF: p[pi] = -INF if pj != -INF: p[pj] = -INF return if pi == pj: p[pi] = -INF p[pj] = -INF return p[pj] = pi # i 의 부모를 찾는다. def find(i): if i == -INF or p[i] == -1: return i p[i] = find(p[i]) return p[i] case = 1 while True: n, m = map(int, sys.stdin.readline().split()) if n == 0 and m == 0: break p = [-1 for _ in range(n + 1)] edges = [tuple(map(int, sys.stdin.readline().split())) for _ in range(m)] # 중복이 있는 트리는 -INF 로 정의한다. for v, w in edges: union(v, w) tree_cnt = 0 for i in range(1, n + 1): if p[i] == -1: tree_cnt += 1 print("Case {}: ".format(case), end='') if tree_cnt == 0: print("No trees.") elif tree_cnt == 1: print("There is one tree.") else: print("A forest of {} trees.".format(tree_cnt)) case += 1 ================================================ FILE: BOJ/4948.베르트랑 공준/6047198844.cpp ================================================ #include #include using namespace std; bool check[246913]; void Sieve() { for (int i = 2; i <= 123456*2; i++) { if (!check[i]) { for (int j = i+i; j <= 123456*2; j += i) { check[j] = true; } } } } int Count(int n) { int res = 0; for (int i = n+1; i <= 2*n; i++) if(!check[i]) res++; return res; } int main() { Sieve(); int num; while (1) { cin >> num; if (!num) break; cout << Count(num) << "\n"; } } ================================================ FILE: BOJ/4963.섬의 개수/rockmiin.py ================================================ from collections import deque import sys def bfs(v): q= deque([v]) # print(v) while q: x, y= q.popleft() tmp= [[1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]] for tmp_x, tmp_y in tmp: dx, dy= x+tmp_x, y+tmp_y if 0<=dx=1 and not visited[x-D]: # print("D", x-D) q.append(x-D) visited[x-D]= visited[x]+ 1 return 'use the stairs' F, S, G, U, D= map(int, input().split()) visited= [0]* (F+1) print(bfs(S)) ================================================ FILE: BOJ/5014.스타트링크/6047198844.cpp ================================================ /* 강호는 코딩 교육을 하는 스타트업 스타트링크에 지원했다. 오늘은 강호의 면접날이다. 하지만, 늦잠을 잔 강호는 스타트링크가 있는 건물에 늦게 도착하고 말았다. 스타트링크는 총 F층으로 이루어진 고층 건물에 사무실이 있고, 스타트링크가 있는 곳의 위치는 G층이다. 강호가 지금 있는 곳은 S층이고, 이제 엘리베이터를 타고 G층으로 이동하려고 한다. 보통 엘리베이터에는 어떤 층으로 이동할 수 있는 버튼이 있지만, 강호가 탄 엘리베이터는 버튼이 2개밖에 없다. U버튼은 위로 U층을 가는 버튼, D버튼은 아래로 D층을 가는 버튼이다. (만약, U층 위, 또는 D층 아래에 해당하는 층이 없을 때는, 엘리베이터는 움직이지 않는다) 강호가 G층에 도착하려면, 버튼을 적어도 몇 번 눌러야 하는지 구하는 프로그램을 작성하시오. 만약, 엘리베이터를 이용해서 G층에 갈 수 없다면, "use the stairs"를 출력한다. base case queue에 값이 없는 경우 -> use the stairs G에 도착한 경우 -> 횟수 출력 특정 층 도착 -> 방문처리 완전탐색으로 풀수있는가? 10! = 약 300만. 300만을 넘지 않는다. 최고 층수가 100만이므로. */ #include #include using namespace std; bool check[1000001]; int brute_force_bfs(int F, int S, int G, int U, int D) { int res = 0; if (S == G) return res; queue q; q.push(S); check[S] = true; while (!q.empty()) { ++res; int size = q.size(); while (size--) { int current_floor = q.front(); q.pop(); int up_stairs = current_floor + U; int down_stairs = current_floor - D; if ((up_stairs == G) || (down_stairs == G)) return res; if ((up_stairs <= F)&&!check[up_stairs]){ q.push(up_stairs); check[up_stairs] = true; } if (down_stairs >= 1 && !check[down_stairs]){ q.push(down_stairs); check[down_stairs] = true; } } } return -1; } int main() { //총 F층 //스타트링크가 있는 위치 G층 // 강호가 있는 층 S층 // U버튼 위로 U층을 가는 버튼 // D버튼 아래로 D층을 가는버튼 int F, S, G, U, D; cin >> F >> S >> G >> U >> D; int res; res = brute_force_bfs(F, S, G, U, D); if (res>=0) cout << res; else cout << "use the stairs"; } ================================================ FILE: BOJ/5086.배수와 약수/6047198844.cpp ================================================ #include #include using namespace std; int main() { int N, M, K; cin >> N >> M; vector> A(N, vector(M)); for (int y = 0; y < N; y++) for (int x = 0; x < M; x++) cin >> A[y][x]; cin >> M >> K; vector> B(M, vector(K)); for (int y = 0; y < M; y++) for (int x = 0; x < K; x++) cin >> B[y][x]; for (int y = 0; y < N; y++) { for (int x = 0; x < K; x++) { int sum = 0; for (int z = 0; z < M; z++) sum += A[y][z] * B[z][x]; cout << sum << " "; } cout << "\n"; } } ``` ================================================ FILE: BOJ/5337.웰컴/6047198844.py ================================================ print('. . .') print('| | _ | _. _ ._ _ _') print('|/\|(/.|(_.(_)[ | )(/.') ================================================ FILE: BOJ/5338.마이크로소프트 로고/6047198844.py ================================================ print(" _.-;;-._") print("'-..-'| || |") print("'-..-'|_.-;;-._|") print("'-..-'| || |") print("'-..-'|_.-''-._|") ================================================ FILE: BOJ/5430.AC/6047198844.cpp ================================================ ================================================ FILE: BOJ/5522.카드 게임/6047198844.py ================================================ print(sum([int(input()) for _ in range(5)])) ================================================ FILE: BOJ/5532.방학 숙제/6047198844.py ================================================ import math L = int(input()) A = int(input()) B = int(input()) C = int(input()) D = int(input()) print(L - max(math.ceil(A/C), math.ceil(B/D))) ================================================ FILE: BOJ/5535.간판/6047198844.py ================================================ # 문제 # 편의점에는 이전 주인이 버리고 간 오래된 간판이 N개 있다. 상근이는 오래된 간판에서 일부 문자를 지워 새로운 간판을 만들려고 한다. # - 남은 문자열이 편의점 이름이어야 하고, 남은 문자가 모두 일정한 간격으로 떨어져 있어야 한다. # - 간판을 자르거나 붙일수는 없다. # - 하나의 오래된 간판에서 만들 수 있는 방법이 여러 개인 경우에도 만들 수 있는 간판은 하나이다. # # 입력 # 첫째 줄에 오래된 간판의 수 N이 주어진다. (1 ≤ N ≤ 100) 둘째 줄에는 상근이가 새로 연 편의점의 이름이 주어진다. # 이름은 알파벳 소문자로만 이루어져 있고, 길이는 3자 이상, 25자 이하이다. 다음 N개 줄에는 이전 주인이 버리고 간 간판에 쓰여 있는 문자가 주어진다. 이 간판에 쓰여 있는 문자는 알파벳 소문자이고, 길이는 1자 이상 100자 이하이다. # # 출력 # 첫째 줄에 상근이가 만들 수 있는 간판의 수를 출력한다. import sys # 입력 N = int(sys.stdin.readline()) new_signboard = sys.stdin.readline().rstrip() old_signboards = [sys.stdin.readline().rstrip() for _ in range(N)] res = 0 def is_possible_to_make(new_signboard, old_signboard): for start_idx in range(len(old_signboard)): for d in range(1, len(old_signboard)): # 끝항이 범위를 넘어서는가? end_idx = start_idx + d * (len(new_signboard) - 1) board = "" if len(old_signboard) <= end_idx: break for idx in range(start_idx, end_idx + 1, d): board += old_signboard[idx] if board == new_signboard: return True return False for old_signboard in old_signboards: # 초항 + d * (n-1) res += int(is_possible_to_make(new_signboard, old_signboard)) print(res) ================================================ FILE: BOJ/5554.심부름 가는 길/6047198844.py ================================================ S = 0 for _ in range(4): S += int(input()) print(S // 60) print(S % 60) ================================================ FILE: BOJ/5557.1학년/6047198844.cpp ================================================ #include #include #include using namespace std; long long cache[100][21]; int arr[100]; int N; long long dp(int idx, int sum) { if (sum < 0 || sum>20) return 0; if (idx == N - 2) return sum == arr[N - 1]; long long& res = cache[idx][sum]; if (res != -1) return res; res = 0; res = dp(idx + 1, sum + arr[idx + 1]) + dp(idx + 1, sum - arr[idx + 1]); return res; } int main() { cin >> N; for (int i = 0; i < N; i++) for (int j = 0; j < 21; j++) cache[i][j] = -1; for (int i = 0; i < N; i++) cin >> arr[i]; cout << dp(0, arr[0]); } ================================================ FILE: BOJ/5585.거스름 돈/rockmiin_5585.py ================================================ x= int(input()) cnt=0 x= 1000-x while(x>0): if x >= 500: x=x-500 elif x >= 100: x=x-100 elif x >= 50: x=x-50 elif x >= 10: x=x-10 elif x >= 5: x=x-5 elif x >= 1: x=x-1 else: break; cnt+=1 print(cnt) ================================================ FILE: BOJ/5596.시험 점수/6047198844.py ================================================ result = -1 for _ in range(2): arr = list(map(int, input().split())) result = max(result, sum(arr)) print(result) ================================================ FILE: BOJ/5597.과제 안 내신 분..?/6047198844.py ================================================ attendance_numbers = set(range(1, 31)) for _ in range(28): attendance_numbers.remove(int(input())) for absent in sorted(attendance_numbers): print(absent) ================================================ FILE: BOJ/5618.공약수/6047198844.py ================================================ def gcd(a, b): while b > 0: a, b = b, a % b return a n = int(input()) nums = list(map(int, input().split())) gcd = gcd(nums[0], nums[1]) if n == 2 else gcd(gcd(nums[0], nums[1]), nums[2]) for i in range(1, gcd + 1): if gcd % i == 0: print(i) ================================================ FILE: BOJ/5635.생일/6047198844.py ================================================ import datetime as dt import heapq from collections import defaultdict N = int(input()) arr = list() for _ in range(N): name, *date = input().split() strptime = dt.datetime.strptime(' '.join(date), "%d %m %Y") heapq.heappush(arr, (strptime, name)) print(heapq.nlargest(1, arr)[0][1]) print(heapq.nsmallest(1, arr)[0][1]) ''' 5 Mickey 1 10 1991 Alice 30 12 1990 Tom 15 8 1993 Jerry 18 9 1990 Garfield 20 9 1990 ''' ================================================ FILE: BOJ/5639.이진 검색 트리/6047198844.cpp ================================================ #include #include #include #include using namespace std; vector slice(vector &vt, int a, int b) { vector svt(vt.begin() + a, vt.begin() + b); return svt; } //후위 순회한다. void postOrder(vector preOrder) { if (!preOrder.size()) return; int root = preOrder[0]; int idx = upper_bound(preOrder.begin(), preOrder.end(), root) - preOrder.begin(); postOrder(slice(preOrder, 1, idx)); postOrder(slice(preOrder, idx, preOrder.size())); cout << root << "\n"; } int main() { vector preOrder; string num; while (getline(cin, num)) preOrder.push_back(stoi(num)); postOrder(preOrder); } ================================================ FILE: BOJ/5671.호텔 방 번호/6047198844.py ================================================ import sys from collections import Counter while True: try: N, M = map(int, sys.stdin.readline().split()) cnt = 0 for i in range(N, M + 1): cnt += Counter(str(i)).most_common()[0][1] == 1 print(cnt) except: break ================================================ FILE: BOJ/5710.전기 요금/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/5710 전기 요금 [풀이] 1. watt를 fee로 바꾸는 함수 생성 2. fee를 watt로 바꾸는 함수 생성 3. 총 사용량 A를 금액으로 변경 4. 이진 탐색으로 만족하는 값 찾기 ''' def watt_fee(watt): return sum([a*b for a, b in zip([watt-l for l in [0, 100, 10000, 1000000]], [2, 1, 2, 2]) if a > 0]) def fee_watt(fee): ret = ([(b, b*c) for a, (b, c) in zip([fee-l for l in [0, 200, 29900, 4979900]], [(2, 0), (1, 100), (2, 10000), (2, 1000000)]) if a > 0]) a, b = list(zip(*ret)) return (fee+sum(b)) // sum(a) while True: A, B = map(int, input().split()) if A == B == 0: break total = fee_watt(A) left, right = 0, total while True: mid = (left + right) // 2 if watt_fee(total-mid) - watt_fee(mid) > B: left = mid + 1 elif watt_fee(total-mid) - watt_fee(mid) < B: right = mid - 1 else: break print(watt_fee(mid)) ================================================ FILE: BOJ/5719.거의 최단 경로/6047198844.py ================================================ import heapq import math import sys from collections import defaultdict, deque def dijkstra(): PQ = [] dist[S] = 0 heapq.heappush(PQ, (dist[S], S)) while PQ: P, V = heapq.heappop(PQ) # dist 는 최단거리임. P가 최단거리가 아니면 아래 과정을 수행하지 않음. if dist[V] != P: continue for W in edges[V]: # S -> V(최단거리 보장) + V -> W (연결거리) 갱신? if dist[W] > dist[V] + edges[V][W]: dist[W] = dist[V] + edges[V][W] heapq.heappush(PQ, (dist[W], W)) def track(): remove = [] Q = deque() Q.append(D) while Q: V = Q.popleft() if V == S: continue for pre_V, pre_P in r_edges[V]: if dist[pre_V] + edges[pre_V][V] == dist[V]: if (pre_V, V) not in remove: Q.append(pre_V) remove.append((pre_V, V)) return remove while True: N, M = map(int, sys.stdin.readline().split()) if N == 0 and M == 0: break # S -> D S, D = map(int, sys.stdin.readline().split()) edges = [dict() for _ in range(N)] r_edges = [list() for _ in range(N)] for _ in range(M): U, V, P = map(int, sys.stdin.readline().split()) # U -> V : 비용 P edges[U][V] = P r_edges[V].append((U, P)) dist = [math.inf for _ in range(N)] dijkstra() remove = track() for U, V in remove: del edges[U][V] dist = [math.inf for _ in range(N)] dijkstra() if dist[D] == math.inf: print(-1) else: print(dist[D]) ================================================ FILE: BOJ/5766.할아버지는 유명해!/6047198844.py ================================================ from collections import Counter while True: N, M = map(int, input().split()) if N == M == 0: break res = [] for _ in range(N): res += list(map(int, input().split())) ranks = Counter(res).most_common() ranks.sort(key=lambda x: (-x[1], x[0])) second_rank_value = ranks[1][1] i = 1 while i < len(ranks) and ranks[i][1] == second_rank_value: print(ranks[i][0], end=' ') i += 1 print() ================================================ FILE: BOJ/5800.성적 통계/6047198844.py ================================================ import math import sys K = int(input()) for i in range(1, K + 1): N, *scores = map(int, sys.stdin.readline().split()) scores.sort(reverse=True) largest_gap = 0 for j in range(len(scores) - 1): largest_gap = max(largest_gap, scores[j] - scores[j+1]) print(f'Class {i}') print(f'Max {max(scores)}, Min {min(scores)}, Largest gap {largest_gap}') ================================================ FILE: BOJ/5883.아이폰 9S/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) people = list() for _ in range(N): people.append(sys.stdin.readline().rstrip()) res = 0 for removed_person in set(people): #person을 제거하자. -> 무시해보자. prev = None count = 0 for person in people: #그냥 무시 if person == removed_person: continue #이전과 같으면 count 올린다. if not prev or prev == person: count += 1 else: res = max(res, count) count = 1 prev = person res = max(res, count) print(res) ================================================ FILE: BOJ/5904.Moo 게임/6047198844.py ================================================ # 문제 # Moo 수열은 다음과 같은 방법으로 재귀적으로 만들 수 있다. # 먼저, S(0)을 길이가 3인 수열 "m o o"이라고 하자. # k >= 1 , S(k) = S(k-1) + o가 k+2개인 수열 "m o ... o" + S(k-1) # S(0) = "m o o" # S(1) = "m o o m o o o m o o" # S(2) = "m o o m o o o m o o m o o o o m o o m o o o m o o" # S(3) = "m o o m o o o m o o m o o o o m o o m o o o m o o m o o o o o m o o m o o o m o o m o o o o m o o m o o o m o o" # 위와 같은 식으로 만들면, 길이가 무한대인 문자열을 만들 수 있으며, 그 수열을 Moo 수열이라고 한다. # N이 주어졌을 때, Moo 수열의 N번째 글자를 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 N (1 ≤ N ≤ 10^9)이 주어진다. # # 출력 # N번째 글자를 출력한다. # func(N, K, length) # N : N번째 글자 # K : 현재 수열의 번호 # length : 현재 수열의 길이 def func(N, K, length): # m o o 만 남았을떄. if N <= 3: return ("moo"[N - 1]) next_length = length * 2 + K + 3 # 확장한다. if next_length < N: return func(N, K + 1, next_length) # 다음 Moo 의 범위에 속해있는지 확인한다. if length + 1 <= N <= length + K + 3: return "m" if N == length + 1 else "o" # 재귀를 처음부터 다시 시작한다. N의 범위는 줄어든다. return func(N - (length + K + 3), 1, 3) print(func(int(input()), 1, 3)) ================================================ FILE: BOJ/6198.옥상 정원 꾸미기/ms9849.cpp ================================================ #include #include #include using namespace std; //monotone stack을 이용하여 풀이 int N,num; long long ans = 0; stack s; vector v; int main(void) { cin >> N; for(int i=0; i> num; v.push_back(num); } for(int i=0; i< N; i++) { // monotone stack을 만드는 과정. 내림차순으로 유지된다. while(!s.empty() && s.top() <= v[i]) s.pop(); s.push(v[i]); ans += s.size() - 1; /* monotone stack으로 만들면 현재 자신을 볼 수 있는 건물의 수만큼 stack에 쌓여있다. 이 때 자기 자신도 stack에 존재하므로 -1을 수행*/ } cout << ans; return 0; } ================================================ FILE: BOJ/6549.히스토그램에서 가장 큰 직사각형/sAp00n.py ================================================ from sys import stdin def sub_list(input_list): if len(input_list) == 1: return input_list[0] mid_idx = len(input_list) // 2 sub_max = max(sub_list(input_list[:mid_idx]), sub_list(input_list[mid_idx:])) start, end = mid_idx - 1, mid_idx min_val = min(input_list[start], input_list[end]) mid_max = min_val * 2 # print(f'in : {input_list}') while 0 < start or end < len(input_list) - 1: # print(f'start:{start} end: {end} mid_max:{mid_max}') if start > 0: if end == len(input_list) - 1 or input_list[start - 1] >= input_list[end + 1]: start -= 1 min_val = min(min_val, input_list[start]) mid_max = max(mid_max, min_val * (end - (start - 1))) continue end += 1 min_val = min(min_val, input_list[end]) mid_max = max(mid_max, min_val * (end - (start - 1))) # print(f'sub_max:{sub_max} mid_max:{mid_idx}') return max(sub_max, mid_max) input_list = list(map(int, stdin.readline().split())) fst_letter = input_list[0] input_list = input_list[1:] while fst_letter != 0: print(sub_list(input_list)) input_list = list(map(int, stdin.readline().split())) fst_letter = input_list[0] input_list = input_list[1:] ================================================ FILE: BOJ/6550.부분 문자열/6047198844.py ================================================ # 문제 # 2개의 문자열 s와 t가 주어졌을 때 s가 t의 부분 문자열인지 판단하는 프로그램을 작성하라. # 부분 문자열을 가지고 있는지 판단하는 방법은 t에서 몇 개의 문자를 제거하고 이를 순서를 바꾸지 않고 합쳤을 경우 s가 되는 경우를 이야기 한다. # # 입력 # 입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 문자열 s 와 t가 빈칸을 사이에 두고 들어온다. s와 t의 길이는 10만을 넘지 않는다. # # 출력 # 입력된 s와 t의 순서대로 s가 t의 부분 문자열인 경우 Yes라 출력하고 아닐 경우 No라고 출력한다. import sys lines = sys.stdin.readlines() for line in lines: s, t = line.split() idx = 0 for char in t: if s[idx] == char: idx += 1 if idx == len(s): break print('Yes') if idx == len(s) else print('No') ================================================ FILE: BOJ/6800.Huffman Encoding/6047198844.cpp ================================================ #include #include using namespace std; int main() { int N; cin >> N; map mp; string word; string code; for (int i = 0; i < N; i++) { cin >> word >> code; mp[code] = word; } string encoded_code; string w; string res; cin >> encoded_code; for (char c : encoded_code) { w += c; if (mp.find(w) != mp.end()) { res += mp[w]; w = ""; } } cout << res; } ================================================ FILE: BOJ/7453.합이 0인 네 정수/6047198844.py ================================================ import sys from collections import defaultdict from itertools import product N = int(sys.stdin.readline()) arr = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] A, B, C, D = zip(*arr) table = dict() for i in A: for j in B: if i + j in table: table[i + j] += 1 else: table[i + j] = 1 res = 0 for i in C: for j in D: if -(i + j) in table: res += table[-(i + j)] print(res) ================================================ FILE: BOJ/7507.올림픽 경기/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/7507 올림픽 경기 [풀이] 1. 날짜 순으로 정렬 그리고 끝나는 시간으로 정렬한다. 2. 내가 보고 있는 프로그램이 다음에 위치하는 프로그램과 겹칠 때 => 내가 보고 있는 프로그램이 먼저 끝난다(정렬을 그렇게 했으니까) => 이후에 프로그램을 하나 더 볼 가능성이 높다 => 따라서 그대로 pass 3. 내가 보고 있는 프로그램이 다음에 위치하는 프로그램보다 먼저 끝난다 => 볼 수 있는 프로그램 수를 하나 더 센다. ''' import sys input = sys.stdin.readline n = int(input()) for i in range(n): m = int(input()) games = sorted([list(map(int, input().split())) for _ in range(m)], key = lambda x : (x[0], x[2])) max_games = 0 cur_day = cur_ed = 0 for day, st, ed in games: if cur_ed <= st or cur_day != day: max_games += 1 cur_day, cur_ed = day, ed print(f"Scenario #{i+1}:\n{max_games}\n") ================================================ FILE: BOJ/7562.나이트의 이동/rockmiin.py ================================================ from collections import deque test_case= int(input()) move= [[2, 1], [2, -1], [-2, 1], [-2, -1], [1, 2], [1, -2], [-1, 2], [-1, -2]] def bfs(v): q= deque([v]) while q: x, y= q.popleft() if x== end_x and y== end_y: return visited[x][y] for dx, dy in move: tmp_x, tmp_y= x+ dx, y+ dy if 0<= tmp_x< n and 0<= tmp_y< n and not visited[tmp_x][tmp_y]: q.append([tmp_x, tmp_y]) visited[tmp_x][tmp_y]= visited[x][y]+1 for i in range(test_case): n= int(input()) start_x, start_y= map(int, input().split()) end_x, end_y= map(int, input().split()) visited=[[0 for _ in range(n)] for _ in range(n)] print(bfs([start_x, start_y])) # 각 test_case마다 변수들을 새로 지정해줘서 # depth와 방문 여부를 확인하는 visited 리스트를 생성해준다. # 종료 지점과 일치하는 좌표가 q에서 나오게 되면 depth를 리턴해주는 방식으로 구현 # 예제 입력 # 3 # 8 # 0 0 # 7 0 # 100 # 0 0 # 30 50 # 10 # 1 1 # 1 1 # # 예제 출력 # 5 # 28 # 0 ================================================ FILE: BOJ/7562.나이트의 이동/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/7562 나이트의 이동 [풀이] 1. 방문 여부를 조사하는 visited 배열을 l * l 크기로 선언 2. BFS로 풀 것이므로 stack과 save 생성 => 최단 거리를 구하는 문제기 때문에 BFS 3. 나이트가 이동할 수 있는 거리는 절댓값이 1과 2인 수의 조합이다. ''' n = int(input()) for _ in range(n): l = int(input()) y1, x1 = map(int, input().split()) y2, x2 = map(int, input().split()) visited = [[0] * l for _ in range(l)] visited[y1][x1] = 1 stack, save = [(y1, x1, 0)], [] while True: if not stack: stack, save = save, stack y, x, cnt = stack.pop() if y == y2 and x == x2: print(cnt) break for dy in [-2, -1, 1, 2]: for dx in [3-abs(dy), abs(dy)-3]: ny, nx = y+dy, x+dx if 0 <= ny < l and 0 <= nx < l and not visited[ny][nx]: visited[ny][nx] = 1 save.append((ny, nx, cnt+1)) ================================================ FILE: BOJ/7568.덩치/6047198844.cpp ================================================ #include #include using namespace std; int main() { int N; cin >> N; vector > hw; int weight, height; for (int i = 0; i < N; i++) { cin >> weight >> height; hw.push_back({ weight,height }); } for (int i = 0; i < N; i++) { int k = 1; for (int j = 0; j < N; j++) if (i != j && hw[i].first < hw[j].first && hw[i].second < hw[j].second) k++; cout << k << " "; } } ================================================ FILE: BOJ/7569.토마토/6047198844.py ================================================ # 문제 # 토마토는 아래의 그림과 같이 격자모양 상자의 칸에 하나씩 넣은 다음, 상자들을 수직으로 쌓아 올려서 창고에 보관한다. # 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. # 하나의 토마토에 인접한 곳은 위, 아래, 왼쪽, 오른쪽, 앞, 뒤 여섯 방향에 있는 토마토를 의미한다. # 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. # 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지 그 최소 일수를 알고 싶어 한다. # # 토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, # 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다. # # 입력 # 첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. # M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100, 1 ≤ H ≤ 100 이다. # # 둘째 줄부터는 가장 밑의 상자부터 가장 위의 상자까지에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 하나의 상자에 담긴 토마토의 정보가 주어진다. # 각 줄에는 상자 가로줄에 들어있는 토마토들의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0 은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다. 이러한 N개의 줄이 H번 반복하여 주어진다. # # 토마토가 하나 이상 있는 경우만 입력으로 주어진다. # # 출력 # 여러분은 토마토가 모두 익을 때까지 최소 며칠이 걸리는지를 계산해서 출력해야 한다. 만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, 토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다. # M : 가로 , N : 세로 , H : 높이 from collections import deque M, N, H = map(int, input().split()) # box[H][N][M] # 맨 아래층을 0이라고하자. box = [[] for _ in range(H)] for i in range(H): for j in range(N): box[i].append(list(map(int, input().split()))) # 정수 1은 익은 토마토, 정수 0 은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다. Q = deque([]) # Q 에는 익은 토마토의 좌표가 들어간다. for z in range(H): for y in range(N): for x in range(M): if box[z][y][x] == 1: Q.append((z, y, x)) day = -1 while Q: day += 1 for _ in range(len(Q)): # 익은 토마토들 wz, wy, wx = Q.popleft() for dz, dy, dx in (-1, 0, 0), (+1, 0, 0), (0, -1, 0), (0, +1, 0), (0, 0, -1), (0, 0, +1): nz, ny, nx = wz + dz, wy + dy, wx + dx if 0 <= nz < H and 0 <= ny < N and 0 <= nx < M and box[nz][ny][nx] == 0: box[nz][ny][nx] = 1 Q.append((nz, ny, nx)) # 익지않은 토마토가 있으면 -1 을 출력하고 익지않은 토마토가 없으면 day를 출력한다. # 익은 토마토만 있으면 True flag = True for z in range(H): for y in range(N): for x in range(M): if box[z][y][x] == 0: flag = False print(day) if flag else print(-1) ================================================ FILE: BOJ/7569.토마토/ms9849.cpp ================================================ #include #include using namespace std; typedef struct _Locate{ int z; int y; int x; } Locate; int map[102][102][102]; // H,N,M순으로 나타냄.. int M, N, H; int dirX[6] = { 1,-1,0,0,0,0 }; int dirY[6] = { 0,0,1,-1,0,0 }; int dirZ[6] = { 0,0,0,0,1,-1 }; int Min = 0; queue q; int check() { for (int i = 1; i <= H; i++) { for (int j = 1; j <= N; j++) { for (int k = 1; k <= M; k++) { if (map[i][j][k] == 0) return 1; } } } return 0; } int main(void) { cin >> M >> N >> H; for (int k = 1; k <= H; k++) { for (int j = 1; j <= N; j++) { for (int i = 1; i <= M; i++) { cin >> map[k][j][i]; if (map[k][j][i] == 1) q.push({ k,j,i }); } } } if (check() == 0) { //만약 모든 토마토가 이미 익은상태로 주어졌다면, cout << "0"; return 0; } while (!q.empty()) { Locate l = q.front(); q.pop(); for (int i = 0; i < 6; i++) { if (l.x + dirX[i] >= 1 && l.x + dirX[i] <= M && l.y + dirY[i] >= 1 && l.y + dirY[i] <= N && l.z + dirZ[i] >= 1 && l.z + dirZ[i] <= H) { // 막혀있는 장소인지, 방문한 정점인지 확인 if (map[l.z + dirZ[i]][l.y + dirY[i]][l.x + dirX[i]] == 0) { // 배열의 범위를 벗어나는지 확인 q.push({ l.z + dirZ[i] ,l.y + dirY[i], l.x + dirX[i]}); map[l.z + dirZ[i]][l.y + dirY[i]][l.x + dirX[i]] = map[l.z][l.y][l.x] + 1; if (map[l.z][l.y][l.x] + 1 > Min) Min = map[l.z][l.y][l.x] + 1; } } } } if (check() == 1) cout << "-1"; else cout << Min-1; return 0; } ================================================ FILE: BOJ/7569.토마토/rockmiin.py ================================================ from collections import deque move= [[1, 0, 0], [0, 1, 0], [-1, 0, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]] def bfs(q): while q: z, y, x= q.popleft() for dx, dy, dz in move: tx, ty, tz= x+ dx, y+ dy, z+ dz if 0<= tx< m and 0<= ty< n and 0<= tz< h: if adj[tz][ty][tx]==0 and not visited[tz][ty][tx]: q.append([tz, ty, tx]) adj[tz][ty][tx]= 1 visited[tz][ty][tx]= visited[z][y][x]+ 1 res= 0 for i in range(h): for j in range(n): for k in range(m): if adj[i][j][k]== 0: return -1 if visited[i][j][k]> res: res= visited[i][j][k] return res-1 m, n, h= map(int, input().split()) adj= [] visited = [[[0] * m for _ in range(n)] for _ in range(h)] for i in range(h): tmp= [] for j in range(n): tmp.append(list(map(int, input().split()))) adj.append(tmp) tomato= deque() cnt= 0 for i in range(h): for j in range(n): for k in range(m): if adj[i][j][k]==1: tomato.append([i, j, k]) visited[i][j][k]= 1 print(bfs(tomato)) ================================================ FILE: BOJ/7576.토마토/rockmiin.py ================================================ import sys from collections import deque def bfs(q): tmp= deque() # print(q) while q: x, y= q.popleft() for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: tmp_x, tmp_y= x+ dx, y+ dy if 0<=tmp_x 0: res += tree[index] index -= (index & -index) return res res = 0 for node in sys.stdin.readline().split(): res += query(N) - query(line1[node]) update(line1[node], 1) print(res) ================================================ FILE: BOJ/7579.앱/6047198844.py ================================================ import sys # M 목표 바이트. N, M = map(int, sys.stdin.readline().split()) # 메모리 m = [0] + list(map(int, sys.stdin.readline().split())) # 비용 c = [0] + list(map(int, sys.stdin.readline().split())) # memo 의 정의부터 세운다. # memo[i][cost] = cost의 비용을 지불한다고 가정했을때 i 번째까지의 어플까지 확보할수있는 최대 메모리값. # j 의 범위는 ? 비용의 합. 즉 최대 10000 total_cost = sum(c) res = total_cost memo = [[0 for _ in range(total_cost + 1)] for _ in range(N + 1)] for i in range(1, N + 1): for cost in range(total_cost + 1): # 현재 어플리케이션 i를 비활성화시 메모리를 얻는다. # 비활성화하게 되면 cost 를 주어야한다. # 현재 메모리값을 확보하려면 이전의 최적값을 알아야한다. 직전의 최적값에 현재 어플리케이션을 비활성화 해보자. # 활성화는 메모리를 오히려 잡아먹으니 하지 않는다. # 이전의 최적값은 memo[직전까지 확보한값][현재 지불하고자하는 비용 - 현재 어플리케이션의 비용] + 현재 어플리케이션으로 확보가능한 메모리 # 비용을 지불못하면 스킵. if cost < c[i]: memo[i][cost] = memo[i - 1][cost] # 비용을 지불, 비활성화 하고 메모리를 받는다. else: memo[i][cost] = max(memo[i - 1][cost], memo[i - 1][cost - c[i]] + m[i]) # 현재 확보한 메모리가 요구하는 메모리보다 크면 답을 교체한다. if M <= memo[i][cost]: res = min(res, cost) print(res) ================================================ FILE: BOJ/7662.이중 우선순위 큐/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/7662 이중 우선순위 큐 : minheap과 maxheap에서 pop하기 exist 배열을 둬서, minheap과 max ''' from sys import stdin import heapq as h def solution(k): exist = [0] * k min_h, max_h = [], [] for i in range(k): a, b = stdin.readline().split() if a == "I": h.heappush(min_h, (int(b), i)) h.heappush(max_h, (-int(b), i)) exist[i] = 1 continue if b == "-1": while min_h and not exist[min_h[0][1]]: h.heappop(min_h) if min_h: exist[min_h[0][1]] = 0 h.heappop(min_h) else: while max_h and not exist[max_h[0][1]]: h.heappop(max_h) if max_h: exist[max_h[0][1]] = 0 h.heappop(max_h) while min_h and not exist[min_h[0][1]]: h.heappop(min_h) while max_h and not exist[max_h[0][1]]: h.heappop(max_h) if min_h and max_h: print(-max_h[0][0], min_h[0][0]) else: print("EMPTY") T = int(stdin.readline()) for _ in range(T): k = int(stdin.readline()) solution(k) ''' ''' ================================================ FILE: BOJ/7785.회사에 있는 사람/6047198844.py ================================================ n = int(input()) people = set() for _ in range(n): name, log = input().split() if log == 'enter': people.add(name) elif name in people: people.remove(name) for person in sorted(people)[::-1]: print(person) ================================================ FILE: BOJ/8979.올림픽/6047198844.py ================================================ import sys N, K = map(int, sys.stdin.readline().split()) arr = list() table = dict() for _ in range(N): i, *j = map(int, sys.stdin.readline().split()) table[i] = j arr.append(j) arr.sort(reverse=True) print(arr.index(table[K]) + 1) ================================================ FILE: BOJ/9009.피보나치/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/9009 피보나치 [풀이] 1. 이 문제의 핵심 다음과 같다 1.1 모든 양의 정수는 하나 이상의 서로 다른 피보나치 수들의 합으로 나타낼 수 있다 => 문제에 제시된 조건이며 https://ko.wikiqube.net/wiki/Complete_sequence 에서 확인 가능하다 1.2 어떤수를 피보나치 수들로 표현할 때 가장 큰 피보나치를 사용하는 것이 적은 수의 피보나치를 사용할 수 있다는 것이다. => 왜일까? 2. 이 부분은 다음을 증명해야 한다. 2-1. 유일성 => 두개의 연속한 피보나치 수를 포함하지 않는 유일한 표현 방법이 존재한다 => https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem 에서 증명 2-2. 유일한 표현 방법이 최소이다 => 만약에 연속한 피보나치 수를 포함하는 방법이 최소라고 가정하자 => 그러면 연속한 피보나치 수는 또다른 피보나치수로 만들 수 있다 => 따라서 최소라고 정의한 가정에 모순이므로 유일한 표현 방법이 최소이다 ''' n = int(input()) for i in range(n): m = int(input()) fibo = [0, 1] idx = 0 while fibo[idx]+fibo[idx+1] <= m: fibo.append(fibo[idx]+fibo[idx+1]) idx += 1 total = m answer = [] for f in fibo[:0:-1]: if total >= f: total -= f answer.append(f) print(*answer[::-1]) ================================================ FILE: BOJ/9019.DSLR/6047198844.cpp ================================================ #include #include #include #include using namespace std; string BFS(int A, int B) { bool check[10000]; // 전역일때는 all false, 지역일때는 all true; fill_n(&check[0], 10000, false); queue > q; int target = B; string res_string = ""; q.push(make_pair(A, res_string)); check[A] = true; while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; i++) { int num = q.front().first; string bfs_string = q.front().second; q.pop(); int check_num[4] = { (2 * num) % 10000,(num - 1) < 0 ? 9999 : num - 1,(num % 1000) * 10 + (num / 1000),(num / 10) + (num % 10) * 1000 }; string commend_string[4] = { "D","S","L","R" }; for (int i = 0; i < 4; i++) { if (num == target) return bfs_string; if (!check[check_num[i]]) { check[check_num[i]] = true; q.push(make_pair(check_num[i], bfs_string + commend_string[i])); } } } } } int main() { int T; scanf("%d", &T); for (int i = 0; i < T; i++) { int A, B; cin >> A; cin >> B; cout << BFS(A, B) << "\n"; } } ================================================ FILE: BOJ/9019.DSLR/6047198844.py ================================================ import collections def D(N): return 2 * N % 10000 def S(N): return 9999 if N == 0 else N - 1 def L(N): return (N % 1000) * 10 + N // 1000 def R(N): return (N // 10) + (N % 10) * 1000 def bfs(A, B): if A == B: return 0 # (숫자, 버튼 경로) 저장 Q = collections.deque() Q.append((A, "")) # 발견한 숫자 저장. discovered = set() discovered.add(A) button_cnt = 0 while Q: button_cnt += 1 for _ in range(len(Q)): a, button_path = Q.popleft() for button, na in zip(('D', 'S', 'L', 'R'), (D(a), S(a), L(a), R(a))): if na in discovered: continue n_button_path = button_path + button if na == B: return n_button_path Q.append((na, n_button_path)) discovered.add(na) T = int(input()) for _ in range(T): A, B = map(int, input().split()) print(bfs(A, B)) ================================================ FILE: BOJ/9020.골드바흐의 추측/6047198844.cpp ================================================ #include #include #define GOLDMAX 10000 using namespace std; //true면 prime임. bool isPrime[10001]; void printPartition(int N) { int resPrime = 0; //차이를 저장 int resDif = -1; for (int i = 1; i <= N; i++) { if (isPrime[i] && isPrime[N - i]) { int dif = abs(N - 2 * i); if (resDif == -1||resDif > dif) { resDif = dif; resPrime = i; } } } int firstOne = resPrime; int secondOne = N - resPrime; if (firstOne > secondOne) swap(firstOne, secondOne); cout << firstOne << " " << secondOne << "\n"; } void doSieve() { fill_n(isPrime, 10000, true); isPrime[1] = false; for (int i = 2; i <= 10000; i++) { if (isPrime[i]) for (int j = i + i; j < 10000; j += i) isPrime[j] = false; } } int main() { int T; cin >> T; doSieve(); while (T--) { int N; cin >> N; printPartition(N); } } ================================================ FILE: BOJ/9024.두 수의 합/6047198844.py ================================================ import sys t = int(sys.stdin.readline()) for _ in range(t): n, K = map(int, sys.stdin.readline().split()) arr = list(map(int, sys.stdin.readline().split())) arr.sort() left = 0 right = len(arr) - 1 most_near_n = sys.maxsize most_near_cnt = 0 while left < right: if abs(K - arr[left] - arr[right]) < abs(K - most_near_n): most_near_n = arr[left] + arr[right] most_near_cnt = 1 elif abs(K - arr[left] - arr[right]) == abs(K - most_near_n): most_near_cnt += 1 if arr[left] + arr[right] <= K: left += 1 else: right -= 1 print(most_near_cnt) ================================================ FILE: BOJ/9081.단어 맞추기/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/9081 단어 맞추기 [풀이] 1. 각 단어가 구성할 수 있는 경우의 수를 구하기 위해 permutations import 2. 이 때 단어의 알파벳이 중복될수도 있으므로 set을 적용해준다 3. 입력받은 단어 뒤의 단어를 알기위해 정렬을 한다 => 문자열의 순서는 문자열을 숫자로 바꾸더라도 동일하다 4. idx를 찾는다. 마지막 원소라면 그대로 유지. 이후 반환 ''' n = int(input()) for _ in range(n): word = list(input()) for idx in range(len(word)-1, 0, -1): if word[idx] > word[idx-1]: a, b = min([(w, jdx) for jdx, w in enumerate(word[idx:]) if w > word[idx - 1]]) print(''.join(word[:idx-1]+[a]+sorted(word[idx:idx+b]+word[idx+b+1:]+[word[idx-1]]))) break else: print(''.join(word)) ================================================ FILE: BOJ/9084.동전/6047198844.py ================================================ import sys T = int(sys.stdin.readline()) # i: 현재 코인 인덱스 # coins: 코인 # K: 목표치 def dp(K, coins): memo = [0] * (K + 1) # memo[K] = K 원을 만들 수 있는 경우의 수 # 0 원을 만드는 경우의 수는 하나이다. memo[0] = 1 for coin in coins: for i in range(K+1): if i - coin >= 0: memo[i] = memo[i] + memo[i-coin] return memo[K] for _ in range(T): N = int(sys.stdin.readline()) coins = list(map(int, sys.stdin.readline().split())) K = int(sys.stdin.readline()) print(dp(K, coins)) ================================================ FILE: BOJ/9085.더하기/6047198844.py ================================================ import sys T = int(sys.stdin.readline()) for _ in range(T): N = int(sys.stdin.readline()) print(sum(map(int,sys.stdin.readline().split()))) ================================================ FILE: BOJ/9094.수학적 호기심/607198844.py ================================================ # 문제 # 두 정수 n과 m이 주어졌을 때, 0 < a < b < n인 정수 쌍 (a, b) 중에서 (a^2+b^2+m)/(ab)가 정수인 쌍의 개수를 구하는 프로그램을 작성하시오. # 입력 # 첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, n과 m이 주어진다. 두 수는 0보다 크고, 100보다 작거나 같다. # 출력 # 각 테스트 케이스마다 문제의 조건을 만족하는 (a, b)쌍의 개수를 출력한다. from itertools import combinations T = int(input()) for _ in range(T): n, m = map(int, input().split()) arr = list(range(1, n)) cnt = 0 for a, b in combinations(arr, 2): cnt += int((a ** 2 + b ** 2 + m) % (a * b) == 0) print(cnt) ================================================ FILE: BOJ/9095.1,2,3 더하기/6047198844.cpp ================================================ /* 정수 n이 주어졌을 때, n을 1, 2, 3의 합으로 나타내는 방법의 수 dp(1) = dp(0); dp(2) = dp(1) + dp(0); dp(3) = dp(1) + dp(2) + dp(0); dp(4) = dp(1) + dp(2) + dp(3); dp(5) = dp(2) + dp(3) + dp(4); dp(n) = 시그마 dp(1~n-1) */ #include int memo[11]; using namespace std; int dp(int n) { if (n < 0) return 0; if (memo[n]) return memo[n]; memo[n] = dp(n - 1) + dp(n - 2) + dp(n - 3); return memo[n]; } int main() { int T; int n; cin >> T; memo[0] = 1; for (int i = 0; i < T; i++) { cin >> n; cout << dp(n) << endl; } } //완전탐색 #include using namespace std; //base case //1. 0일떄 1을 반환한다. //2. 0보다 작을때 0을 반환한다. //et의 정의. // n-1 , n-2 , n-3을 더한 값을 반환한다. int et(int n) { if (n == 0) return 1; else if (n < 0) return 0; return et(n - 1) + et(n - 2) + et(n - 3); } int main() { int T; cin >> T; int n; for (int i = 0; i < T; i++) { cin >> n; cout << et(n) << endl; } } ================================================ FILE: BOJ/9184.신나는 함수 실행/6047198844.cpp ================================================ #include #include #define INT_MAX 100000 using namespace std; int memo[51][51][51]; int w(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) return 1; if (memo[a][b][c] != -1) return memo[a][b][c]; int& res = memo[a][b][c]; if (a > 20 || b > 20 || c > 20) return res = w(20, 20, 20); if (a < b && b < c) return res = w(a, b, c - 1) + w(a, b - 1, c - 1) - w(a, b - 1, c); return res = w(a - 1, b, c) + w(a - 1, b - 1, c) + w(a - 1, b, c - 1) - w(a - 1, b - 1, c - 1); } int main() { int a; int b; int c; while (1) { cin >> a >> b >> c; if (a == -1 && b == -1 && c == -1) break; memset(memo, -1, sizeof(memo)); //memset은 0으로 초기화할때 사용. cout << "w(" << a << ", " << b << ", " << c << ") = " << w(a, b, c) << "\n"; } } ================================================ FILE: BOJ/9204.체스/sangmandu.py ================================================ ''' https://www.acmicpc.net/problem/9204 체스 [풀이] 1. 열 좌표가 문자이므로, 행 좌표와 동일하게 설정한다 => A는 1, ... , H는 8 => 이 때 ord()를 사용한다. ord(A) = 65 => 추후에, 알파벳 좌표로 변환할 때는 chr() 사용 2. 시작좌표와 도착좌표에서 움직일 수 있는 대각선 좌표들을 모두 구한다. => 이들을 각각 diagonal[0]과 diagonal[1]에 할당 => 체스판의 끝지점에 도달할 때 까지 대각선방향으로 이동할 수 있는 좌표를 모두 구한다 => 이러한 과정을 총 4방향으로 진행한다. => 도달할 수 있는 좌표들은 튜플 형태로 각각의 대각선 리스트에 추가한다. => 추후에, set형태로 비교할 것이기 때문에 리스트가 아닌 튜플 형태로 추가한다. 3. 비교하는 방법은 다음과 같다. 3-1. 두 점이 같을 경우 => print(0, x1, y1) 3-2. 시작좌표의 대각선 이동범위 안에 도착 좌표가 있을 경우 => print(1, x1, y1, x2, y2) 3-3. 시작좌표의 대각선 이동범위와 도착좌표의 대각선 이동범위안에 둘 다 속하는 좌표가 존재할 경우 => 이 좌표를 x3, y3 라 하자 => print(2, x1, y1, x3, y3, x2, y2) => 이 때 diagonal을 set형태로 만들고 intersect()를 이용해 교집합을 구한다. 3-4. 이 외에는 방법이 없다 => print("Impossible") => 이 방법은 시작좌표의 합과 도착좌표의 합이 각각 홀수나 짝수로 동일한지 여부로 구할 수도 있다 ''' n = int(input()) for _ in range(n): x1, y1, x2, y2 = input().split() if x1 == x2 and y1 == y2: print(0, x1, y1) continue x1, x2 = ord(x1)-64, ord(x2)-64 y1, y2 = int(y1), int(y2) diagonal = [[], []] for idx, x, y in ([[0, x1, y1], [1, x2, y2]]): for nx, ny in [[1, 1], [1, -1], [-1, 1], [-1, -1]]: d = 1 while 1 <= x + nx*d <= 8 and 1 <= y + ny*d <= 8: diagonal[idx].append((x + nx*d, y + ny*d)) d += 1 if idx == 0: if (x2, y2) in diagonal[idx]: print(1, chr(x1+64), y1, chr(x2+64), y2) break else: inter = set(diagonal[0]).intersection(set(diagonal[1])) if inter: x3, y3 = list(inter)[0] print(2, chr(x1+64), y1, chr(x3+64), y3, chr(x2+64), y2) else: print("Impossible") ================================================ FILE: BOJ/9205.맥주 마시면서 걸어가기/6047198844.py ================================================ # 문제 # 출발은 상근이네 집에서 하고, 맥주 한 박스를 들고 출발한다. # 맥주 한 박스에는 맥주가 20개 들어있다. # 목이 마르면 안되기 때문에 50미터에 한 병씩 마시려고 한다. 즉, 50미터를 가려면 그 직전에 맥주 한 병을 마셔야 한다. # # 편의점에 들렸을 때, 빈 병은 버리고 새 맥주 병을 살 수 있다. # 하지만, 박스에 들어있는 맥주는 20병을 넘을 수 없다. # 편의점을 나선 직후에도 50미터를 가기 전에 맥주 한 병을 마셔야 한다. # # 편의점, 상근이네 집, 펜타포트 락 페스티벌의 좌표가 주어진다. # 상근이와 친구들이 행복하게 페스티벌에 도착할 수 있는지 구하는 프로그램을 작성하시오. # # 입력 # 첫째 줄에 테스트 케이스의 개수 t가 주어진다. (t ≤ 50) # 각 테스트 케이스의 첫째 줄에는 맥주를 파는 편의점의 개수 n이 주어진다. (0 ≤ n ≤ 100). # 다음 n+2개 줄에는 상근이네 집, 편의점, 펜타포트 락 페스티벌 좌표가 주어진다. 각 좌표는 두 정수 x와 y로 이루어져 있다. (두 값 모두 미터, -32768 ≤ x, y ≤ 32767) # 송도는 직사각형 모양으로 생긴 도시이다. 두 좌표 사이의 거리는 x 좌표의 차이 + y 좌표의 차이 이다. (맨해튼 거리) # # 출력 # 각 테스트 케이스에 대해서 상근이와 친구들이 행복하게 페스티벌에 갈 수 있으면 "happy", 중간에 맥주가 바닥나서 더 이동할 수 없으면 "sad"를 출력한다. import sys t = int(input()) def is_connected(place1, place2): x1, y1 = place1 x2, y2 = place2 return (abs(x1 - x2) + abs(y1 - y2)) <= 1000 for _ in range(t): n = int(sys.stdin.readline()) places = [tuple(map(int, sys.stdin.readline().split())) for _ in range(n + 2)] # 연결되어있으면 True. 연결되있지않으면 False # 0번째 정점, n + 1 번째 정점이 True 인지 판단하면된다. # 초기화 board = [[False for _ in range(n + 2)] for _ in range(n + 2)] for i in range(n + 2): for j in range(i + 1, n + 2): board[i][j] = board[j][i] = is_connected(places[i], places[j]) # 플로이드는 다이나믹 프로그래밍에 기반한다. # k 에 대해 전수조사하며 최적인지 검사한다. for k in range(n + 2): for i in range(n + 2): for j in range(n + 2): board[i][j] = board[i][j] or (board[i][k] and board[k][j]) print("happy") if board[0][n + 1] else print("sad") ================================================ FILE: BOJ/9251.LCS/6047198844.cpp ================================================ /* 문제 LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다. 예를 들어, ACAYKP와 CAPCAK의 LCS는 ACAK가 된다. 입력 첫째 줄과 둘째 줄에 두 문자열이 주어진다. 문자열은 알파벳 대문자로만 이루어져 있으며, 최대 1000글자로 이루어져 있다. 출력 첫째 줄에 입력으로 주어진 두 문자열의 LCS의 길이를 출력한다. ACAYKP CAPCAK */ #include #include #include #include #include using namespace std; int memo[1001][1001]; string a; string b; int LCS(int a_index, int b_index) { if (a_index == -1 || b_index == -1) return 0; int& ret = memo[a_index][b_index]; if (ret!=-1) return ret; if (a[a_index] == b[b_index]) { return ret = 1 + LCS(a_index - 1, b_index - 1); } else { return ret = max(LCS(a_index, b_index -1), LCS(a_index-1, b_index)); } } int main() { memset(memo, -1, sizeof(memo)); cin >> a >> b; cout << LCS(a.size() - 1, b.size() - 1); } ================================================ FILE: BOJ/9252.LCS 2/6047198844.py ================================================ # 문제 # LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다. # # 예를 들어, ACAYKP와 CAPCAK의 LCS는 ACAK가 된다. # # 입력 # 첫째 줄과 둘째 줄에 두 문자열이 주어진다. 문자열은 알파벳 대문자로만 이루어져 있으며, 최대 1000글자로 이루어져 있다. A = '.' + input() B = '.' + input() # memo[i][j] # A[~i] / B[~j] 까지의 최장 공통 부분 수열의 길이. memo = [[0 for _ in range(len(A))] for _ in range(len(B))] for y in range(1, len(B)): for x in range(1, len(A)): if A[x] == B[y]: # 정의를 생각해보자. memo[y-1][x-1] 은 바로 직전의 최장 공통 부분 수열이다. # x, y 는 현재를 뜻한다. 현재값이 같다면, 최적화된 직전값에 1을 더했을때도 최적값이다. memo[y][x] = memo[y-1][x-1] + 1 else: # 바로 직전의 두 값중 하나가 최적값이다. # 근거는 연속되지 않아도 되기때문에 직전값의 값을 계승해도 문제가 없다. 따라서 직전의 값을 계승한다. memo[y][x] = max(memo[y-1][x], memo[y][x-1]) # 맨끝에서 부터 찾아나간다. # 영향을 어디서 부터 받았는지 생각해보자. # 값이 같다면, 직전으로부터 영향을 받은것이고, 값이 틀리다면 큰값으로 부터 영향을 받은것이다. 영향 받는 곳으로 역추적하자. 어쩌피, 맨 마지막값이 답이다. res = '' M, N = len(B) - 1, len(A) - 1 print(memo[M][N]) while M > 0 and N > 0: if A[N] == B[M]: res += A[N] M -= 1 N -= 1 else: if memo[M][N-1] > memo[M-1][N]: N -= 1 else: M -= 1 print(res[::-1]) ================================================ FILE: BOJ/9316.Hello Judge/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) for i in range(1, N+1): print(f'Hello World, Judge {i}!') ================================================ FILE: BOJ/9324.진짜 메시지/6047198844.py ================================================ import sys from collections import defaultdict N = int(sys.stdin.readline()) for _ in range(N): table = defaultdict(int) s = sys.stdin.readline().rstrip() i = 0 while i < len(s): table[s[i]] += 1 if table[s[i]] % 3 == 0: if i + 1 >= len(s) or table[s[i + 1]] != table[s[i]]: print('FAKE') break else: i += 1 i += 1 else: print('OK') ================================================ FILE: BOJ/9325.얼마?/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) for _ in range(N): res = 0 car_price = int(sys.stdin.readline()) res += car_price option_N = int(sys.stdin.readline()) for _ in range(option_N): quantity, option_price = map(int, sys.stdin.readline().split()) res += (quantity * option_price) print(res) ================================================ FILE: BOJ/9328.열쇠/6047198844.py ================================================ import sys from collections import deque T = int(sys.stdin.readline()) for _ in range(T): h, w = map(int, sys.stdin.readline().split()) board = [list(sys.stdin.readline().rstrip()) for _ in range(h)] keys = set(list(sys.stdin.readline().rstrip())) count = 0 # BFS 시작점 edges = [] edge_doors = [] # 가장자리. 빈곳. for y in range(h): for x in range(w): if (y == 0 or y == h - 1 or x == 0 or x == w - 1) and board[y][x] != '*': # 빈공간인 경우 if board[y][x] == ".": edges.append((y, x)) # 문서인 경우 elif board[y][x] == '$': count += 1 edges.append((y, x)) board[y][x] = "." # 열쇠인 경우 elif board[y][x].islower(): keys.add(board[y][x]) edges.append((y, x)) board[y][x] = "." # 문인 경우 elif board[y][x].isupper(): # 키가 있는 경우 if board[y][x].lower() in keys: edges.append((y, x)) board[y][x] = "." # 키가 없는 경우. BFS 돌면서 열수있는지 판단해야한다. else: edge_doors.append((y, x)) # 열쇠/문/문서에 대한 행동이 존재. actions = True while actions: actions = False # 진입점을 넣는다. visited = set(edges) Q = deque(edges) while Q: y, x = Q.popleft() # 주변을 탐색한다. for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny, nx = y + dy, x + dx if (ny, nx) in visited: continue if not (0 <= ny < h and 0 < nx < w): continue if board[ny][nx] == "*": continue # 빈공간 if board[ny][nx] == ".": visited.add((ny, nx)) Q.append((ny, nx)) # 대문자 -> 문을 여는 경우 elif board[ny][nx].isupper() and board[ny][nx].lower() in keys: visited.add((ny, nx)) Q.append((ny, nx)) board[ny][nx] = "." actions = True # 소문자 -> 열쇠 획득 elif board[ny][nx].islower(): keys.add(board[ny][nx]) visited.add((ny, nx)) Q.append((ny, nx)) board[ny][nx] = "." actions = True # $ 문서 획득 elif board[ny][nx] == '$': visited.add((ny, nx)) Q.append((ny, nx)) board[ny][nx] = "." actions = True count += 1 # 테두리 문을 열수 있는가? for y, x in edge_doors: if board[y][x].lower() in keys: edges.append((y, x)) board[y][x] = "." actions = True print(count) ================================================ FILE: BOJ/9375.패션왕 신해빈/6047198844.cpp ================================================ #include #include #include using namespace std; int main() { int C; cin >> C; while (C--) { int N; cin >> N; map mp; while (N--) { string a, b; cin >> a >> b; mp[b]++; } int res = 1; for (auto i : mp) res *= (i.second + 1); cout << res - 1 << "\n"; } } ================================================ FILE: BOJ/9424.폭탄 해체/6047198844.py ================================================ # 문제 # 홍준이는 폭탄의 상단에 숫자가 표시되고 있다는 점에 주목했다. # 폭탄의 상단에 표시되는 숫자를 코드라고 한다는 것을 알게 되었다. 또, 코드가 6으로 나누어 떨어질 때 전선을 잘라야 한다고 나왔다. # 폭탄의 코드가 주어졌을 때, 전선을 자르면 폭탄을 해체할 수 있는지, 폭탄이 폭발하는지 구하는 프로그램을 작성하시오. # # 입력 # 입력으로 폭탄의 코드가 주어진다. 코드는 2자리 이상, 8자리 이하이고, 각 자리는 5행 3열의 문자로 주어진다. 문자는 공백과 별표('*') 중 하나이다. 또, 각 숫자를 구분하기 위해 숫자 사이에는 빈 칸이 하나씩 있다. # # 모든 숫자는 5×3 크기이지만, 올바르지 않은 숫자가 주어질 수도 있다. 올바르지 않은 숫자가 주어진 경우에는 전선을 자르면 안 된다. # # 0부터 9까지 숫자를 5×3으로 나타내는 방법은 아래에 나와있다. # # ### ### ### ### ### ### ### ### ### ### # *** * *** *** * * *** *** *** *** *** # * * * * * * * * * * * * * * # * * * *** *** *** *** *** * *** *** # * * * * * * * * * * * * * # *** * *** *** * *** *** * *** *** # 그림 1. 맨 위의 #는 열을 알아보기 쉽게 하기 위해 주어진 문자이다. # # 코드는 0으로 시작하는 숫자일 수도 있다. 예를 들어, 00000076는 76이다. # # 출력 # 첫째 줄에 입력으로 주어진 코드인 경우에 전선을 잘라도 되면 "BEER!!"를, 자르면 폭발하는 경우에는 "BOOM!!"을 출력한다. # 숫자를 매핑 import sys dict = dict() dict[("**** ** ** ****")] = '0' dict[(" * * * * *")] = '1' dict[("*** ***** ***")] = '2' dict[("*** **** ****")] = '3' dict[("* ** **** * *")] = '4' dict[("**** *** ****")] = '5' dict[("**** **** ****")] = '6' dict[("*** * * * *")] = '7' dict[("**** ***** ****")] = '8' dict[("**** **** ****")] = '9' res = '' board = [input() for _ in range(5)] row_len = len(board[0]) for col in range(2, row_len, 4): word = "" for row in range(0, 5): word += board[row][col-2] + board[row][col-1] + board[row][col] if word in dict: res += dict[word] else: print("BOOM!!") exit() if int(res) % 6 == 0: print("BEER!!") else: print("BOOM!!") ================================================ FILE: BOJ/9461.파도반수열/6047198844.py ================================================ # 오른쪽 그림과 같이 삼각형이 나선 모양으로 놓여져 있다. 첫 삼각형은 정삼각형으로 변의 길이는 1이다. 그 다음에는 다음과 같은 과정으로 정삼각형을 계속 추가한다. 나선에서 가장 긴 변의 길이를 k라 했을 때, 그 변에 길이가 k인 정삼각형을 추가한다. # # 파도반 수열 P(N)은 나선에 있는 정삼각형의 변의 길이이다. P(1)부터 P(10)까지 첫 10개 숫자는 1, 1, 1, 2, 2, 3, 4, 5, 7, 9이다. # # N이 주어졌을 때, P(N)을 구하는 프로그램을 작성하시오. # 1 # 1 # 1 # 1 + 1 = 2 # 0 + 2 = 2 # 1 + 2 = 3 # 1 + 3 = 4 # 1 + 4 = 5 # 2 + 5 = 7 # 2 + 7 = 9 # 3 + 9 = 12 # 4 + 12 = 16 # 5 + 16 = 21 # 7 + 21 = 28 # 9 + 28 = 37 # 12 + 37 = 49 # P(n-5) + P(n-1) = P(n) # P(-4) + P(0) = P(1) # P(-3) + P(1) = P(2) # P(-2) + P(2) = P(3)å # P(-1) + P(3) = P(4) T = int(input()) for _ in range(T): N = int(input()) P = [1, 1, 1, 2, 2] for idx in range(5, N + 1): P.append(P[idx-5] + P[idx-1]) print(P[N-1]) ================================================ FILE: BOJ/9461.파도반수열/rockmiin.py ================================================ test_case=int(input()) for i in range(test_case): n=int(input()) dp=[1, 1, 1, 2, 2] if n>5: for i in range(n-5): dp.append(dp[-1]+dp[-5]) print(dp[-1]) else: print(dp[n-1]) ================================================ FILE: BOJ/9465.스티커/Munang.py ================================================ t = int(input()) for i in range(t): n = int(input()) dp =[] memo =[] for j in range(2): score = list(map(int,input().split())) dp.append(score) memo.append([0]*n) ## 0이 아닐경우 출력이라는걸 구현해야함 for k in range(n): if(k ==0): memo[0][k] = dp[0][k] memo[1][k] = dp[1][k] if(k ==1): memo[1][1] = dp[0][0] + dp[1][1] memo[0][1] = dp[1][0] + dp[0][1] memo[0][k] = max(memo[1][k-1], memo[1][k-2]) + dp[0][k] memo[1][k] = max(memo[0][k-1], memo[0][k-2]) + dp[1][k] print(max(memo[0][n-1],memo[1][n-1])) ================================================ FILE: BOJ/9465.스티커/sAp00n.py ================================================ # 실패한 아이디어들... # 1. 가장 큰 값의 스티커를 일단 뜯어 낸 후, 반으로 갈라진 스티커들을 재귀적으로 계산 = > 메모리 오버. # 2. 부루트포스 방식으로 접근하되, 한번 접근한 노드에 대한 최댓값을 메모이제이션 시켜 그보다 적을경우 큐에 추가하지 않음 => 메모리 오버 # 3. 결국 솔루션 보고 일반항을 세울수 있다는걸 알게됨... 왜 몰랐을까 from sys import stdin def sol(): n = int(stdin.readline()) sticker = [list(map(int, stdin.readline().split())) for _ in range(2)] DP = {(0, 0): sticker[0][0], (1, 0): sticker[1][0], (0, 1): sticker[1][0] + sticker[0][1], (1, 1): sticker[0][0] + sticker[1][1]} for idx in range(2, n): DP[(0, idx)] = max(DP[(1, idx - 1)], DP[(1, idx - 2)]) + sticker[0][idx] DP[(1, idx)] = max(DP[(0, idx - 1)], DP[(0, idx - 2)]) + sticker[1][idx] return max(DP[(0, n - 1)], DP[(1, n - 1)]) T = int(stdin.readline()) for _ in range(T): print(sol()) ================================================ FILE: BOJ/9536.여우는 어떻게 울지?/6047198844.py ================================================ T = int(input()) for _ in range(T): record_voices = input().split() fox_voice = set(record_voices) while True: V = input() if V == "what does the fox say?": break animal, goes, voice = V.split() fox_voice.remove(voice) for record_voice in record_voices: if record_voice in fox_voice: print(record_voice, end=' ') print() ================================================ FILE: BOJ/9625.BABBA/6047198844.py ================================================ commands = 'A' K = int(input()) a, b = 0, 1 for _ in range(1, K): a, b = b, a+b print(a, b) ================================================ FILE: BOJ/9653.스타워즈 로고/6047198844.py ================================================ print(' 8888888888 888 88888') print(' 88 88 88 88 88 88') print(' 8888 88 88 88 88888') print(' 88 88 888888888 88 88') print('88888888 88 88 88 88 888888') print('') print('88 88 88 888 88888 888888') print('88 88 88 88 88 88 88 88') print('88 8888 88 88 88 88888 8888') print(' 888 888 888888888 88 88 88') print(' 88 88 88 88 88 88888888') ================================================ FILE: BOJ/9654.나부 함대 데이터/6047198844.py ================================================ print('SHIP NAME CLASS DEPLOYMENT IN SERVICE') print('N2 Bomber Heavy Fighter Limited 21 ') print('J-Type 327 Light Combat Unlimited 1 ') print('NX Cruiser Medium Fighter Limited 18 ') print('N1 Starfighter Medium Fighter Unlimited 25 ') print('Royal Cruiser Light Combat Limited 4 ') ================================================ FILE: BOJ/9655.돌 게임/6047198844.py ================================================ import sys N = int(sys.stdin.readline()) print("SK") if N % 2 == 1 else print("CY") ================================================ FILE: BOJ/9663.N-Queen/6047198844.cpp ================================================ #include #include #include using namespace std; int N; //N범위 : 1~14 bool arr[15][15]; //y범위 : 1~14 / x범위 : 1~14 int dy[8] = { -1,-1, 0,+1,+1,+1, 0,-1 }; int dx[8] = { 0,-1,-1,-1, 0,+1,+1,+1 }; void check_Queen(int y, int x, queue>& q) { if (q.empty()) { int check_y; int check_x; arr[y][x] = !arr[y][x]; q.push({ y,x }); for (int i = 0; i < 8; i++) { check_y = y; check_x = x; while (check_y + dy[i] > 0 && check_y + dy[i] <= N && check_x + dx[i] > 0 && check_x + dx[i] <= N) { check_y += dy[i]; check_x += dx[i]; if (!arr[check_y][check_x]) { arr[check_y][check_x] = arr[y][x]; q.push({ check_y,check_x }); } } } } else { while (!q.empty()) { int y = q.front().first; int x = q.front().second; q.pop(); arr[y][x] = false; } } } int dfs(int y) { int res = 0; for (int x = 1; x <= N; x++) { if (y == N) { if (!arr[y][x]) ++res; continue; } if (!arr[y][x]) { queue> q; check_Queen(y, x, q); res += dfs(y + 1); check_Queen(y, x, q); } } return res; } int main() { cin >> N; memset(arr, false, sizeof(arr)); cout << dfs(1); } ================================================ FILE: BOJ/9663.N-Queen/6047198844.py ================================================ #col : x ''' 0123 0123 0123 0123 ''' #row : y ''' 0000 1111 2222 3333 ''' #ldiag : y + x ''' 0123 1234 2345 3456 ''' #rdiag : y + (n-x-1) ''' 3210 4321 5432 6543 ''' N = int(input()) col = set() #row = set() ldiag = set() rdiag = set() def dfs(y:int)->int: if y == N: return 1 res = 0 for x in range(0, N): if x not in col and y + x not in ldiag and y + (N-x-1) not in rdiag: col.add(x) ldiag.add(y + x) rdiag.add(y + N - x - 1) res += dfs(y+1) col.remove(x) ldiag.remove(y + x) rdiag.remove(y + N - x - 1) return res print(dfs(0)) ================================================ FILE: BOJ/9933.민균이의 비밀번호/6047198844.py ================================================ import sys visited = set() N = int(input()) for _ in range(N): line = sys.stdin.readline().rstrip() visited.add(line) if line[::-1] in visited: print(len(line), line[len(line)//2]) ================================================ FILE: BOJ/solved.ac_class/Class01/10818. 최소, 최대/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) input_list = stdin.readline().split() input_list = [int(ele) for ele in input_list] print(f'{min(input_list)} {max(input_list)}') ================================================ FILE: BOJ/solved.ac_class/Class01/10869.사칙연산/sAp00n.py ================================================ import sys input_list = sys.stdin.readline().split() A, B = (int(ele) for ele in input_list) print(A + B) print(A - B) print(A * B) print(A // B) print(A % B) ================================================ FILE: BOJ/solved.ac_class/Class01/10950.A + B - 3/sAp00n.py ================================================ from sys import stdin T = int(stdin.readline()) for case in range(T): input_list = stdin.readline().split() input_list = [int(ele) for ele in input_list] print(input_list[0]+input_list[1]) ================================================ FILE: BOJ/solved.ac_class/Class01/10951.A + B - 4/sAp00n.py ================================================ from sys import stdin input_str = stdin.readlines() input_str = [string.rstrip('\n') for string in input_str] input_num_couple = [couples.split() for couples in input_str] for idx in range(len(input_num_couple)): input_num_couple[idx] = [int(numbers) for numbers in input_num_couple[idx]] for i in input_num_couple: print(i[0] + i[1]) ================================================ FILE: BOJ/solved.ac_class/Class01/10952.A + B - 5/sAp00n.py ================================================ from sys import stdin input_str = stdin.readlines() input_str = [string.rstrip('\n') for string in input_str] input_num_couple = [couples.split() for couples in input_str] for idx in range(len(input_num_couple)): input_num_couple[idx] = [int(numbers) for numbers in input_num_couple[idx]] for i in input_num_couple: if i != [0, 0]: print(i[0] + i[1]) ================================================ FILE: BOJ/solved.ac_class/Class01/11654.아스키 코드/sAp00n.py ================================================ val = input() print(ord(val)) ================================================ FILE: BOJ/solved.ac_class/Class01/11720.숫자의 합/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) input_str = stdin.readline() input_list = map(int, [input_str[idx] for idx in range(N)]) print(sum(input_list)) ================================================ FILE: BOJ/solved.ac_class/Class01/1330.두 수 비교하기/sAp00n.py ================================================ import sys input_list = sys.stdin.readline().split() A, B = (int(ele) for ele in input_list) if A > B: print('>') elif A < B: print('<') else: print('==') ================================================ FILE: BOJ/solved.ac_class/Class01/2438.별 찍기 - 1/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) for i in range(N): print('*'*(i+1)) ================================================ FILE: BOJ/solved.ac_class/Class01/2562.최댓값/sAp00n.py ================================================ from sys import stdin input_list = [int(stdin.readline()) for _ in range(9)] max_val = max(input_list) max_val_idx = input_list.index(max_val) print(f'{max_val}\n{max_val_idx+1}') ================================================ FILE: BOJ/solved.ac_class/Class01/2675.문자열 반복/sAp00n.py ================================================ from sys import stdin T = int(stdin.readline()) for i in range(T): input_list = stdin.readline().split() input_list[0] = int(input_list[0]) return_str = '' for j in range(len(input_list[1])): return_str += input_list[1][j] * input_list[0] print(return_str) ================================================ FILE: BOJ/solved.ac_class/Class01/2739.구구단/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) for i in range(1, 10): print(f'{N} * {i} = {N * i}') ================================================ FILE: BOJ/solved.ac_class/Class01/2920.음계/sAp00n.py ================================================ from sys import stdin a = list(map(int, stdin.readline().split())) if a == sorted(a): print('ascending') elif a == sorted(a, reverse=True): print('descending') else: print('mixed') ================================================ FILE: BOJ/solved.ac_class/Class01/8958.OX퀴즈/sAp00n.py ================================================ from sys import stdin T = int(stdin.readline()) for cases in range(T): result = stdin.readline() score = 0 temp = 0 for idx in range(len(result)): if result[idx] == 'O': temp += 1 score += temp else: temp = 0 print(score) ================================================ FILE: BOJ/solved.ac_class/Class02/1018.채스판 다시 칠하기/sAp00n.py ================================================ def check_BW(ex): cnt1 = 0 for i in range(8): for j in range(8): i_ = (0 if i in [0, 2, 4, 6] else 1) j_ = (0 if j in [0, 2, 4, 6] else 1) if (i_ == 0 and j_ == 0) or (i_ == 1 and j_ == 1): if ex[i][j] != "B": cnt1 += 1 if (i_ == 0 and j_ == 1) or (i_ == 1 and j_ == 0): if ex[i][j] != "W": cnt1 += 1 cnt2 = 0 for i in range(8): for j in range(8): i_ = (0 if i in [0, 2, 4, 6] else 1) j_ = (0 if j in [0, 2, 4, 6] else 1) if (i_ == 0 and j_ == 0) or (i_ == 1 and j_ == 1): if ex[i][j] != "W": cnt2 += 1 if (i_ == 0 and j_ == 1) or (i_ == 1 and j_ == 0): if ex[i][j] != "B": cnt2 += 1 return min(cnt1, cnt2) n, m = map(int, input().split()) s = [list(input()) for i in range(n)] check = list() for i in range(n - 7): for j in range(m - 7): ex = [z[(0 + j):(8 + j)] for z in s[(0 + i):(8 + i)]] check.append(check_BW(ex)) print(min(check)) ================================================ FILE: BOJ/solved.ac_class/Class02/10250.ACM호텔/sAp00n.py ================================================ from sys import stdin T = int(stdin.readline()) for i in range(T): H, W, N = list(map(int, stdin.readline().split())) room_num = N // H if N % H > 0: room_num += 1 if len(str(room_num)) < 2: room_num = '0' + str(room_num) floor_num = min(N%H, H) print(f'{floor_num}{room_num}') ================================================ FILE: BOJ/solved.ac_class/Class02/10814.나이순 정렬/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) age_list = [] member_dict = {} for _ in range(N): member_age, member_name = list(stdin.readline().split()) member_age = int(member_age) if member_age not in age_list: age_list.append(member_age) member_dict[member_age] = [] member_dict[member_age] += [str(member_age)+' '+member_name] age_list.sort() for age in age_list: for member in member_dict[age]: print(member) ================================================ FILE: BOJ/solved.ac_class/Class02/10816.숫자 카드2/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) cards = list(map(int, stdin.readline().split())) M = int(stdin.readline()) call_list = list(map(int, stdin.readline().split())) card_dict = {} for card in cards: card_dict[card] = card_dict.get(card, 0) + 1 return_str = '' for call in call_list: if call not in card_dict: return_str += ' 0' else: return_str += (' '+str(card_dict[call])) return_str = return_str.strip() print(return_str) ================================================ FILE: BOJ/solved.ac_class/Class02/10828.스택/sAp00n.py ================================================ from sys import stdin class Stack: def __init__(self): self.stack_data = [] def push(self, data_in): self.stack_data.append(data_in) def pop(self): if self.empty(): print(-1) else: temp = self.stack_data[-1] self.stack_data = self.stack_data[:-1] print(temp) def size(self): print(len(self.stack_data)) def empty(self): return len(self.stack_data) == 0 def top(self): if self.empty(): print(-1) else: print(self.stack_data[-1]) def check_commend(stack, str_line): input_commend = str_line.split() if input_commend[0] == 'push': stack.push(int(input_commend[-1])) if input_commend[0] == 'pop': stack.pop() if input_commend[0] == 'size': stack.size() if input_commend[0] == 'empty': if stack.empty(): print(1) else: print(0) if input_commend[0] == 'top': stack.top() N = int(stdin.readline()) commend_list = [] for _ in range(N): commend_list.append(stdin.readline().rstrip('\n')) new_stack = Stack() for commend in commend_list: check_commend(new_stack, commend) ================================================ FILE: BOJ/solved.ac_class/Class02/10845.큐/sAp00n.py ================================================ from sys import stdin class Que: def __init__(self): self.que_data = [] def push(self, data_in): self.que_data.append(data_in) def pop(self): if self.empty(): print(-1) else: temp = self.que_data[0] self.que_data = self.que_data[1:] print(temp) def size(self): print(len(self.que_data)) def empty(self): return len(self.que_data) == 0 def front(self): if self.empty(): print(-1) else: print(self.que_data[0]) def back(self): if self.empty(): print(-1) else: print(self.que_data[-1]) def check_commend(stack, str_line): input_commend = str_line.split() if input_commend[0] == 'push': stack.push(int(input_commend[-1])) if input_commend[0] == 'pop': stack.pop() if input_commend[0] == 'size': stack.size() if input_commend[0] == 'empty': if stack.empty(): print(1) else: print(0) if input_commend[0] == 'front': stack.front() if input_commend[0] == 'back': stack.back() N = int(stdin.readline()) commend_list = [] for _ in range(N): commend_list.append(stdin.readline().rstrip('\n')) new_stack = Que() for commend in commend_list: check_commend(new_stack, commend) ================================================ FILE: BOJ/solved.ac_class/Class02/1085.직사각형에서 탈출/sAp00n.py ================================================ from sys import stdin x, y, w, h = map(int, stdin.readline().split()) escape_condition = [(x, 0), (0, y), (x, h), (w, y)] min_distance = ((x-escape_condition[0][0])**2 + (y-escape_condition[0][1])**2) ** 0.5 for i in range(1, 4): min_distance = min(min_distance, ((x-escape_condition[i][0])**2 + (y-escape_condition[i][1])**2) ** 0.5) print(int(min_distance)) ================================================ FILE: BOJ/solved.ac_class/Class02/10866.덱/sAp00n.py ================================================ from sys import stdin class Deck: def __init__(self): self.deck_data = [] def push_back(self, data_in): temp = data_in self.deck_data = [temp] + self.deck_data def push_front(self, data_in): self.deck_data.append(data_in) def pop_front(self): if self.empty(): return print(-1) temp = self.deck_data[-1] self.deck_data = self.deck_data[:-1] print(temp) def pop_back(self): if self.empty(): return print(-1) temp = self.deck_data[0] self.deck_data = self.deck_data[1:] print(temp) def size(self): print(len(self.deck_data)) def empty(self): if len(self.deck_data) == 0: return True else: return False def front(self): if self.empty(): print(-1) else: print(self.deck_data[-1]) def back(self): if self.empty(): print(-1) else: print(self.deck_data[0]) def check_commend(stack, str_line): input_commend = str_line.split() if input_commend[0] == 'push_front': stack.push_front(int(input_commend[-1])) if input_commend[0] == 'push_back': stack.push_back(int(input_commend[-1])) if input_commend[0] == 'pop_front': stack.pop_front() if input_commend[0] == 'pop_back': stack.pop_back() if input_commend[0] == 'size': stack.size() if input_commend[0] == 'empty': if stack.empty(): print(1) else: print(0) if input_commend[0] == 'front': stack.front() if input_commend[0] == 'back': stack.back() N = int(stdin.readline()) commend_list = [] for _ in range(N): commend_list.append(stdin.readline().rstrip('\n')) new_stack = Deck() for commend in commend_list: check_commend(new_stack, commend) ================================================ FILE: BOJ/solved.ac_class/Class02/11050. 이항계수/sAp00n.py ================================================ from math import factorial as f n, k = map(int, input().split()) if k < 0 or k > n: print(0) else: print(int(f(n) / (f(k) * f(n - k)))) ================================================ FILE: BOJ/solved.ac_class/Class02/11650.좌표 정렬하기/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) dots = [] * range(N) for i in range(N): dots[i] = list(map(int,stdin.readline().split())) dots.sort() for i in dots: print(f'{i[0]} {i[1]}') ================================================ FILE: BOJ/solved.ac_class/Class02/1181.단어정렬/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) words_list = [] for _ in range(N): words_list.append(stdin.readline().rstrip('\n')) word_dict = {} max_len = 0 for word in words_list: word_len = len(word) if word_len not in word_dict: word_dict[word_len] = [] max_len = max(max_len, word_len) if word not in word_dict[word_len]: word_dict[word_len] += [word] for len in range(1, max_len+1): if len in word_dict: temp = word_dict[len] temp.sort() for word in temp: print(word) ================================================ FILE: BOJ/solved.ac_class/Class02/11866.요세푸스 문제/sAp00n.py ================================================ from sys import stdin from collections import deque N, K = list(map(int, stdin.readline().split())) jump = K-1 circle = deque() return_str = '<' for i in range(1, N+1): circle.append(i) for j in range(N): circle.rotate(-jump) return_str += (str(circle.popleft())+', ') return_str = return_str[:-2] return_str += '>' print(return_str) ================================================ FILE: BOJ/solved.ac_class/Class02/1259.팰린드롬수/sAp00n.py ================================================ from sys import stdin def word_input(): temp = stdin.readline().rstrip('\n') word_list = [] if temp != '0': word_list.append(temp) temp = stdin.readline().rstrip('\n') while temp != '0': word_list.append(temp) temp = stdin.readline().rstrip('\n') return word_list def is_palindrome(input_str): idx = 0 while idx < len(input_str) / 2: left_str = input_str[idx] right_str = input_str[-(idx + 1)] if left_str == right_str: idx += 1 else: return False return True word_list = word_input() for word in word_list: if is_palindrome(word): print('yes') else: print('no') ================================================ FILE: BOJ/solved.ac_class/Class02/1920.수 찾기/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) A = list(map(int, stdin.readline().strip('\n').split())) A_dict = {} for ele in A: A_dict[ele] = True M = int(stdin.readline().strip('\n')) B = list(map(int, stdin.readline().strip('\n').split())) for ele in B: if ele in A_dict: print('1') else: print('0') ================================================ FILE: BOJ/solved.ac_class/Class02/1978.소수 찾기/sAp00n.py ================================================ from sys import stdin def sieve_of_eratosthenes(Maximum): numbers = {} for number in range(2, Maximum + 1): numbers[number] = True root_of_max = int(Maximum ** 0.5) for i in range(2, root_of_max + 1): if numbers[i]: n = 2 while i * n <= Maximum: numbers[i * n] = False n += 1 return [j for j in range(2, Maximum + 1) if numbers[j]] N = int(stdin.readline().strip('\n')) list_of_numbers = list(map(int, stdin.readline().strip('\n').split())) Maximum_number = max(list_of_numbers) sieve = sieve_of_eratosthenes(Maximum_number) print( len([ number for number in list_of_numbers if number in sieve]) ) ================================================ FILE: BOJ/solved.ac_class/Class02/2164.카드2/sAp00n.py ================================================ from sys import stdin def solution(): N = int(stdin.readline().strip('\n')) deck = [card for card in range(1, N + 1)] + [None] * range(N + 1) fst_card = 0 end_card = N temp = deck[fst_card] while deck[fst_card + 1] is not None: deck[fst_card] = None temp = deck[fst_card + 1] deck[fst_card + 1] = None deck[end_card] = temp fst_card += 2 end_card += 1 print(temp) solution() ================================================ FILE: BOJ/solved.ac_class/Class02/2609. 최대공약수와 최소공배수/sAp00n.py ================================================ from sys import stdin def gdc(a, b): if b > a: a, b = b, a while b > 0: a, b = b, a%b return a a, b = list(map(int, stdin.readline().split())) gdc_num = gdc(a, b) print(gdc_num) print(int((a * b)/gdc_num)) ================================================ FILE: BOJ/solved.ac_class/Class02/2798.블랙잭/sAp00n.py ================================================ n, m = map(int,input().split()) v = list(map(int, input().split())) s = list() for i in range(len(v)) : for j in range((i+1), len(v)) : for z in range((j+1),len(v)) : s.append(sum([v[i],v[j],v[z]])) s = [i for i in s if i<=m] if len(s)>0 : print(max(s)) ================================================ FILE: BOJ/solved.ac_class/Class02/9023.괄호/sAp00n.py ================================================ from sys import stdin from collections import deque def checker(test_case): que = deque() for idx in range(len(test_case)): if test_case[idx] == ')': if '(' not in que: return False que.remove('(') if test_case[idx] == '(': que.appendleft('(') return len(que) == 0 T = int(stdin.readline()) str_list = [stdin.readline().rstrip('\n') for string in range(T)] for test_case in str_list: if checker(test_case): print('YES') else: print('NO') ================================================ FILE: BOJ/solved.ac_class/Class03/1003.피보나치 함수/sAp00n.py ================================================ a = int(input()) zero = [1, 0, 1] one = [0, 1, 1] def cal(num): length = len(zero) if length <= num: for i in range(length, num + 1): zero.append(zero[i - 1] + zero[i - 2]) one.append(one[i - 1] + one[i - 2]) print("%d %d" % (zero[num], one[num])) for i in range(a): k = int(input()) cal(k) ================================================ FILE: BOJ/solved.ac_class/Class03/1012.유기농 배추/sAp00n.py ================================================ from sys import stdin def bfs(farm, i, j, M, N, visited): if farm[i][j] == 0: visited.append([i, j]) return [0, visited] block = [] queue = [[i, j]] while queue: [i, j] = queue.pop(0) block.append([i, j]) visited.append([i, j]) if farm[i][j] == 1: if i < N - 1 and farm[i + 1][j] == 1 and [i + 1, j] not in block and [i + 1, j] not in queue: queue.append([i + 1, j]) if j < M - 1 and farm[i][j + 1] == 1 and [i, j + 1] not in block and [i, j + 1] not in queue: queue.append([i, j + 1]) if j > 0 and farm[i][j - 1] == 1 and [i, j - 1] not in block and [i, j - 1] not in queue: queue.append([i, j - 1]) if i > 0 and farm[i - 1][j] == 1 and [i - 1, j] not in block and [i - 1, j] not in queue: queue.append([i - 1, j]) return [len(block), visited] case = int(input()) for _ in range(case): M, N, K = map(int, stdin.readline().split()) farm = [[0 for _ in range(M)] for _ in range(N)] for _ in range(K): X, Y = map(int, stdin.readline().split()) farm[Y][X] = 1 visited = [] result = 0 for i in range(N): for j in range(M): if [i, j] not in visited: [size, visited] = bfs(farm, i, j, M, N, visited) if size != 0: result += 1 print(result) ================================================ FILE: BOJ/solved.ac_class/Class03/1074.Z/sAp00n.md ================================================ ### Z 한수는 2차원 배열 (항상 2^N * 2^N 크기이다)을 Z모양으로 탐색하려고 한다. 예를 들어, 2*2배열을 왼쪽 위칸, 오른쪽 위칸, 왼쪽 아래칸, 오른쪽 아래칸 순서대로 방문하면 Z모양이다. ![img](https://www.acmicpc.net/upload/201003/z1.JPG) 만약, 2차원 배열의 크기가 2^N * 2^N라서 왼쪽 위에 있는 칸이 하나가 아니라면, 배열을 4등분 한 후에 (크기가 같은 2^(N-1)로) 재귀적으로 순서대로 방문한다. 다음 예는 2^2 * 2^2 크기의 배열을 방문한 순서이다. ![img](https://www.acmicpc.net/upload/201003/z2.JPG) N이 주어졌을 때, (r, c)를 몇 번째로 방문하는지 출력하는 프로그램을 작성하시오. 다음 그림은 N=3일 때의 예이다. ![img](https://www.acmicpc.net/upload/201003/z3.JPG) ## 입력 첫째 줄에 N r c가 주어진다. N은 15보다 작거나 같은 자연수이고, r과 c는 0보다 크거나 같고, 2^N-1보다 작거나 같은 정수이다 ## pesudo code 총 모눈의 크기(L) = 2^(N) target 위치 = (r, c) 위치가 (N-1,N-1) = H 인 모눈을 기준으로, (r, c) 모두 H 보다 같거나 작으면 case 01 case 01: (L/2) 안에서의 target 좌표의 순서와 동일. r은 H보다 크고 c는 H보다 같거나 작으면 case 02 case 02: (L/2)안에서의 (target 좌표 - (N,0) )의 순서 + (L/2)^2 와 동일 c는 H보다 크고 r은 H보다 같거나 작으면 case 03 case 03 : (L/2)안에서의 (target 좌표 -(0,N) )의 순서 + ((L/2)^2)*2 와 동일 모두 H보다 크면 case 04 case 04: (L/2) 안에서의 (target 좌표 - (N,N)) 의 순서 + ((L/2)^2)*3 와 동일 모든 캐이스는 최소단위를 도달할떄까지 재귀적으로 반복된다! ================================================ FILE: BOJ/solved.ac_class/Class03/1074.Z/sAp00n.py ================================================ from sys import stdin def z(size_of_mat, target): if size_of_mat == 2: # minimal case #print(f'minimal_case') if target == (0, 0): #print(0) return 0 elif target == (1, 0): #print(1) return 1 elif target == (0, 1): #print(2) return 2 else: #print(3) return 3 else: #print('recursion') mid_ind = (size_of_mat / 2 - 1, size_of_mat / 2 - 1) if target[0] <= mid_ind[0] and target[1] <= mid_ind[1]: new_size = int((size_of_mat / 2)) #print(f'case01\nz({new_size}, {target})') return z(new_size, target) elif target[0] > mid_ind[0] and target[1] <= mid_ind[1]: new_size = int(size_of_mat / 2) new_target = int(target[0] - (size_of_mat / 2)), target[1] #print(f'case02\n{new_size ** 2} + z({new_size},{new_target})') return new_size ** 2 + z(new_size, new_target) elif target[0] <= mid_ind[0] and target[1] > mid_ind[1]: new_target = int(target[0]), int(target[1] - (size_of_mat / 2)) new_size = int(size_of_mat / 2) return (new_size ** 2) * 2 + z(new_size, new_target) else: new_target = int(target[0] - (size_of_mat / 2)), int(target[1] - (size_of_mat / 2)) new_size = int(size_of_mat / 2) return (new_size ** 2) * 3 + z(new_size, new_target) size_of_mat, x, y = map(int, stdin.readline().split()) size_of_mat = 2 ** size_of_mat #print(size_of_mat) print(z(size_of_mat, (y, x))) ================================================ FILE: BOJ/solved.ac_class/Class03/11279.최대 힙/sAp00n.py ================================================ # https://www.acmicpc.net/problem/11279 """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 1 초 (추가 시간 없음) 256 MB 19260 7805 5872 43.512% 문제 널리 잘 알려진 자료구조 중 최대 힙이라는 것이 있다. 최대 힙을 이용하여 다음과 같은 연산을 지원하는 프로그램을 작성하시오. 배열에 자연수 x를 넣는다. 배열에서 가장 큰 값을 출력하고, 그 값을 배열에서 제거한다. 프로그램은 처음에 비어있는 배열에서 시작하게 된다. 입력 첫째 줄에 연산의 개수 N(1≤N≤100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0이라면 배열에서 가장 큰 값을 출력하고 그 값을 배열에서 제거하는 경우이다. 입력되는 자연수는 2^31보다 작다. 출력 입력에서 0이 주어진 회수만큼 답을 출력한다. 만약 배열이 비어 있는 경우인데 가장 큰 값을 출력하라고 한 경우에는 0을 출력하면 된다. """ # 간단하게 내부구조는 최소힙으로 구현하되, 입출력시에 데이터에 -1을 곱하여 구현 할 수 있다. from sys import stdin import heapq N = int(stdin.readline()) max_heap = [] for _ in range(N): x = int(stdin.readline()) if x != 0: heapq.heappush(max_heap,-x) elif x == 0 and len(max_heap) > 0: print(-heapq.heappop(max_heap)) else: print(0) ================================================ FILE: BOJ/solved.ac_class/Class03/11399. ATM/sAp00n.py ================================================ # https://www.acmicpc.net/problem/11399 """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 1 초 256 MB 31901 20303 16990 65.076% 문제 인하은행에는 ATM이 1대밖에 없다. 지금 이 ATM앞에 N명의 사람들이 줄을 서있다. 사람은 1번부터 N번까지 번호가 매겨져 있으며, i번 사람이 돈을 인출하는데 걸리는 시간은 Pi분이다. 사람들이 줄을 서는 순서에 따라서, 돈을 인출하는데 필요한 시간의 합이 달라지게 된다. 예를 들어, 총 5명이 있고, P1 = 3, P2 = 1, P3 = 4, P4 = 3, P5 = 2 인 경우를 생각해보자. [1, 2, 3, 4, 5] 순서로 줄을 선다면, 1번 사람은 3분만에 돈을 뽑을 수 있다. 2번 사람은 1번 사람이 돈을 뽑을 때 까지 기다려야 하기 때문에, 3+1 = 4분이 걸리게 된다. 3번 사람은 1번, 2번 사람이 돈을 뽑을 때까지 기다려야 하기 때문에, 총 3+1+4 = 8분이 필요하게 된다. 4번 사람은 3+1+4+3 = 11분, 5번 사람은 3+1+4+3+2 = 13분이 걸리게 된다. 이 경우에 각 사람이 돈을 인출하는데 필요한 시간의 합은 3+4+8+11+13 = 39분이 된다. 줄을 [2, 5, 1, 4, 3] 순서로 줄을 서면, 2번 사람은 1분만에, 5번 사람은 1+2 = 3분, 1번 사람은 1+2+3 = 6분, 4번 사람은 1+2+3+3 = 9분, 3번 사람은 1+2+3+3+4 = 13분이 걸리게 된다. 각 사람이 돈을 인출하는데 필요한 시간의 합은 1+3+6+9+13 = 32분이다. 이 방법보다 더 필요한 시간의 합을 최소로 만들 수는 없다. 줄을 서 있는 사람의 수 N과 각 사람이 돈을 인출하는데 걸리는 시간 Pi가 주어졌을 때, 각 사람이 돈을 인출하는데 필요한 시간의 합의 최솟값을 구하는 프로그램을 작성하시오. 입력 첫째 줄에 사람의 수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄에는 각 사람이 돈을 인출하는데 걸리는 시간 Pi가 주어진다. (1 ≤ Pi ≤ 1,000) 출력 첫째 줄에 각 사람이 돈을 인출하는데 필요한 시간의 합의 최솟값을 출력한다. """ # sort 후 누적합을 구하면 해결 from sys import stdin N = int(stdin.readline()) time_list = sorted(list(map(int, stdin.readline().split()))) temp = 0 return_value = 0 for idx in range(len(time_list)): temp += time_list[idx] return_value += temp print(return_value) ================================================ FILE: BOJ/solved.ac_class/Class03/11723.집합/sAp00n.py ================================================ # https://www.acmicpc.net/problem/11723 """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 1.5 초 4 MB (하단 참고) 24904 7507 5181 29.779% 문제 비어있는 공집합 S가 주어졌을 때, 아래 연산을 수행하는 프로그램을 작성하시오. add x: S에 x를 추가한다. (1 ≤ x ≤ 20) S에 x가 이미 있는 경우에는 연산을 무시한다. remove x: S에서 x를 제거한다. (1 ≤ x ≤ 20) S에 x가 없는 경우에는 연산을 무시한다. check x: S에 x가 있으면 1을, 없으면 0을 출력한다. (1 ≤ x ≤ 20) toggle x: S에 x가 있으면 x를 제거하고, 없으면 x를 추가한다. (1 ≤ x ≤ 20) all: S를 {1, 2, ..., 20} 으로 바꾼다. empty: S를 공집합으로 바꾼다. 입력 첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다. 둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다. 출력 check 연산이 주어질때마다, 결과를 출력한다. """ # 비트 마스킹으로 풀이. # 다중 if문을 피할 수 있는 방법이 있었을까? => 함수 선언하여 캡슐화 해야했을지 고민 from sys import stdin M = int(stdin.readline()) set = bin(1048576) # print(set) commend_list = ['add', 'remove', 'check', 'toggle', 'all', 'empty'] for _ in range(M): commend = stdin.readline().split() commend_idx = commend_list.index(commend[0]) binary_set = int(set, 2) commend_num = int(commend[1]) if commend_idx == 0: set = bin(binary_set | (1 << commend_num)) elif commend_idx == 1: set = bin(binary_set & ~(1 << commend_num)) elif commend_idx == 2: temp = int(bin(binary_set & (1 << commend_num)), 2) if temp > 0: print(1) else: print(0) elif commend_idx == 3: set = bin(binary_set ^ (1 << commend_num)) elif commend_idx == 4: set = bin(2097151) else: set = bin(1048576) ================================================ FILE: BOJ/solved.ac_class/Class03/11724.연결 요소의 개수/sAp00n.py ================================================ # https://www.acmicpc.net/problem/11724 """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 3 초 512 MB 33586 16421 10655 46.016% 문제 방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오. 입력 첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다. 출력 첫째 줄에 연결 요소의 개수를 출력한다. """ # 전체 node를 포함하는 checklist를 만들고, 거기서 방문하지 않은 노드를 뽑아 BFS를 시작하는 root 노드로 두어, # 모든 노드를 순회할때까지 반복한다. BFS를 한번 완료할때마다 연결 요소의 개수는 +1 되는것. from sys import stdin from collections import deque def bfs(que, graph, check_list): while len(que) > 0: current_node = que[0] link_list = graph[current_node] for linked_node in link_list: if not check_list[linked_node]: check_list[linked_node] = True que.append(linked_node) que.popleft() def sol(): N, M = map(int, stdin.readline().split()) check_list = [True] + [False] * N graph = {} for i in range(1, N + 1): graph[i] = [i] for j in range(M): node01, node02 = map(int, stdin.readline().split()) graph[node01].append(node02) graph[node02].append(node01) num_of_cc = 0 while False in check_list: que = deque() que.append(check_list.index(False)) bfs(que, graph, check_list) num_of_cc += 1 return num_of_cc print(sol()) ================================================ FILE: BOJ/solved.ac_class/Class03/11726.2xn 타일링/sAp00n.py ================================================ # https://www.acmicpc.net/problem/11726 """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 1 초 256 MB 67991 25075 18388 34.633% 문제 2×n 크기의 직사각형을 1×2, 2×1 타일로 채우는 방법의 수를 구하는 프로그램을 작성하시오. 입력 첫째 줄에 n이 주어진다. (1 ≤ n ≤ 1,000) 출력 첫째 줄에 2×n 크기의 직사각형을 채우는 방법의 수를 10,007로 나눈 나머지를 출력한다. """ # 제대로 코드 짯는데 뎁스 터져버리는 경험은 처음이였다. # 다행이 이전에 최대 깊이 수정하는 방법을 알아둬서 그걸로 풀이 완료. # 재귀적으로 구현하면 생각이 편해져서 좋긴 한데, 다른 방법으로 풀이하는것도 연습해야할꺼같다. import sys sys.setrecursionlimit(2000) def sol(): n = int(sys.stdin.readline()) global memo memo = {0: 0, 1: 1, 2: 2} print(cal(n) % 10007) def cal(n): global memo if n in memo: return memo[n] memo[n] = cal(n - 1) + cal(n - 2) return memo[n] sol() ================================================ FILE: BOJ/solved.ac_class/Class03/1463.1로 만들기/sAp00n.md ================================================ ### 1로 만들기 ### 문제 정수 X에 사용할 수 있는 연산은 다음과 같이 세 가지 이다. 1. X가 3으로 나누어 떨어지면, 3으로 나눈다. 2. X가 2로 나누어 떨어지면, 2로 나눈다. 3. 1을 뺀다. 정수 N이 주어졌을 때, 위와 같은 연산 세 개를 적절히 사용해서 1을 만들려고 한다. 연산을 사용하는 횟수의 최솟값을 출력하시오. ### 입력 첫째 줄에 1보다 크거나 같고, 106보다 작거나 같은 정수 N이 주어진다. ### 출력 첫째 줄에 연산을 하는 횟수의 최솟값을 출력한다. ### sudo code n* = n/3 if n%3 == 0 else n/2 n%2 ==0 else n phase 01: ​ case 01 n* == n ​ n = n-1 , turn += 2 ​ go to start again ​ case 02 ​ n = n* , turn += 1 phase 02: ​ case 03 n** < (n-1) * ​ n = n** ​ turn += 1 ​ go to start again ​ case 04 n** < (n-1) * ​ n = (n - 1)* ​ go to start again /// 반례 있음.... 무조건 3으로 나눈다고 최적해가 찾아지는게 아니다. ``` 입력 정답 출력 321 9 10 609 10 11 642 10 11 643 11 12 645 11 12 963 10 11 ``` 반례들.. 그래서 그냥 BFS느낌으로 모든 경우의수 찾아가며 계산하기로함. 그와중 나눠 떨어지지 않는 경우는 필요 없으니까 None으로 표시뒤에 순차검색하며 걸러낸다. 이 풀이방식이 DP가 맞을까...? ================================================ FILE: BOJ/solved.ac_class/Class03/1463.1로 만들기/sAp00n.py ================================================ from sys import stdin from collections import deque def sol(): input_num = int(stdin.readline()) if input_num == 1: print(0) return que = deque() n = 0 que.append([input_num]) while True: list_to_compute = que.pop() # print(f'list to compute : {list_to_compute}') result = [] temp = [] for ele in list_to_compute: temp += [ele // 2 if ele % 2 == 0 else None, ele // 3 if ele % 3 == 0 else None, ele - 1] for i in temp: if i is None: continue result.append(i) # print(f'temp : {temp} result : {result}') n += 1 if 1 in result: return print(n) que += [result] sol() ================================================ FILE: BOJ/solved.ac_class/Class03/1620.나는야 포캣몬 마스터 이다솜/sAp00n.py ================================================ from sys import stdin i, j = map(int, stdin.readline().split()) name2_num = {} num2_name = {} for num in range(1, i+1): number = str(num) name = stdin.readline().strip('\n') name2_num[name] = number num2_name[number] = name #print(name2_num) #print(num2_name) for case in range(j): input_str = stdin.readline().strip('\n') if input_str in num2_name: print(num2_name[input_str]) else: print(name2_num[input_str]) ================================================ FILE: BOJ/solved.ac_class/Class03/1697.숨바꼭질/sAp00n.py ================================================ from sys import stdin from collections import deque def sol(): N, K = map(int, stdin.readline().split()) size_of_space = max(N, K) size_of_space = size_of_space + (size_of_space // 2) + 2 #print(f'size_of space : {size_of_space}') if N == K: print(0) return space = [0 for i in range(1, size_of_space)] que = deque([[N]]) #print(que) times = 0 while True: times += 1 current = que.pop() #print(current) travable = [] for node in current: if node - 1 == K or node + 1 == K or node * 2 == K: print(times) return if node - 1 >= 0: if space[node - 2] == 0 or space[node - 2] > times: space[node - 2] = times travable.append(node - 1) if node + 1 < size_of_space: if space[node] == 0 or space[node] > times: space[node] = times travable.append(node + 1) if node * 2 < size_of_space: if space[(node * 2) - 1] == 0 or space[(node * 2) - 1] > times: space[(node * 2) - 1] = times travable.append(node * 2) que.append(travable) sol() ================================================ FILE: BOJ/solved.ac_class/Class03/1697.숨바꼭질/test_case.md ================================================ TEST CASE #1: 6 16 exp -> 3 you -> 6 TEST CASE #2: 8 20 exp -> 3 you -> 5 TEST CASE #3: 15964 89498 exp -> 4781 you -> 19110 3 43 출력: 7 정답: 6 3 -> 6 -> 12 -> 11 -> 22 -> 44 -> 43 4 27 출력: 6 정답: 5 4 -> 8 -> 7 -> 14 -> 28 -> 27 5 35 출력: 6 정답: 5 5 -> 10 -> 9 -> 18 -> 36 -> 35 6 43 출력: 6 정답: 5 6 -> 12 -> 11 -> 22 -> 44 -> 43 7 43 출력: 7 정답: 6 7 -> 6 -> 12 -> 11 -> 22 -> 44 -> 43 ================================================ FILE: BOJ/solved.ac_class/Class03/1764.듣보잡/sAp00n.py ================================================ from sys import stdin N, M = map(int, stdin.readline().split()) non_heard_list = [stdin.readline().strip('\n') for _ in range(N)] non_seen_dict = {} return_list = [] for i in range(M): name = stdin.readline().strip('\n') non_seen_dict[name] = True #print(f'non_seen: {non_seen_dict} non_heard: {non_heard_list}') return_list = [ name for name in non_heard_list if non_seen_dict.get(name) ].sorted() print(len(return_list)) for name in return_list: print(name) ================================================ FILE: BOJ/solved.ac_class/Class03/18870.좌표 압축/sAp00n.py ================================================ # https://www.acmicpc.net/problem/18870 """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 2 초 512 MB 1772 1072 758 62.387% 문제 수직선 위에 N개의 좌표 X1, X2, ..., XN이 있다. 이 좌표에 좌표 압축을 적용하려고 한다. Xi를 좌표 압축한 결과 X'i의 값은 Xi > Xj를 만족하는 서로 다른 좌표의 개수와 같아야 한다. X1, X2, ..., XN에 좌표 압축을 적용한 결과 X'1, X'2, ..., X'N를 출력해보자. 입력 첫째 줄에 N이 주어진다. 둘째 줄에는 공백 한 칸으로 구분된 X1, X2, ..., XN이 주어진다. 출력 첫째 줄에 X'1, X'2, ..., X'N을 공백 한 칸으로 구분해서 출력한다. 제한 1 ≤ N ≤ 1,000,000 -109 ≤ Xi ≤ 109 """ # 사실 아직 잘 모르겠다. 좌표압축이라는 개념이 이런게 아닌거같은데? from sys import stdin N = int(stdin.readline()) coo_list = list(map(int, stdin.readline().split())) temp = [] dic = {} for coordinate in coo_list: if coordinate not in dic: dic[coordinate] = 0 temp.append(coordinate) temp.sort() for idx in range(len(temp)): dic[temp[idx]] = idx return_str = '' for idx in range(len(coo_list)): return_str += str(dic[coo_list[idx]]) + ' ' print(return_str[:-1]) ================================================ FILE: BOJ/solved.ac_class/Class03/1927.최소 힙/sAp00n.py ================================================ from sys import stdin import heapq min_heap = [] N = int(stdin.readline()) for _ in range(N): input_val = int(stdin.readline()) if input_val == 0: if len(min_heap) == 0: print(0) else: print(heapq.heappop(min_heap)) else: heapq.heappush(min_heap, input_val) ================================================ FILE: BOJ/solved.ac_class/Class03/1931. 회의실배정/sAp00n.py ================================================ from sys import stdin N = int(stdin.readline()) meeting_list = [] for idx in range(N): meeting_list.append(list(map(int, stdin.readline().split()))) meeting_list = sorted(meeting_list, key=lambda x: (x[1], x[0])) count = 0 last = 0 for meet in meeting_list: if last <= meet[0]: count += 1 last = meet[1] print(count) ================================================ FILE: BOJ/solved.ac_class/Class03/2630.색종이 만들기/sAp00n.py ================================================ from sys import stdin def recursion(mat, return_list): blue_count = 0 white_count = 0 for rows in mat: for ele in rows: if ele == 1: blue_count += 1 else: white_count += 1 if blue_count == 0 or white_count == 0: return_list.append(mat) return sliced_mat = slicer(mat) return [ recursion(sliced, return_list) for sliced in sliced_mat[:3]] def slicer(mat): len_of_mat = len(mat) half_len = len_of_mat // 2 return_list = [[], [], [], []] for i in range(len_of_mat): if i < half_len: return_list[0].append(mat[i][:half_len]) return_list[1].append(mat[i][half_len:]) else: return_list[2].append(mat[i][:half_len]) return_list[3].append(mat[i][half_len:]) return return_list N = int(stdin.readline()) mat = [list(map(int, stdin.readline().split())) for i in range(N)] result = [] recursion(mat,result) #print(result) b_count = 0 w_count = 0 for sliced in result: if sliced[0][0] == 1: b_count += 1 else: w_count += 1 print(f'{w_count}\n{b_count}') ================================================ FILE: BOJ/solved.ac_class/Class03/7576.토마토/sAp00n.py ================================================ from sys import stdin from collections import deque def sol(): M, N = map(int, stdin.readline().split()) warehouse = [] for row in range(N): warehouse.append(list(map(int, stdin.readline().split()))) print(warehouse) num_of_green_tomato = 0 que = deque() next_append = [] for row_idx in range(len(warehouse)): for ele_idx in range(len(warehouse[row_idx])): if warehouse[row_idx][ele_idx] == 1: next_append.append((ele_idx, row_idx)) elif warehouse[row_idx][ele_idx] == 0: num_of_green_tomato += 1 que.append(next_append) # print(f'que : {que} ngt : {num_of_green_tomato}\n') time = 0 if num_of_green_tomato == 0: print(time) return while len(que) > 0: time += 1 current_time_search = que.popleft() next_append = [] for searching_node in current_time_search: around_node_list = [(searching_node[0] - 1, searching_node[1]), (searching_node[0] + 1, searching_node[1]), (searching_node[0], searching_node[1] - 1), (searching_node[0], searching_node[1] + 1)] for node in around_node_list: if 0 <= node[0] <= M - 1 and 0 <= node[1] <= N - 1: if warehouse[node[1]][node[0]] == 0: next_append.append(node) warehouse[node[1]][node[0]] = 1 num_of_green_tomato -= 1 if num_of_green_tomato == 0: print(time) return continue if len(next_append) > 0: que.append(next_append) """print(f'current_searching_list: {current_time_search} time: {time}\nwarehouse') for row in warehouse: print(row) print('\n')""" if num_of_green_tomato != 0: print(-1) sol() ================================================ FILE: BOJ/solved.ac_class/Class03/7662.이중 우선순위 큐/sAp00n.py ================================================ from sys import stdin import heapq def sol(k): check = [False] * k min_heap = [] max_heap = [] for i in range(k): commend = stdin.readline().split() commend[1] = int(commend[1]) # print(commend) if commend[0] == 'I': # print(f'commend : {commend}') check[i] = True node = (commend[1], i) heapq.heappush(min_heap, node) node = (-commend[1], i) heapq.heappush(max_heap, node) if commend[0] == 'D': if len(min_heap) > 0: if commend[1] == 1: while max_heap: if not check[max_heap[0][1]]: heapq.heappop(max_heap) else: check[max_heap[0][1]] = False heapq.heappop(max_heap) break else: while min_heap: if not check[min_heap[0][1]]: heapq.heappop(min_heap) else: check[min_heap[0][1]] = False heapq.heappop(min_heap) break # print(f'commend : {commend} que : min => {min_heap} max => {max_heap} check: {check}') # print(f'loop end que:{deb_que}') # print(check) # print(f'{min_heap} {max_heap}') while min_heap and not check[min_heap[0][1]]: heapq.heappop(min_heap) while max_heap and not check[max_heap[0][1]]: heapq.heappop(max_heap) # print(f'{min_heap} {max_heap}') if len(min_heap) == 0: print('EMPTY') else: result = [] result.append(f'{-max_heap[0][0]} {min_heap[0][0]}' if max_heap and min_heap else 'EMPTY') print('\n'.join(result)) T = int(stdin.readline()) for _ in range(T): k = int(stdin.readline()) sol(k) ================================================ FILE: BOJ/solved.ac_class/Class03/9095.1, 2, 3 더하기/sAp00n.py ================================================ # https://www.acmicpc.net/problem/9095 """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 1 초 128 MB 50501 32144 21313 61.645% 문제 정수 4를 1, 2, 3의 합으로 나타내는 방법은 총 7가지가 있다. 합을 나타낼 때는 수를 1개 이상 사용해야 한다. 1+1+1+1 1+1+2 1+2+1 2+1+1 2+2 1+3 3+1 정수 n이 주어졌을 때, n을 1, 2, 3의 합으로 나타내는 방법의 수를 구하는 프로그램을 작성하시오. 입력 첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있고, 정수 n이 주어진다. n은 양수이며 11보다 작다. 출력 각 테스트 케이스마다, n을 1, 2, 3의 합으로 나타내는 방법의 수를 출력한다. """ # 재귀로 간단하게 구현이 가능함. 풀고 보니 DP 문제였다고 한다 from sys import stdin def compute(n): if n == 3: return 4 if n == 2: return 2 if n == 1: return 1 return compute(n - 1) + compute(n - 2) + compute(n - 3) def sol(): n = int(stdin.readline()) print(compute(n)) T = int(stdin.readline()) for _ in range(T): sol() ================================================ FILE: BOJ/solved.ac_class/Class04/1149.RGB거리/sAp00n.py ================================================ """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 0.5 초 (추가 시간 없음) 128 MB 50108 23747 17747 47.867% 문제 RGB거리에는 집이 N개 있다. 거리는 선분으로 나타낼 수 있고, 1번 집부터 N번 집이 순서대로 있다. 집은 빨강, 초록, 파랑 중 하나의 색으로 칠해야 한다. 각각의 집을 빨강, 초록, 파랑으로 칠하는 비용이 주어졌을 때, 아래 규칙을 만족하면서 모든 집을 칠하는 비용의 최솟값을 구해보자. 1번 집의 색은 2번 집의 색과 같지 않아야 한다. N번 집의 색은 N-1번 집의 색과 같지 않아야 한다. i(2 ≤ i ≤ N-1)번 집의 색은 i-1번, i+1번 집의 색과 같지 않아야 한다. 입력 첫째 줄에 집의 수 N(2 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 각 집을 빨강, 초록, 파랑으로 칠하는 비용이 1번 집부터 한 줄에 하나씩 주어진다. 집을 칠하는 비용은 1,000보다 작거나 같은 자연수이다. 출력 첫째 줄에 모든 집을 칠하는 비용의 최솟값을 출력한다. """ import sys N = int(sys.stdin.readline()) cost_list = [] for _ in range(N): cost_list.append(tuple(map(int, sys.stdin.readline().split()))) result_list = [cost_list[0]] for i in range(1, N): r_result = min(result_list[i - 1][1], result_list[i - 1][2]) + cost_list[i][0] g_result = min(result_list[i - 1][0], result_list[i - 1][2]) + cost_list[i][1] b_result = min(result_list[i - 1][0], result_list[i - 1][1]) + cost_list[i][2] result_list.append([r_result, g_result, b_result]) print(min(result_list[N - 1])) ================================================ FILE: BOJ/solved.ac_class/Class04/1176.트리의 지름/sAp00n.py ================================================ """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 2 초 256 MB 12127 4607 3364 36.609% 문제 트리의 지름이란, 트리에서 임의의 두 점 사이의 거리 중 가장 긴 것을 말한다. 트리의 지름을 구하는 프로그램을 작성하시오. 입력 트리가 입력으로 주어진다. 먼저 첫 번째 줄에서는 트리의 정점의 개수 V가 주어지고 (2≤V≤100,000)둘째 줄부터 V개의 줄에 걸쳐 간선의 정보가 다음과 같이 주어진다. (정점 번호는 1부터 V까지 매겨져 있다고 생각한다) 먼저 정점 번호가 주어지고, 이어서 연결된 간선의 정보를 의미하는 정수가 두 개씩 주어지는데, 하나는 정점번호, 다른 하나는 그 정점까지의 거리이다. 예를 들어 네 번째 줄의 경우 정점 3은 정점 1과 거리가 2인 간선으로 연결되어 있고, 정점 4와는 거리가 3인 간선으로 연결되어 있는 것을 보여준다. 각 줄의 마지막에는 -1이 입력으로 주어진다. 주어지는 거리는 모두 10,000 이하의 자연수이다. 출력 첫째 줄에 트리의 지름을 출력한다. """ # 가중치 있는 트리에서 BFS 두번 하면 되는 간단한 문제입니다. # 트리의 지름은 임의이 노드에서 가장 먼 가중치를 가지는 노드를 찾고, 그 노드에서 다시 가장 멀리 있는 노드를 찾으면 # 그 두 노드 사이의 거리가 항상 트리의 지름인 아이디어가 핵심. from sys import stdin from collections import deque def BFS(que, graph): md_node = 0 md = 0 result = {} while len(que) > 0: current_node = que.popleft() current_cost = que.popleft() if current_node in result: continue result[current_node] = current_cost if current_cost > md: md = current_cost md_node = current_node for idx in range(0, len(graph[current_node]), 2): que += [graph[current_node][idx], graph[current_node][idx + 1] + current_cost] return md, md_node def sol(): V = int(stdin.readline()) graph = {} node_list = [] for i in range(V): input_list = list(map(int, stdin.readline().split())) node = input_list[0] node_list.append(node) graph[node] = input_list[1:-1] que = deque([node_list[0], 0]) fst_max_distance, fst_node = BFS(que, graph) que = deque([fst_node, 0]) sec_max_distance, sec_node = BFS(que, graph) print(sec_max_distance) return sol() ================================================ FILE: BOJ/solved.ac_class/Class04/1629.곱셈/sAp00n.py ================================================ """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 0.5 초 (추가 시간 없음) 128 MB 29712 7434 5526 25.347% 문제 자연수 A를 B번 곱한 수를 알고 싶다. 단 구하려는 수가 매우 커질 수 있으므로 이를 C로 나눈 나머지를 구하는 프로그램을 작성하시오. 입력 첫째 줄에 A, B, C가 빈 칸을 사이에 두고 순서대로 주어진다. A, B, C는 모두 2,147,483,647 이하의 자연수이다. 출력 첫째 줄에 A를 B번 곱한 수를 C로 나눈 나머지를 출력한다. """ import sys sys.setrecursionlimit(100000) def sol(): A, B, C = map(int, sys.stdin.readline().split()) result = power(A, B, C) return result def power(A, B, C): if B == 1: return A % C temp = power(A, B // 2, C) if B % 2 == 1: return temp * temp * A % C return temp * temp % C print(sol()) ================================================ FILE: BOJ/solved.ac_class/Class04/1753.최단경로/sAp00n.py ================================================ """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 1 초 256 MB 71517 18521 8875 23.270% 문제 방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다. 입력 첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1≤V≤20,000, 1≤E≤300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1≤K≤V)가 주어진다. 셋째 줄부터 E개의 줄에 걸쳐 각 간선을 나타내는 세 개의 정수 (u, v, w)가 순서대로 주어진다. 이는 u에서 v로 가는 가중치 w인 간선이 존재한다는 뜻이다. u와 v는 서로 다르며 w는 10 이하의 자연수이다. 서로 다른 두 정점 사이에 여러 개의 간선이 존재할 수도 있음에 유의한다. 출력 첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i번 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF를 출력하면 된다. """ from sys import stdin import heapq V, E = map(int, stdin.readline().split()) graph = {i: [] for i in range(1, V + 1)} K = int(stdin.readline()) for _ in range(E): u, v, w = map(int, stdin.readline().split()) graph[u].append((v, w)) que = [] result = ['INF'] * V result[K - 1] = 0 heapq.heappush(que, (0, K)) # print(graph) while que: distance_from_root, current_node = heapq.heappop(que) for link_data in graph[current_node]: linked_node, distance_from_current = link_data if result[linked_node - 1] == 'INF' or result[linked_node - 1] > distance_from_current + distance_from_root: result[linked_node - 1] = distance_from_current + distance_from_root heapq.heappush(que, (distance_from_current + distance_from_root, linked_node)) for total_distance in result: print(total_distance) ================================================ FILE: BOJ/solved.ac_class/Class04/1786.찾기/sAp00n.py ================================================ """ 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 2 초 256 MB 19936 5619 3061 28.371% 문제 워드프로세서 등을 사용하는 도중에 찾기 기능을 이용해 본 일이 있을 것이다. 이 기능을 여러분이 실제로 구현해 보도록 하자. 두 개의 문자열 P와 T에 대해, 문자열 P가 문자열 T 중간에 몇 번, 어느 위치에서 나타나는지 알아내는 문제를 '문자열 매칭'이라고 한다. 워드프로세서의 찾기 기능은 이 문자열 매칭 문제를 풀어주는 기능이라고 할 수 있다. 이때의 P는 패턴이라고 부르고 T는 텍스트라고 부른다. 편의상 T의 길이를 n, P의 길이를 m 이라고 하자. 일반적으로, n>=m 이라고 가정해도 무리가 없다. n 0: temp += str(location_of_pattern[0]) for idx in range(1, len(location_of_pattern)): temp += ' ' + str(location_of_pattern[idx]) print(temp) def computelps(pattern, lps): length = 0 idx = 1 while idx < len(pattern): if pattern[idx] == pattern[length]: length += 1 lps[idx] = length idx += 1 else: if length != 0: length = lps[length - 1] else: lps[length] = 0 idx += 1 text = stdin.readline() pattern = stdin.readline().strip('\n') KMPSearch(pattern, text) ================================================ FILE: JSTestModule.js ================================================ const assert = require('assert').strict; module.exports = function (filePath, solution) { require(filePath).forEach(({ input, output }) => { assert.deepEqual(solution(...input), output); }); }; ================================================ FILE: LeetCode/Array/3Sum/6047198844.py ================================================ # i : first / l : second(left) / r : third(right) class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [] for i in range(len(nums)-2): if i > 0 and nums[i] == nums[i-1]: continue; l = i + 1 r = len(nums) - 1 while l < r : s = nums[i] + nums[l] + nums[r] if s > 0 : r += -1 elif s < 0 : l += 1 else: res.append((nums[i],nums[l],nums[r])) while l < r and nums[l] == nums[l+1]: l += 1 while l < r and nums[r] == nums[r-1]: r -= 1 l += 1 r -= 1 return res ================================================ FILE: LeetCode/Array/3Sum/HyeonJeong.py ================================================ class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums = sorted(nums) #1 if len(nums) < 3 : return [] slist = [] for i, a in enumerate(nums): for j, b in enumerate(nums[i+1:]): for c in nums[i+j+2:]: if a+b+c == 0: slist += [[a, b, c]] #1을 사용하지 않는 경우 '''if a<=b: if b<=c: slist += [[a, b, c]] elif c<=a: slist += [[c, a, b]] else: slist += [[a, c, b]] else: if a<=c: slist += [[b, a, c]] elif c<=b: slist += [[c, b, a]] else: slist += [[b, c, a]]''' answer = [] for x in slist: if x not in answer: answer += [x] return answer ================================================ FILE: LeetCode/Array/3Sum_Closet/6047198844.py ================================================ class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: nums.sort() dif = 10**3 + 1 res = 0 for i in range(len(nums)): #nums[i]는 무조건 더한다. #목표는 t를 만드는것. t = target - nums[i] left = i + 1 right = len(nums) - 1 while left < right: s = nums[left] + nums[right] if dif > abs(t-s): dif = abs(t-s) res = s + nums[i] #s가 target에 가깝게 조정되어야한다. if s > t: right -= 1 elif s <= t: left += 1 return res ================================================ FILE: LeetCode/Array/4Sum/6047198844.py ================================================ class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: answer = [] nums.sort() N = len(nums) for i in range(N): if i != 0 and nums[i-1] == nums[i]: continue for j in range(i+1,N): if j != i+1 and nums[j-1] == nums[j]: continue begin = j+1 end = N-1 while begin < end: s = nums[i] + nums[j] + nums[begin] + nums[end] if s == target: answer.append([nums[i],nums[j],nums[begin],nums[end]]) while begin < N-1 and nums[begin] == nums[begin+1]: begin += 1 while end > 0 and nums[end] == nums[end-1]: end -= 1 begin += 1 end -= 1 elif s < target: begin += 1 else: end -= 1 return answer ================================================ FILE: LeetCode/Array/Add_Two_Numbers/wongueShin/_test.dart ================================================ //import 'package:flutter_test/flutter_test.dart'; import './solution.dart'; List _setUpTest(List nums, int target) { final solution = Solution(); return solution.twoSum(nums, target); } /* TEST_CODE void main() { test( "case01", () => expect( _setUpTest([2, 7, 11, 15], 9), equals([0, 1]), ), ); test( "case02", () => expect( _setUpTest([3, 2, 4], 6), equals([1, 2]), ), ); test( "case03", () => expect( _setUpTest([3, 3], 6), equals([0, 1]), ), ); } */ ================================================ FILE: LeetCode/Array/Add_Two_Numbers/wongueShin/solution.dart ================================================ /* * RunTime 393ms * 78.54 % * ------------- * Memory 157.5MB * 48.85 % * */ class Solution { late final List _num; List? _searchFromCurrentIdx(int idx, int target) { for (int jdx = idx + 1; jdx < _num.length; jdx++) { if (_num[idx] + _num[jdx] == target) { //print("[$idx(= ${_num[idx]}), jdx(= ${_num[jdx]})] => ${_num[idx] + _num[jdx]} "); return [idx, jdx]; } } return null; } List twoSum(List nums, int target) { _num = nums; for (int idx = 0; idx < _num.length; idx++) { List? possibleAns = _searchFromCurrentIdx(idx, target); if (possibleAns != null) { return possibleAns; } } return [0, 1]; // 문제의 설명이 정확 하면 (적어도 하나의 해를 가진다면) 도달하지 않는 코드. } } ================================================ FILE: LeetCode/Array/Arranging_Coins/HyeonJeong.java ================================================ package LeetCode.Array.Arranging_Coins; class HyeonJeong { public int arrangeCoins(int n) { // 이진 탐색 이용 long left = 0, right = n, value, x; while (left <= right) { x = left + (right - left) / 2; value = x * (x + 1) / 2; if (value == n) return (int)x; else if (value > n) right = x-1; else left = x+1; } return (int)right; } } ================================================ FILE: LeetCode/Array/Array_Partition_I/6047198844.py ================================================ class Solution: def arrayPairSum(self, nums: List[int]) -> int: #짝수개의 n nums.sort() return sum(i for i in nums[::2]) ================================================ FILE: LeetCode/Array/Array_Partition_I/HyeonJeong.java ================================================ package LeetCode.Array.Array_Partition_I; import java.util.Arrays; class HyeonJeong { public int arrayPairSum(int[] nums) { /* 배열의 요소를 2개씩 묶은 그룹이 둘 중의 작은 수 값을 가질 때, 그룹들의 합계가 최대가 되는 합계 반환하는 문제 풀이 : 정렬한 배열에서 순서대로 두개씩 그룹을 만들면 그룹의 합계를 최대로 만들 수 있음 */ Arrays.sort(nums); int sum = 0; for (int i = 0; i < nums.length; i += 2) { sum += nums[i]; } return sum; } } ================================================ FILE: LeetCode/Array/Best_Time_to_Buy_and_Sell_Stock/6047198844.py ================================================ class Solution: def maxProfit(self, prices: List[int]) -> int: min_price = prices[0] res = 0 for i in range(1, len(prices)): tmp = prices[i] - min_price if tmp > res: res = tmp if min_price > prices[i]: min_price = prices[i] return res #100000 = 십만 #10000 = 만 #브루트 포스로 풀면안된다. ================================================ FILE: LeetCode/Array/Binary Search/6047198844.py ================================================ class Solution: def search(self, nums, target): l, r = 0, len(nums) - 1 while l <= r: mid = (l + r) // 2 if nums[mid] < target: l = mid + 1 elif nums[mid] > target: r = mid - 1 else: return mid return -1 ================================================ FILE: LeetCode/Array/Bulb_Switcher_III/HyeonJeong.py ================================================ class Solution: def numTimesAllBlue(self, light: List[int]) -> int: result = 0 check = [0]*len(light) # 노란색으로 변한(켜진) 전구는 1, 꺼진 전구는 0 max_index = 0 # 불이 켜진 전구 중 가장 오른쪽에 있는 전구의 번호(1~5) for i, x in enumerate(light): if x > max_index: max_index = x check[x-1] = 1 if max_index <= i+1 and sum(check[:max_index]) == max_index: # 왼쪽이 연속적으로 켜져서 파란색으로 변하는 경우 result += 1 return result ================================================ FILE: LeetCode/Array/Capacity To Ship Packages Within D Days/6047198844.cpp ================================================ class Solution { public: int shipWithinDays(vector& weights, int D) { int begin = *max_element(weights.begin(), weights.end()); int end = accumulate(weights.begin(), weights.end(), 0); //Day가 크다. -> 용량을 늘린다. //Day가 작다. -> 용량을 줄인다. while (begin < end) { int capa = 0; int day = 1; //중요 int mid = (begin + end) / 2; for (int i = 0; i < weights.size(); i++) { capa += weights[i]; if (capa > mid) { capa = weights[i]; day++; } } if (day <= D) { end = mid; } else { begin = mid + 1; } } return begin; } }; ================================================ FILE: LeetCode/Array/Combination_Sum/6047198844.py ================================================ class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: def dfs(idx: int, acc: int, elements: List): # pruning if acc > target: return if idx == len(candidates): if target == sum(elements): result.append(elements) return # 현재 인덱스 선택. 또 선택가능 dfs(idx, acc + candidates[idx], elements + [candidates[idx]]) # 현재 인덱스 선택 거부 dfs(idx + 1, acc, elements) result = [] dfs(0, 0, []) return result ================================================ FILE: LeetCode/Array/Combination_Sum/JeongShin.js ================================================ /** * @param {number[]} candidates * @param {number} target * @return {number[][]} * 모든 조합 중복 X */ const combinationSum = function (candidates, target) { const len = candidates.length; const answer = []; candidates.sort((a, b) => b - a); const combination = (array, sum, idx) => { if (target <= sum) return target === sum ? answer.push(array) : null; for (let i = idx; i < len; i++) { const v = candidates[i]; if (v < array[0] || 0) continue; combination([v, ...array], sum + v, idx); } }; combination([], 0, 0); return answer; }; /* LeetCode 에서 참고한 풀이 */ const combinationSum_2 = (candidates, target) => { const answer = []; candidates.sort((a, b) => a - b); backtrack(candidates, [], 0, target, answer); return answer; }; function backtrack(candidates, arr, idx, remain, answer, len = candidates.length) { if (remain <= 0) return remain === 0 ? answer.push(arr) : null; for (let i = idx; i < len; i++) { const curr = candidates[i]; arr.push(curr); backtrack(candidates, [...arr], i, remain - curr, answer, len); arr.pop(); } } combinationSum2([2, 3, 6, 7], 7); ================================================ FILE: LeetCode/Array/Combination_Sum_II/JeongShin.js ================================================ /** * @param {number[]} candidates * @param {number} target * @return {number[][]} * 모든 조합 중복 O */ const combinationSum2 = function (candidates, target) { candidates.sort((a, b) => a - b); let answer = []; const len = candidates.length; let dfs = function (idx, num, arr) { if (num === 0) return answer.push(arr); for (let i = idx; i < len; i++) { const curr = candidates[i]; if (curr <= num) { dfs(i + 1, num - curr, [...arr, curr]); } while (candidates[i + 1] === candidates[i]) i++; } return answer; }; dfs(0, target, []); return answer; }; /* LeetCode 참고한 코드 */ const combinationSum2_2 = (candidates, target) => { const answer = []; candidates.sort((a, b) => a - b); backtrack(candidates, [], 0, target, answer); return answer; }; function backtrack(candidates, arr, idx, remain, answer, len = candidates.length) { if (remain <= 0) return remain === 0 ? answer.push(arr) : null; for (let i = idx; i < len; i++) { const curr = candidates[i]; arr.push(curr); backtrack(candidates, [...arr], i + 1, remain - curr, answer, len); arr.pop(); while (candidates[i + 1] === candidates[i]) i++; } } const candidates = [10, 1, 2, 7, 6, 1, 5], target = 8; combinationSum2_2(candidates, target); // [ // [1, 7], // [1, 2, 5], // [2, 6], // [1, 1, 6] // ] ================================================ FILE: LeetCode/Array/Construct Binary Tree from Inorder and Postorder Traversal/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* build (int postIdx, int inBeginIdx, int inEndIdx, vector& inorder, vector& postorder){ TreeNode* root = NULL; if(inBeginIdx < inEndIdx){ int rootValue = postorder[postIdx]; root = new TreeNode(rootValue); int i = find(inorder.begin()+inBeginIdx, inorder.begin()+inEndIdx, rootValue) - inorder.begin(); int leftNum = i - inBeginIdx; int rightNum = inEndIdx - inBeginIdx - leftNum - 1; root->left = build (postIdx-1-rightNum, inBeginIdx, i, inorder, postorder); root->right = build (postIdx-1, i+1, inEndIdx, inorder, postorder); } return root; } TreeNode* buildTree(vector& inorder, vector& postorder) { return build (postorder.size()-1, 0, inorder.size(), inorder, postorder); } }; ================================================ FILE: LeetCode/Array/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* build(int rootIdx, int inbegin, int inend, vector& preorder, vector& inorder) { TreeNode* root = NULL; if (inbegin <= inend&&rootIdxleft = build(rootIdx + 1, inbegin, i - 1, preorder, inorder); root->right = build(rootIdx + 1 + i - inbegin, i + 1, inend, preorder, inorder); } return root; } TreeNode* buildTree(vector& preorder, vector& inorder) { return build(0, 0, inorder.size() - 1, preorder, inorder); } }; ================================================ FILE: LeetCode/Array/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if preorder: root = TreeNode(preorder[0]) #루트 인덱스 == 왼쪽 서브트리 개수 root_idx = inorder.index(root.val) #preorder 왼쪽 서브트리 시작(1) ~ 왼쪽 서브트리 끝(1+왼쪽 서브트리 개수) #inorder 루트 기준 왼쪽(처음~루트인덱스(루트 제외)) root.left = self.buildTree(preorder[1:1+root_idx], inorder[:root_idx]) #preorder 오른쪽 서브트리 시작(root_idx+1) ~ 오른쪽 서브트리 끝 #inorder 루트 기준 오른쪽(루트 오른쪽 ~ 끝) root.right = self.buildTree(preorder[root_idx+1:], inorder[root_idx+1:]) return root ================================================ FILE: LeetCode/Array/Container_With_Most_Water/6047198844.py ================================================ class Solution: def maxArea(self, height: List[int]) -> int: begin = 0 end = len(height) - 1 res = 0 while begin < end: res = max(res,(end-begin)*min(height[begin],height[end])) if height[begin] < height[end]: begin+=1 else: end-=1 return res ================================================ FILE: LeetCode/Array/Contains_Duplicate/6047198844.py ================================================ class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(nums) != len(set(nums)) ================================================ FILE: LeetCode/Array/Contains_Duplicate/HyeonJeong.py ================================================ class Solution: def containsDuplicate(self, nums: List[int]) -> bool: nlist = sorted(nums) length = len(nlist) for i in range(length-1): if nlist[i] == nlist[i+1]: return True return False ================================================ FILE: LeetCode/Array/Count_Negative_Numbers_in_a_Sorted_Matrix/6047198844.cpp ================================================ class Solution { public: int countNegatives(vector>& grid) { int res = 0; for(auto g : grid){ res += upper_bound(g.rbegin(),g.rend(),-1) - g.rbegin(); } return res; } }; ================================================ FILE: LeetCode/Array/Create_Target_Array_in_the_Given_Order/HyeonJeong.py ================================================ class Solution: # nums의 값을 target[nums의 인덱스와 같은 위치의 index값]에 넣어서 리스트를 반환하는 문제 def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: target = [] for i, n in enumerate(index): target = target[:n] + [nums[i]] + target[n:] return target ================================================ FILE: LeetCode/Array/Distance_Between_Bus_Stops/6047198844.py ================================================ class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: # 시계 방향으로 start에서 destination까지 clockwise_start = start clockwise_distance = 0 while clockwise_start != destination: clockwise_distance += distance[clockwise_start] clockwise_start += 1 clockwise_start = (clockwise_start % len(distance)) print(clockwise_distance) # 반시계 방향으로 start에서 destination까지 counterclockwise_start = start counterclockwise_distance = 0 while counterclockwise_start != destination: counterclockwise_start -= 1 counterclockwise_distance += distance[counterclockwise_start] counterclockwise_start = (counterclockwise_start % len(distance)) return min(clockwise_distance, counterclockwise_distance) ================================================ FILE: LeetCode/Array/Fair_Candy_Swap/HyeonJeong.java ================================================ package Fair_Candy_Swap; class HyeonJeong { public int[] fairCandySwap(int[] A, int[] B) { int sumA = 0, sumB = 0; int [] result = new int[2]; for (int a : A) { sumA += a; } for (int b : B) { sumB += b; } for (int j = 0; j < A.length; j++) { for (int i = 0; i < B.length; i++) { if (sumA + 2*B[i] == sumB + 2*A[j]) { // 값의 변경 후 합이 같은지 result[0] = A[j]; result[1] = B[i]; break; } } } return result; } } ================================================ FILE: LeetCode/Array/Filter_Restaurants_by_Vegan-Friendly,_Price_and_Distance/6047198844.py ================================================ class Solution: def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]: filtered_list = [restaurant for restaurant in restaurants if (veganFriendly == 0 or restaurant[2] == veganFriendly) and restaurant[3]<=maxPrice and restaurant[4]<=maxDistance] print(filtered_list) filtered_list.sort(reverse=True, key=itemgetter(1,0)) res = list(zip(*filtered_list)) if res: return res[0] return res ================================================ FILE: LeetCode/Array/Find Numbers with Even Number of Digits/6047198844.py ================================================ class Solution: def findNumbers(self, nums: List[int]) -> int: res = 0 for num in nums: res += len(str(num)) % 2 == 0 return res ================================================ FILE: LeetCode/Array/Find the Highest Altitude/6047198844.py ================================================ class Solution: def largestAltitude(self, gain: List[int]) -> int: res = [0] for i in gain: res.append(res[-1] + i) return max(res) ================================================ FILE: LeetCode/Array/Find the Town Judge/6047198844.py ================================================ class Solution: def findJudge(self, n: int, trust: List[List[int]]) -> int: if n == 1: return 1 # 모든 주민이 믿는다. # B의개수 == n-1 == judge # A의개수 == 0 A = Counter([a for a, b in trust]) B = Counter([b for a, b in trust]).items() for b, b_count in B: if b_count == n-1 and A[b] == 0: return b return -1 ================================================ FILE: LeetCode/Array/Find_Common_Characters/HyeonJeong.py ================================================ class Solution: def commonChars(self, A: List[str]) -> List[str]: s = [] for a in A: s += [list(a)] result = [] for j in range(len(s[0])): for i in range(1, len(s)): if s[0][j] not in s[i]: break if i == len(s)-1: result += s[0][j] for x in range(1, len(s)): s[x].remove(s[0][j]) return result ================================================ FILE: LeetCode/Array/Find_First_and_Last_Position_of_Element_in_Sorted_Array/6047198844.py ================================================ class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: ans = [] begin = 0 end = len(nums) while begin < end: mid = (begin + end) // 2 if nums[mid] < target: begin = mid + 1 else: end = mid if not nums or begin == len(nums) or nums[begin] != target: ans.append(-1) else: ans.append(begin) begin = 0 end = len(nums) while begin < end: mid = (begin + end) // 2 if nums[mid] <= target: begin = mid + 1 else: end = mid if not nums or begin == 0 or nums[begin - 1] != target: ans.append(-1) else: ans.append(begin - 1) return ans ================================================ FILE: LeetCode/Array/Find_First_and_Last_Position_of_Element_in_Sorted_Array/HyeonJeong.py ================================================ class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: if target not in nums: return [-1, -1] return [nums.index(target), len(nums)-nums[-1::-1].index(target)-1] ================================================ FILE: LeetCode/Array/Find_Pivot_Index/HyeonJeong.java ================================================ package LeetCode.Array.Find_Pivot_Index; class HyeonJeong { public int pivotIndex(int[] nums) { int len = nums.length; for (int i = 0; i < len; i++) { int left = 0, right = 0; for (int j = 0; j < len; j++) { // 배열에서 기준 요소(nums[j])에 따라 양쪽 요소들의 합을 구함 if (j < i) left += nums[j]; else if (j > i) right += nums[j]; } if (left == right) return i; } return -1; } } ================================================ FILE: LeetCode/Array/Find_the_Duplicate_Number/6047198844.py ================================================ class Solution(object): def findDuplicate(self, nums): for i in range(len(nums)): if nums.count(nums[i])>1 : return nums[i] # How can we prove that at least one duplicate number must exist in nums? # Can you solve the problem without modifying the array nums? # Can you solve the problem using only constant, O(1) extra space? # Can you solve the problem with runtime complexity less than O(n2)? ================================================ FILE: LeetCode/Array/First Missing Positive/6047198844.py ================================================ def firstMissingPositive(self, nums): nums.append(0) n = len(nums) for i in range(n): if nums[i] < 0 or nums[i] >= n: nums[i] = 0 for i in range(n): # use the index as the hash to record the frequency of each number nums[nums[i] % n] += n for i in range(1, n): if nums[i] / n == 0: return i return n ================================================ FILE: LeetCode/Array/Flipping_an_Image/HyeonJeong.java ================================================ package LeetCode.Array.Flipping_an_Image; class HyeonJeong { public int[][] flipAndInvertImage(int[][] A) { int len = A.length, tmp; for (int i = 0; i < len; i++) { for (int j = 0; j < len/2; j++) { // 각 행을 역순으로 정렬하고 이미지를 반전시킨 상태가 되도록 함 tmp = A[i][j]; A[i][j]= (A[i][len-(j+1)] == 1)?0:1; A[i][len-(j+1)] = (tmp == 1)?0:1; } if (len%2 == 1) // 배열의 행 길이가 홀수일 때, 가운데 숫자의 이미지를 반전시킴 A[i][len/2] = (A[i][len/2] == 1)?0:1; } return A; } } ================================================ FILE: LeetCode/Array/Insert Interval/6047198844.py ================================================ class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: intervals.append(newInterval) intervals.sort() res = [] for interval in intervals: if not res or res[-1][1] < interval[0]: res.append(interval) else: res[-1][1] = max(res[-1][1], interval[1]) return res ================================================ FILE: LeetCode/Array/Intersection_of_Two_Arrays/HyeonJeong.py ================================================ class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: return set(nums1) & set(nums2) # set.intersection(set(nums1), set(nums2)) ================================================ FILE: LeetCode/Array/Jump Game/6047198844.py ================================================ sys.setrecursionlimit(10 ** 8) def jump(cur, dst, nums, memo) -> bool: if cur >= dst: return True if memo[cur] != -1: return memo[cur] memo[cur] = 0 for step in range(nums[cur], 0, -1): if jump(cur + step, dst, nums, memo): memo[cur] = 1 break return memo[cur] class Solution: def canJump(self, nums: List[int]) -> bool: memo = [-1] * len(nums) return jump(0, len(nums) - 1, nums, memo) ================================================ FILE: LeetCode/Array/Jump Game II/6047198844.py ================================================ class Solution: def jump(self, nums: List[int]) -> int: memo = [-1] * len(nums) def dp(idx): if idx == len(nums) - 1: return 0 if memo[idx] != -1: return memo[idx] memo[idx] = 9999999 for dx in range(1, nums[idx] + 1): if idx + dx < len(nums): memo[idx] = min(memo[idx], 1 + dp(idx + dx)) return memo[idx] return dp(0) ================================================ FILE: LeetCode/Array/Keyboard_Row/HyeonJeong.py ================================================ class Solution(object): def findWords(self, words): alpha = ["qwertyuiop", "asdfghjkl", "zxcvbnm"] result = [] for j, word in enumerate(words): word = list(set(word.lower())) for i, n in enumerate(alpha): if word[0] in n: index = i break state = 1 for x in word[1:]: if x not in alpha[index]: state = 0 break if state == 1: result += [words[j]] return result ================================================ FILE: LeetCode/Array/Kth_Missing_Positive_Number/HyeonJeong.py ================================================ class Solution: def findKthPositive(self, arr: List[int], k: int) -> int: # arr 배열에서 누락된 k번째 정수 반환하는 문제 result = 0 i = 0 while (k != -1): # k번째 정수가 반환되기 위해서 k=0까지 돌아가야함 if i not in arr: result = i k -= 1 i += 1 # max(arr) <= 1000이므로 i <= 1001+k return result ================================================ FILE: LeetCode/Array/Largest_Number_At_Least_Twice_of_Others/6047198844.py ================================================ class Solution: def dominantIndex(self, nums: List[int]) -> int: largest_number = max(nums) cnt = 0 for num in nums: if num != largest_number and num * 2 > largest_number: return -1 return nums.index(largest_number) ================================================ FILE: LeetCode/Array/Longest _Palindromic_Substring/6047198844.py ================================================ class Solution: def longestPalindrome(self, s: str) -> str: def expand(left: int, right: int) -> str: # left와 right를 가지고 투포인터 연산을 수행. while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left + 1:right] # 예외처리: 아래 알고리즘은 길이가 1일때 처리를 하지 못한다. # 인덱스 슬라이싱이 빠르므로 인덱스 슬라이싱을 이용한다. if len(s) < 2 or s[:] == s[::-1]: return s # i가 최대 len(s)-2까지 증가할수있다. result = '' for i in range(len(s) - 1): result = max(result, expand(i, i + 1), expand(i, i + 2), key=len) return result ================================================ FILE: LeetCode/Array/Longest_Common_Subsequence/JeongShin.js ================================================ /** * @param {string} text1 * @param {string} text2 * @return {number} */ const longestCommonSubsequence = function (text1, text2) { const len1 = text1.length, len2 = text2.length; const dp = []; for (let i = 0; i <= len1; i++) { dp[i] = []; for (let j = 0; j <= len2; j++) { if (i === 0 || j === 0) { dp[i][j] = 0; continue; } if (text1[i - 1] === text2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; continue; } dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } return dp[len1][len2]; }; longestCommonSubsequence("abcde", "ace"); longestCommonSubsequence("oxcpqrsvwf", "shmtulqrypy"); ================================================ FILE: LeetCode/Array/Lucky Numbers in a Matrix/6047198844.py ================================================ class Solution: def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: res = [] for y in range(len(matrix)): for x in range(len(matrix[0])): if matrix[y][x] == min(matrix[y]) and matrix[y][x] == max(list(zip(*matrix))[x]): res.append(matrix[y][x]) return res ================================================ FILE: LeetCode/Array/Marjority_Element/6047198844.py ================================================ class Solution: def majorityElement(self, nums: List[int]) -> int: return Counter(nums).most_common(1)[0][0] ================================================ FILE: LeetCode/Array/Marjority_Element/HyeonJeong.py ================================================ class Solution: def majorityElement(self, nums: List[int]) -> int: length = len(nums) s = list(set(nums)) # set으로 중복제거 for n in s: if nums.count(n) > length/2: # count()로 해당개수 찾아서 비교 return n ================================================ FILE: LeetCode/Array/Max_Consecutive_Ones/HyeonJeong.java ================================================ package LeetCode.Array.Max_Consecutive_Ones; class HyeonJeong { public int findMaxConsecutiveOnes(int[] nums) { int length = 0, i, j; for (i = 0; i < nums.length; i++) { if (nums[i] == 1) { for (j = i+1; j < nums.length; j++) { if (nums[j] != 1) { break; } } if (j-i > length) { length = j-i; } i = j; } } return length; } } ================================================ FILE: LeetCode/Array/Maximum_Ice_Cream_Bars/HyeonJeong.py ================================================ class Solution: def maxIceCream(self, costs: List[int], coins: int) -> int: if min(costs) > coins : return 0 costs.sort() result = 0 for cost in costs: if coins >= cost: coins -= cost result += 1 else: break return result ================================================ FILE: LeetCode/Array/Maximum_Subarray/6047198844.py ================================================ class Solution: def maxSubArray(self, nums: List[int]) -> int: for i in range(1,len(nums)): if nums[i-1] > 0: nums[i] += nums[i-1] return max(nums) ================================================ FILE: LeetCode/Array/Maximum_Swap/HyeonJeong.py ================================================ class Solution: def maximumSwap(self, num: int) -> int: # 정수의 두 자리를 최대 1번 바꿔서 최대의 수를 만드는 문제 # 0번 바꾸는 경우 : 이미 수가 만들어질 수 있는 최대와 같은지 비교 # 1번 바꾸는 경우 : 가장 높은 자리 수부터 최대 정수와 비교해 <처음으로 발견된 다른 자리인 수>와 <다른 자리 보다 아래 자리인 수 중 최대값(최대값이 2개 이상인 경우는 가장 낮은 자리 수)>의 자리를 바꿈 n = [int(x) for x in str(num)] sort_n = sorted(n, reverse = True) length = len(n) if sort_n == n: return num else: for i, m in enumerate(n): if m != sort_n[i]: tmp = n[i] n[i] = n[length-(n[-1::-1].index(max(n[i+1:]))+1)] # length-(n[-1::-1].index(max(n[i+1:]))+1) # : n 리스트의 현재 인덱스(i)의 뒤 리스트([i+1:])에서 최대값을 찾고, n 리스트의 뒤에서부터 최대값을 찾아서 가장 먼저 발견되는 인덱스 n[length-(n[-1::-1].index(max(n[i+1:]))+1)] = tmp break s = "" for c in n: s += str(c) return int(s) ================================================ FILE: LeetCode/Array/Merge_Intervals/6047198844.py ================================================ class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: ans = [] intervals = sorted(intervals, key=lambda L: (L[0], -L[1])) for nbegin, nend in intervals: #ans가 없는 경우 && 교집합이 없는 경우 if not ans or ans[-1][1] < nbegin: ans.append([nbegin, nend]) else: # 교집합을 구한다. # 교집합이 있는 경우 # 포함되는 경우. ans[-1][1] = ans[-1][1] if nend <= ans[-1][1] else nend return ans ================================================ FILE: LeetCode/Array/Merge_Intervals/HyeonJeong.py ================================================ class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals = list(set([tuple(x) for x in intervals])) # 2차원 리스트의 값에서 중복 제거 intervals = sorted(intervals, key =lambda x: x[0]) # 2차원 리스트의 첫번째 인자 값으로 정렬 length = len(intervals) i = 1 while i < length: if length == 1: break m = intervals[i-1] n = intervals[i] if m[0] <= n[0] <= m[1]: # 두 범위에 겹쳐지는 값이 있는지 확인 for i, cmp in enumerate(intervals): # 합쳐진 리스트가 추가될 위치 확인 if cmp[0] > m[0]: index = i-1 break elif i == len(intervals)-1: index = len(intervals) # 두 리스트가 큰 범위로 합쳐져서 추가됨 if m[1] <= n[1]: intervals.insert(index, [m[0], n[1]]) else: intervals.insert(index, [m[0], m[1]]) intervals.remove(m) intervals.remove(n) i = 1 # 리스트에 새로운 값이 추가 되었으므로 처음부터 다시 비교 length = len(intervals) else: i += 1 return intervals ================================================ FILE: LeetCode/Array/Merge_Intervals/kth496.kt ================================================ import kotlin.math.max class Solution { fun merge(intervals: Array): Array { val answer: MutableList = ArrayList(); intervals.sortWith(compareBy { it[0] }) var temp: IntArray? = null for (interval in intervals) { when { temp == null -> temp = interval temp[1] >= interval[0] -> temp[1] = max(temp[1], interval[1]) else -> { answer.add(temp) temp = interval } } } answer.add(temp) return answer.toTypedArray() } } ================================================ FILE: LeetCode/Array/Minimum_Number_of_Days_to_Make_m_Bouquets/6047198844.cpp ================================================ class Solution { public: int minDays(vector& bloomDay, int m, int k) { if(m*k > bloomDay.size()) return -1; vector Days = bloomDay; sort(Days.begin(),Days.end()); Days.erase(unique(Days.begin(),Days.end()),Days.end()); //Days에서 이분 탐색으로 고른다. int beginDay = 0; int endDay = Days.size()-1; while(beginDay < endDay){ int midDay = (beginDay + endDay) / 2; int bouquetsN = 0; int bloomN = 0; for(int i = 0; i < bloomDay.size(); i++){ if(bloomDay[i] <= Days[midDay]){ bloomN++; if(bloomN == k){ bouquetsN++; bloomN = 0; } }else{ bloomN = 0; } } //주어진 날짜로 못만들었을때 -> 날짜를 늘려야한다. if(bouquetsN < m) beginDay = midDay + 1; //주어진 날짜로 만들었을때 -> 날짜를 줄인다. else endDay = midDay; } return Days[beginDay]; } }; //100000 * lgN 1000 //100000000 //범위의 개념 ================================================ FILE: LeetCode/Array/Minimum_Path_Sum/6047198844.cpp ================================================ typedef pair> P; class Solution { private: const int INF = 987654321; public: int minPathSum(vector>& grid) { int m = grid.size(); int n = grid[0].size(); vector< vector > dist(m,vector(n,INF)); priority_queue < P , vector

, greater

> pq; dist[0][0] = grid[0][0]; pq.push({dist[0][0],{0,0}}); while(!pq.empty()){ int y = pq.top().second.first; int x = pq.top().second.second; int d = pq.top().first; // 0,0에서 y,x로 가는 최단 거리. pq.pop(); if(d > dist[y][x]) continue; if(y+1 < m &&(d+grid[y+1][x] < dist[y+1][x])){ dist[y+1][x] = d + grid[y+1][x]; pq.push({dist[y+1][x],{y+1,x}}); } if(x+1 < n &&(d+grid[y][x+1] < dist[y][x+1])){ dist[y][x+1] = d + grid[y][x+1]; pq.push({dist[y][x+1],{y,x+1}}); } } return dist[m-1][n-1]; } }; ================================================ FILE: LeetCode/Array/Minimum_Value_to_Get_Positive_Step_by_Step_Sum/6047198844.cpp ================================================ class Solution { public: int minStartValue(vector& nums) { for(int i = 1; i < nums.size(); i++) nums[i] += nums[i-1]; sort(nums.begin(),nums.end()); if(nums[0]<0) return -nums[0]+1; return 1; } }; ================================================ FILE: LeetCode/Array/Missing Number/6047198844.py ================================================ class Solution: def missingNumber(self, nums: List[int]) -> int: nums = set(nums) for i in range(len(nums)+1): if i not in nums: return i ================================================ FILE: LeetCode/Array/Missing_Number/HyeonJeong.py ================================================ class Solution: def missingNumber(self, nums: List[int]) -> int: for i in range(len(nums)+1): # for문은 O(n), len()은 O(1) 시간복잡도를 가짐 if i not in nums: return i ================================================ FILE: LeetCode/Array/Move_Zeroes/6047198844.py ================================================ class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ N = nums.count(0) for _ in range(N): nums.remove(0) nums.append(0) ================================================ FILE: LeetCode/Array/Peak_Index_in_a_Mountain_Array/6047198844.cpp ================================================ class Solution { public: int peakIndexInMountainArray(vector& arr) { int begin = 0; int end = arr.size()-1; while(begin < end){ int mid = begin - (begin - end) / 2; if(arr[mid-1] { if (!~arr.indexOf(v)) permutation(nums, [...arr, v], answer, len); }) } permute([1, 2, 3]); /* LeetCode 를 참고한 풀이 */ const permute = function (nums) { const answer = []; backtrack(answer, [], nums); return answer; }; function backtrack(answer, arr, nums, len = nums.length) { if (arr.length === len) return answer.push(arr); for (let i = 0; i < len; i++) { const curr = (nums[i]); if (arr.includes(curr)) continue; arr.push(curr); backtrack(answer, [...arr], nums, len); arr.pop(); } } ================================================ FILE: LeetCode/Array/Permutations_II/JeongShin.js ================================================ /** * @param {number[]} nums * @return {number[][]} * 모든 순열 단, 중복된 후보가 있음 */ /* 나의 풀이 */ const permuteUnique = function (nums) { const answer = []; const possible = {}; nums.sort((a, b) => a - b); for (const num of nums) possible[num] = (possible[num] || 0) + 1; backtrack(answer, [], nums, {}, possible); return answer; }; function backtrack(answer, arr, nums, visited, possible, len = nums.length) { if (arr.length === len) return answer.push(arr); for (let i = 0; i < len; i++) { const curr = nums[i]; if (visited[curr] === possible[curr]) continue; arr.push(curr); visited[curr] = (visited[curr] || 0) + 1; backtrack(answer, [...arr], nums, {...visited}, possible, len); arr.pop(); visited[curr] = visited[curr] - 1; while (nums[i] === nums[i + 1]) i++; } } permuteUnique([1, 1, 2]); /* LeetCode 를 참고한 풀이 */ const permuteUnique2 = (nums) => { const answer = []; const visited = []; nums.sort((a, b) => a - b); backtrack2(nums, visited, [], answer); return answer; }; function backtrack2(nums, visited, arr, answer, len = nums.length) { if (arr.length === len) return answer.push(arr); for (let i = 0; i < len; i++) { if (visited[i] || (i > 0 && nums[i - 1] === nums[i] && !visited[i - 1])) continue; arr.push(nums[i]); visited[i] = true; backtrack2(nums, visited, [...arr], answer, len); visited[i] = false; arr.pop(); } } ================================================ FILE: LeetCode/Array/Plus_One/6047198844.py ================================================ class Solution: def plusOne(self, digits: List[int]) -> List[int]: digits = [0] + digits digits[-1] += 1 N = len(digits) - 1 for i in range(N,-1,-1): digits[i-1] += digits[i] // 10 digits[i] %= 10 if digits[0] == 0: digits.pop(0) return digits ================================================ FILE: LeetCode/Array/Plus_One/HyeonJeong.py ================================================ class Solution: def plusOne(self, digits: List[int]) -> List[int]: digits[-1] += 1 i = len(digits)-1 while i >= 0: if digits[i] == 10: if i == 0: # 가장 앞의 인덱스가 10이 되는 경우 한자리가 되게 숫자(1과 0) 분리 digits.insert(0, 1) digits[i+1] = 0 else: digits[i-1] += 1 digits[i] = 0 i -= 1 ================================================ FILE: LeetCode/Array/Product_of_Array_Except_Self/6047198844.py ================================================ class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: #left를 구한다. left = [1] for i in range(len(nums)-1): left.append(left[-1]*nums[i]) right = [1] for i in range(len(nums)-1,0,-1): right.append(right[-1]*nums[i]) return [t[0]*t[1] for t in zip(left,right[::-1])] ================================================ FILE: LeetCode/Array/Remove Duplicates from Sorted Array II/6047198844.py ================================================ class Solution: def removeDuplicates(self, nums: List[int]) -> int: i = 0 #nums를 스택으로 쓰자. i는 top을 가리킨다. for num in nums: if i < 2 or nums[i-2] != num: nums[i] = num i += 1 return i ================================================ FILE: LeetCode/Array/Remove_Duplicates_from_Sorted_Array/6047198844.py ================================================ class Solution: def removeDuplicates(self, nums: List[int]) -> int: #삽입 idx idx = 0 for i in range(len(nums)): if i==0 or nums[i-1] != nums[i]: nums[idx] = nums[i] idx += 1 for _ in range(idx,len(nums)): nums.pop() ================================================ FILE: LeetCode/Array/Remove_Duplicates_from_Sorted_Array/HyeonJeong.py ================================================ class Solution: def removeDuplicates(self, nums: List[int]) -> int: i = 0 while i+1 < len(nums):# 중복되는 값을 지우다가 없는 인덱스에 접근하지 않게 종료 if nums[i] == nums[i+1]: # 중복되는 값 확인 del nums[i+1] # 해당 인덱스 위치의 값을 제거 i -= 1 # 다음 값들의 인덱스가 -1 됨 i += 1 return len(nums) ================================================ FILE: LeetCode/Array/Remove_Element/6047198844.py ================================================ class Solution: def removeElement(self, nums: List[int], val: int) -> int: #try: # while True: # nums.remove(val) #except ValueError: i = 0 for num in nums: if num != val: nums[i] = num i += 1 return i #참고 #https://hashcode.co.kr/questions/1158/%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EC%95%88%EC%97%90-%ED%8A%B9%EC%A0%95%EA%B0%92%EC%9D%84-%EB%8B%A4-%EC%A7%80%EC%9A%B0%EB%8A%94-%EB%B0%A9%EB%B2%95%EC%9D%B4-%EA%B6%81%EA%B8%88%ED%95%A9%EB%8B%88%EB%8B%A4 ================================================ FILE: LeetCode/Array/Richest_Customer_Wealth/HyeonJeong.java ================================================ package Richest_Customer_Wealth; class HyeonJeong { public int maximumWealth(int[][] accounts) { int result = 0; int []sum = new int[accounts.length]; for (int i = 0; i < accounts.length; i++) { sum[i] = 0; for (int j = 0; j < accounts[0].length; j++) { sum[i] += accounts[i][j]; } if (sum[i] > result) result = sum[i]; } return result; } } ================================================ FILE: LeetCode/Array/Rotate_Array/HyeonJeong.py ================================================ class Solution: def rotate(self, nums: List[int], k: int) -> None: for i in range(k): nums.insert(0, nums[-1]) nums.pop() return nums ================================================ FILE: LeetCode/Array/Rotate_Image/604798844.py ================================================ class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ N = len(matrix[0]) for step in range((N+1)//2): for d in range(N-2*step-1): matrix[step][step+d],matrix[step+d][N-1-step], matrix[N-1-step][N-1-step-d], matrix[N-1-step-d][step] = matrix[N-1-step-d][step], matrix[step][step+d], matrix[step+d][N-1-step], matrix[N-1-step][N-1-step-d] ''' a = matrix[step][step+d] b = matrix[step+d][N-1-step] c = matrix[N-1-step][N-1-step-d] d = matrix[N-1-step-d][step] N = 3 00 01 02 10 11 12 20 21 22 N = 4 00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33 ''' ================================================ FILE: LeetCode/Array/Running_Sum_of_1d_Array/HyeonJeong.py ================================================ class Solution: def runningSum(self, nums: List[int]) -> List[int]: return [sum([nums[j] for j in range(0, i)]) for i in range(1, len(nums)+1)] # 더해져야하는 마지막 번째 수가 1 ~ len(nums)+1 ================================================ FILE: LeetCode/Array/Search a 2D Matrix/6047198844.py ================================================ class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: m = len(matrix) n = len(matrix[0]) begin = 0 end = m * n - 1 while begin <= end: mid = (begin + end) // 2 search = matrix[mid // n][mid % n] if search < target: begin = mid + 1 elif search > target: end = mid - 1 else: return True return False ================================================ FILE: LeetCode/Array/Search_Insert_Position/HyeonJeong.py ================================================ class Solution: def searchInsert(self, nums: List[int], target: int) -> int: for i, n in enumerate(nums): if n == target: return i elif n > target: # 크기순으로 정리된 리스트에 target이 들어가게 되는 인덱스 위치 return i return len(nums) # target이 nums에 존재하지 않고, nums에서 가장 큰 수가 되는 경우에는 인덱스+1인 위치에 target이 들어가게 됨 ================================================ FILE: LeetCode/Array/Search_in_Rotated_Sorted_Array/6047198844.py ================================================ class Solution: def search(self, nums: List[int], target: int) -> int: begin = 0 end = len(nums) while begin < end: mid = (begin + end) // 2 cur = nums[mid] if (cur < nums[0]) != (target < nums[0]): if target < nums[0]: cur = -9876543210 else: cur = +9876543210 if cur < target: begin = mid + 1 elif cur > target: end = mid else: return mid return -1 ================================================ FILE: LeetCode/Array/Search_in_Rotated_Sorted_Array/HyeonJoeng.py ================================================ class Solution: def search(self, nums: List[int], target: int) -> int: if target not in nums: return -1 answer = [i for i, x in enumerate(nums) if x == target] return int(answer[0]) ================================================ FILE: LeetCode/Array/Set Matrix Zeroes/6047198844.py ================================================ class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ # 첫번째 행과 열로 0을 표현하자. -> 행의 첫번째에 0이있으면 그 행은 0으로 칠해져야한다는뜻이다. # 표현하는것은 좋다. 하지만 해당 행 자체가 0이였다면 -> 값이 왜곡되게 된다. flag로 표현한다. # 행의 첫번째나 열의 첫번째는 접근의 맨처음이므로 더렵혀지지않는다 -> 제대로된 flag를 가질수있다. # fr/fc는 순수 값이 0일때를 뜻한다. 0일때 True를가진다. fr = False fc = False m = len(matrix) n = len(matrix[0]) # 첫번째 행과 열을 0으로 칠하자. for i in range(m): for j in range(n): if matrix[i][j] == 0: # flag값 먼저 챙기자. if i == 0: fr = True if j == 0: fc = True matrix[i][0] = 0 matrix[0][j] = 0 # 첫번째 행과 열이 0일 경우 칠하기. 이때 범위에 유의한다. for i in range(1, m): for j in range(1, n): if matrix[i][0] == 0 or matrix[0][j] == 0: matrix[i][j] = 0 # flag값에 따른 첫번째 row / column칠하기 if fc: for i in range(m): matrix[i][0] = 0 if fr: for j in range(n): matrix[0][j] = 0 ================================================ FILE: LeetCode/Array/Single_Number/6047198844.py ================================================ import collections class Solution: def singleNumber(self, nums: List[int]) -> int: return collections.Counter(nums).most_common()[-1][0] ================================================ FILE: LeetCode/Array/Single_Number/HyeonJeong.java ================================================ package LeetCode.Array.Single_Number; import java.util.Arrays; class HyeonJeong { public int singleNumber(int[] nums) { Arrays.sort(nums); for (int i=0; i+1 List[int]: result = [] for n in nums: if n not in result: result.append(n) else: # 반복된 수는 결과 리스트에서 제거 result.remove(n) return result ================================================ FILE: LeetCode/Array/Sort Colors/6047198844.py ================================================ class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ red = 0 white = 0 blue = len(nums) - 1 # white를 움직이자 while white <= blue: color = nums[white] if color == 1: white += 1 elif color == 0: nums[red], nums[white] = nums[white], nums[red] red += 1 white += 1 else: nums[blue], nums[white] = nums[white], nums[blue] blue -= 1 return nums ================================================ FILE: LeetCode/Array/Sort_Array_By_Parity_II/HyeonJeong.java ================================================ package LeetCode.Array.Sort_Array_By_Parity_II; class HyeonJeong { public int[] sortArrayByParityII(int[] A) { // A의 길이가 2의 배수이고, 항상 반환이 가능하다는 조건 int odd = 0, even = 0, len = A.length; int []result = new int[len]; for (int i = 0; i < len; i++) { if (A[i]%2 == 0) { result[2*even] = A[i]; even++; } else { result[2*odd+1] = A[i]; odd++; } } return result; } } ================================================ FILE: LeetCode/Array/Sort_Colors/HyeonJeong.py ================================================ class Solution: def sortColors(self, nums: List[int]) -> None: for m in nums: for i in range(len(nums)-1): if nums[i] > nums[i+1]: nums[i], nums[i+1] = nums[i+1], nums[i] ================================================ FILE: LeetCode/Array/Spiral Matrix/6047198844.py ================================================ class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1]) ''' if matrix: ... else: return [] 와 같다. ''' ================================================ FILE: LeetCode/Array/Squares_of_a_Sorted_Array/HyeonJeong.java ================================================ package LeetCode.Array.Squares_of_a_Sorted_Array; import java.util.Arrays; class HyeonJeong { public int[] sortedSquares(int[] nums) { int []result = nums; for (int i = 0; i < nums.length; i++) { result[i] *= result[i]; } Arrays.sort(result); return result; } } ================================================ FILE: LeetCode/Array/Summary_Ranges/HyeonJeong.java ================================================ package LeetCode.Array.Summary_Ranges; import java.util.ArrayList; import java.util.List; class HyeonJeong { public List summaryRanges(int[] nums) { List list = new ArrayList<>(); if (nums.length == 0) return list; int i = 0, num = nums[0]; while (i < nums.length) { if (i+1 == nums.length || nums[i]+1 != nums[i+1]) { if (num == nums[i]) // 1개의 값이 범위가 되는 경우 list.add(Integer.toString(num)); else // 2개이상의 값이 범위가 되는 경우 list.add(num + "->" + nums[i]); if (i+1 < nums.length) num = nums[i+1]; } i++; } return list; } } ================================================ FILE: LeetCode/Array/The_K_Weakest_Rows_in_a_Matrix/6047198844.cpp ================================================ class Solution { public: static bool compare(pair &a, pair &b){ if(a.first != b.first) return a.first < b.first; return a.second < b.second; } vector kWeakestRows(vector>& mat, int k) { int n = mat[0].size(); vector< pair > tmp; for(int i = 0 ; i < mat.size(); i++){ int soldierN = n - (lower_bound(mat[i].rbegin(),mat[i].rend(),1) - mat[i].rbegin()); tmp.push_back({soldierN,i}); } sort(tmp.begin(),tmp.end(),compare); vector res; for(int i = 0; i < k ; i++) res.push_back(tmp[i].second); return res; } }; ================================================ FILE: LeetCode/Array/Third_Maximum_Number/HyeonJeong.java ================================================ package LeetCode.Array.Third_Maximum_Number; import java.util.Arrays; class HyeonJeong { public int thirdMax(int[] nums) { Arrays.sort(nums); int tmp = 1, n = nums[nums.length-1]; for (int i = nums.length-2; i >= 0; i--) { if (n > nums[i]) { tmp += 1; n = nums[i]; } if (tmp == 3) // 3번째로 큰 값 반환 return n; } return nums[nums.length-1]; // 값이 2개 이하로 사용된 배열이 주어진 경우는 가장 큰 값 반환 } } ================================================ FILE: LeetCode/Array/Three Consecutive Odds/6047198844.py ================================================ class Solution: def threeConsecutiveOdds(self, arr: List[int]) -> bool: cnt = 0 for x in arr: # odd if x % 2 == 1: cnt += 1 if cnt == 3: return True else: cnt = 0 return False ================================================ FILE: LeetCode/Array/TwoSum/6047198844.py ================================================ class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: sorted_nums = sorted(nums) left, right = 0, len(sorted_nums) - 1 while left < right: sum = sorted_nums[left] + sorted_nums[right] if sum == target: return [nums.index(sorted_nums[left]), nums.index(sorted_nums[right])] elif sum < target: left += 1 else: right -= 1 ================================================ FILE: LeetCode/Array/TwoSum/HyeonJeong.py ================================================ # 이중 for문 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for j, n in enumerate(nums): for i, m in enumerate(nums[j+1:]): if n+m == target: return [j, i+j+1] # while문 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: length = len(nums) j = 0 i = 1 while 1: if nums[j] + nums[i] == target: return [j, i] i += 1 if i == length: j += 1 i = j+1 # twoSum([2,7,11,15],9) == [0,1] # twoSum([3,2,4],6) == [1,2] # twoSum([3,3],6) == [0,1] ================================================ FILE: LeetCode/Array/TwoSum/JeongShin.js ================================================ /* Brute Force Method */ const twoSum = function (nums, target) { const len = nums.length; for (let i = 0; i < len; i++) { for (let j = i + 1; j < len; j++) { if (nums[i] + nums[j] === target && i !== j) return [i, j] } } }; /* 다른 사람 풀이 */ const twoSum2 = function (nums, target) { const cache = {}; for (let i = 0; i < nums.length; i++) { const curr = nums[i]; if (cache[curr] >= 0) { return [cache[curr], i] } cache[target - curr] = i } }; ================================================ FILE: LeetCode/Array/TwoSum/eyabc.js ================================================ // Brute Force const myTwoSum = function(nums, target) { const len = nums.length; for(let i = 0; i < len ; i++){ for (let j = i + 1; j < len; j++) { if ((nums[i] + nums[j]) === target) return [i, j]; } } }; // Two-pass Hash Table const twoSum2 = function(nums, target) { const hash = {}; const len = nums.length; for (let i = 0; i < len; i++) hash[nums[i]] = i; for (let i = 0; i < len; i++) { const complement = target - nums[i]; const hashValue = hash[complement]; if (hashValue && hashValue != i) return [i, hashValue]; } }; // One-pass Hash Table const twoSum = function(nums, target) { const hash = {}; const len = nums.length; for (let i = 0; i < len; i++) { const thisNum = nums[i]; const complement = target - thisNum; const hashValue = hash[complement]; if (hashValue !== undefined) return [hashValue, i]; hash[thisNum] = i; } }; console.log( twoSum([2,7,11,15], 9), // [0, 1] twoSum([3,2,4], 6), // [1, 2] twoSum([3,3], 6) // [1,0] ) ================================================ FILE: LeetCode/Array/Two_Sum_II_-_Input_array_is_sorted/6047198844(2).cpp ================================================ class Solution { public: vector twoSum(vector& numbers, int target) { int l = 0; int r = numbers.size()-1; int sum; while((sum=numbers[l]+numbers[r])!=target){ if(sum < target){ l++; }else{ r--; } } vector res; res.push_back(l+1); res.push_back(r+1); return res; } }; //투포인터 ================================================ FILE: LeetCode/Array/Two_Sum_II_-_Input_array_is_sorted/6047198844.cpp ================================================ class Solution { public: vector twoSum(vector& numbers, int target) { unordered_map umap; for(int i = 0; i < numbers.size(); i++){ int dif = target - numbers[i]; if(umap[numbers[i]]){ return vector({umap[numbers[i]],i+1}); } umap[dif] = i+1; } return vector(); } }; //해쉬 테이블 ================================================ FILE: LeetCode/Array/Unique Paths II/6047198844.py ================================================ class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: m = len(obstacleGrid) n = len(obstacleGrid[0]) dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] dp[0][1] = 1 for i in range(1, m + 1): for j in range(1, n + 1): if obstacleGrid[i - 1][j - 1] == 0: dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[m][n] ================================================ FILE: LeetCode/Array/Unique_Paths/HyeonJeong.py ================================================ class Solution: def uniquePaths(self, m: int, n: int) -> int: # m-1개의 '아래'와 n-1개의 '오른쪽'의 순서를 정하는 순열(nCr) num = 1 # num은 nCr에서 n! for i in range(2,m+n-1): num *= i r1 = 1 #r1은 nCr에서 r! r2 = 1 #r2는 nCr에서 (n-r)! for i in range(2, m): r1 *= i for i in range(2, n): r2 *= i return num//(r1*r2) ================================================ FILE: LeetCode/Array/Word Search/6047198844.py ================================================ def is_range_valid(y, x, ny, nx): return 0 <= y < ny and 0 <= x < nx def is_word_valid(board, y, x, word, check): if not word: return True if not self.is_range_valid(y, x, len(board), len(board[0])): return False if word[0] != board[y][x]: return False tmp = word[y][x] word[y][x] = '#' for dy, dx in ((-1, 0), (+1, 0), (0, -1), (0, +1)): if self.is_word_valid(board, y + dy, x + dx, word[1:]): return True word[y][x] = tmp return False def exist(board, word: str) -> bool: check = [[False for i in range(len(board[0]))] for j in range(len(board))] for y in range(len(board)): for x in range(len(board[0])): if is_word_valid(board, y, x, word, check): return True return False exist([["a"]],"a") ================================================ FILE: LeetCode/Array/zigzag_conversion/wongue_shin.dart ================================================ /* Runtime 380 ms Beats 94.83% -------------- Memory 160.4 MB Beats 43.10% */ // import 'package:flutter_test/flutter_test.dart'; class Solution { late final int _sliceLen; String convert(String s, int numRows) { // numRows 가 1인경우, 원본 스트링을 그대로 반환하면 된다. if (numRows == 1) return s; _sliceLen = numRows + (numRows - 2); List> ans = List.generate(numRows, (index) => []); for (int i = 0; i < s.length; i = i + _sliceLen) { int endIdx = i + _sliceLen < s.length ? i + _sliceLen : s.length; _reorderString(ans, s.substring(i, endIdx), numRows); } return ans.map((e) => e.join()).join(); } void _reorderString(List> ans, String slicedString, int numRows) { for (int idx = 0; idx < slicedString.length; idx++) { if (idx == 0 || idx == numRows - 1 || idx < numRows) { ans[idx].add(slicedString[idx]); continue; } ans[_sliceLen - idx].add(slicedString[idx]); } } } /* TEST_CODE -------- void main() { group( "Zigzag Conversion", () { late Solution solution; setUp(() { solution = Solution(); }); test('case01', () => expect(solution.convert("PAYPALISHIRING", 3), equals("PAHNAPLSIIGYIR"))); test('case02', () => expect(solution.convert("PAYPALISHIRING", 4), equals("PINALSIGYAHRPI"))); test('case03', () => expect(solution.convert("A", 1), equals("A"))); }, ); } */ ================================================ FILE: LeetCode/Backtracking/Combination Sum II/6047198844.cpp ================================================ class Solution { private: vector> res; public: void makeCombi(vector& candidates, vector& temp, int idx, int sum, int target){ if(sum > target){ return; } if(sum == target){ res.push_back(temp); } for(int i = idx; i < candidates.size()&& candidates[i] <= target; i++){ if(i==idx||candidates[i-1]!=candidates[i]){ temp.push_back(candidates[i]); makeCombi(candidates, temp, i+1, sum+candidates[i], target); temp.pop_back(); } } } vector> combinationSum2(vector& candidates, int target) { sort(candidates.begin(),candidates.end()); vector temp; makeCombi(candidates, temp, 0 , 0, target); return res; } }; ================================================ FILE: LeetCode/Backtracking/Combination Sum III/6047198844.cpp ================================================ class Solution { private: vector> res; public: void makeCombi(int k, int n,vector &temp, int idx, int sum){ if(sum > n||temp.size()>k){ return; } if(sum == n){ if(temp.size()==k) res.push_back(temp); return; } for(int i = idx; i <= 9; i++){ temp.push_back(i); makeCombi(k, n,temp, i+1, sum+i); temp.pop_back(); } return; } vector> combinationSum3(int k, int n) { vector temp; makeCombi(k,n,temp,1,0); return res; } }; ================================================ FILE: LeetCode/Backtracking/Combination Sum IV/6047198844.cpp ================================================ class Solution { private: int memo[1001]; public: int makeCombi(vector& nums, int remain){ if(remain < 0)// if negative numbers are allowed , it should be removed return 0; if(remain == 0) return 1; if(memo[remain]!=-1) return memo[remain]; int &res = memo[remain]; res = 0; for(int i = 0; i < nums.size(); i++){ res += makeCombi(nums, remain-nums[i]); } return res; } int combinationSum4(vector& nums, int target) { memset(memo,-1,sizeof(memo)); // if negative numbers are allowed , it should not be-1 but be changed return makeCombi(nums, target); } }; ================================================ FILE: LeetCode/Backtracking/Combination_Sum/6047198844.cpp ================================================ class Solution { private: vector> res; public: void makeCombiSum(vector& candidates,vector&combi, int idx, int sum,int target){ if(sum>target) return; if(sum==target){ res.push_back(combi); return; } for(int i=idx; i < candidates.size(); i++){ combi.push_back(candidates[i]); makeCombiSum(candidates,combi, i, sum+candidates[i],target); combi.pop_back(); } } vector> combinationSum(vector& candidates, int target) { vector combi; makeCombiSum(candidates, combi, 0, 0, target); return res; } }; ================================================ FILE: LeetCode/Backtracking/Combinations/6047198844.cpp ================================================ class Solution { //1~N 범위에서의 모든 조합 private: int max_n; vector> res; public: void makeCombi(int idx, vector &combinations, int remain){ if(remain==0){ res.push_back(combinations); return; } for(int i = idx+1; i <= max_n; i++){ combinations.push_back(i); makeCombi(i,combinations,remain-1); combinations.pop_back(); } return; } vector> combine(int n, int k) { max_n = n; vector combinations; makeCombi(0,combinations,k); return res; } }; ================================================ FILE: LeetCode/Backtracking/Letter_Combinations_of_a_Phone_Number/JeongShin.js ================================================ /** * 다음과 같이 숫자 별로 해당 문자가 정해져 있을때, (아래 chars 객체 참고) * digits 이 '23' 이면 2,3 으로 만들수 있는 모든 string 을 만드는 문제 * 따라서, ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] 을 반환 해야함. * @param {string} digits * @return {string[]} */ const letterCombinations = function (digits) { const letters = { '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z'] }; const target = digits.length; const answer = []; if (target === 0) return answer; const permutation = (str, idx) => { if (idx === target) return answer.push(str); letters[digits[idx]].forEach((ch) => { permutation(str + ch, idx + 1); }) }; permutation('', 0); return answer; }; ================================================ FILE: LeetCode/Backtracking/N-Queens/6047198844.cpp ================================================ class Solution { private: vector> res; vector chessBoard; bool col[9]; bool crossLeft[17]; bool crossRight[17]; public: void makeNQueens(int n, int y){ if(n==y){ res.push_back(chessBoard); return; } string s(n,'.'); for(int x = 0; x> solveNQueens(int n) { makeNQueens(n,0); return res; } }; ================================================ FILE: LeetCode/Backtracking/N-Queens_II/6047198844.cpp ================================================ class Solution { private: bool col[9]; bool CrossLeft[17]; bool CrossRight[17]; int max_n; public: int makeNQueens(int y){ if(y==max_n) return 1; int res = 0; for(int x = 0; x < max_n; x++){ if(!col[x]&&!CrossLeft[y+x]&&!CrossRight[max_n-1-y+x]){ col[x] = CrossLeft[y+x] = CrossRight[max_n-1-y+x] = true; res += makeNQueens(y+1); col[x] = CrossLeft[y+x] = CrossRight[max_n-1-y+x] = false; } } return res; } int totalNQueens(int n) { max_n = n; return makeNQueens(0); } }; ================================================ FILE: LeetCode/Backtracking/Next Permutation/6047198844.cpp ================================================ class Solution { public: void nextPermutation(vector& nums) { int cur = nums.size(); while(cur--){ if(cur==0){ sort(nums.begin(),nums.end()); return; } int &beforeValue = nums[cur-1]; int ¤tValue = nums[cur]; if(beforeValue < currentValue){ sort(nums.begin()+cur,nums.end()); int changedIdx = upper_bound(nums.begin()+cur,nums.end(),nums[cur-1]) - nums.begin(); swap(nums[cur-1],nums[changedIdx]); return; } } } }; ================================================ FILE: LeetCode/Backtracking/Palindrome_Partitioning/JeongShin.js ================================================ /** * @param {string} s * @return {string[][]} */ const partition = function (s) { const target = s.length; const answer = []; let possibleAnswer = []; backtracking(s, 0, s.length, possibleAnswer, answer); return answer; }; function checkPalindrome(string, startIdx, endIdx) { while (startIdx < endIdx) { if (string[startIdx++] !== string[endIdx--]) return false; } return true; } function backtracking(string, startIdx, target, possibleAnswer, answer) { if (startIdx === target){ return answer.push([...possibleAnswer]); } for (let endIdx = startIdx; endIdx < target; endIdx++) { if (checkPalindrome(string, startIdx, endIdx)) { possibleAnswer.push(string.substring(startIdx, endIdx + 1)); backtracking(string, endIdx + 1, target, possibleAnswer, answer); possibleAnswer.pop(); } } } partition("aab"); // ["aa", "b"], ["a","b", "c"] ================================================ FILE: LeetCode/Backtracking/Path_with_Maximum_Gold/kth496.kt ================================================ import kotlin.math.max class Solution { fun getMaximumGold(grid: Array): Int { val R = grid.size; val C = grid[0].size val dr: IntArray = intArrayOf(0, 0, 1, -1) val dc: IntArray = intArrayOf(1, -1, 0, 0) var answer = 0 val visited: Array = Array(R) { BooleanArray(C) { false } } fun dfs(r: Int, c: Int, acc: Int) { visited[r][c] = true val ret = acc + grid[r][c] var flag = false for (i in 0..3) { val nr = r + dr[i] val nc = c + dc[i] if (nr in 0 until R && nc in 0 until C && !visited[nr][nc] && grid[nr][nc] > 0) { flag = true dfs(nr, nc, ret) } } if (!flag) answer = max(answer, ret) visited[r][c] = false } for (r in 0 until R) { for (c in 0 until C) { if (grid[r][c] > 0) { dfs(r, c, 0) } } } return answer } } ================================================ FILE: LeetCode/Backtracking/Permutations/6047198844.cpp ================================================ class Solution { private: bool check[21]; vector> res; public: void makePermutation(vector &temp, vector& nums){ if(temp.size()==nums.size()){ res.push_back(temp); return; } for(int i = 0; i < nums.size(); i++){ if(!check[i]){ check[i] = true; temp.push_back(nums[i]); makePermutation(temp, nums); temp.pop_back(); check[i] = false; } } return; } vector> permute(vector& nums) { vector temp; fill_n(check,21,false); makePermutation(temp, nums); return res; } }; ================================================ FILE: LeetCode/Backtracking/Permutations II/6047198844.cpp ================================================ class Solution { private: vector> res; public: void makePermutation(vector &temp,vector &pickCheck, const vector& nums){ //다뽑은 경우의수 if(temp.size()==nums.size()){ res.push_back(temp); return; } //현재 뽑았던 수중에 중복되는 수는 뽑지 않는다. bool dupCheck[21]; fill_n(dupCheck,21,false); //이미 뽑았던 인덱스(pickCheck)는 뽑지 않는다. //나머지는 뽑아도된다. for(int i = 0; i < nums.size(); i++){ if(!dupCheck[nums[i]+10]&&!pickCheck[i]){ dupCheck[nums[i]+10] = true; pickCheck[i] = 1; temp.push_back(nums[i]); makePermutation(temp, pickCheck, nums); temp.pop_back(); pickCheck[i] = 0; } } } vector> permuteUnique(vector& nums) { vectortemp; vectorpickCheck(nums.size(),0); makePermutation(temp,pickCheck, nums); return res; } }; ================================================ FILE: LeetCode/Backtracking/Subsets/JeongShin.js ================================================ /** * @param {number[]} nums * @return {number[][]} */ const subsets = function (nums) { const answer = []; backtracking(nums, [], 0, nums.length, answer); console.log(answer) return answer; }; function backtracking(nums, subset, start, target, answer) { for (let i = start; i < target; i++) { subset.push(nums[i]); backtracking(nums, [...subset], i + 1, target, answer); subset.pop(); } answer.push([...subset]); } subsets([1, 2, 2]); ================================================ FILE: LeetCode/Backtracking/Subsets_II/JeongShin.js ================================================ ================================================ FILE: LeetCode/Backtracking/Word_Search/JeongShin.js ================================================ /** * Board 내부에 단어들로 word 를 만들 수 있는지 판단 * @param {character[][]} board * @param {string} word * @return {boolean} */ const exist = function (board, word) { const [row, col] = [board.length, board[0].length]; const visited = {}; const target = word.length; const checkOutOfBound = (i, j) => { return i >= row || i < 0 || j >= col || j < 0; }; const search = (i, j, idx) => { const key = `${i},${j}`; if (idx === target) return true; if (checkOutOfBound(i, j) || board[i][j] !== word[idx] || visited[key] === true) return false; visited[key] = true; if (search(i - 1, j, idx + 1) || search(i + 1, j, idx + 1) || search(i, j - 1, idx + 1) || search(i, j + 1, idx + 1)) return true; visited[key] = false; return false; }; for (let i = 0; i < row; i++) for (let j = 0; j < col; j++) if ((board[i][j] === word[0]) && search(i, j, 0)) return true; return false; }; ================================================ FILE: LeetCode/Backtracking/Word_Search_II/JeongShin.js ================================================ class Node { constructor(key) { this.key = key; this.children = new Map(); this.isEnd = null; } } class Trie { constructor(row, col) { this.root = new Node(null); this.row = row; this.col = col; } addWord(word, node = this.root) { const l = word.length; for (let i = 0; i < l; i++) { const curr = word[i]; if (!node.children.has(curr)) node.children.set(curr, new Node(curr)); node = node.children.get(curr); } node.isEnd = word; } checkOutOfBound = (i, j) => (i >= this.row || i < 0 || j >= this.col || j < 0); // dfs 알고리즘 find(board, i, j, answer, node = this.root) { if (this.checkOutOfBound(i, j)) return false; const char = board[i][j]; const child = node.children.get(char); // Visited 거나 Trie 에 자식이 없는 경우 리턴 if (char === '#' || !child) return; // 단어를 끝까지 찾은 경우 단어를 정답에 add if (child.isEnd) { answer.add(child.isEnd); child.isEnd = null; } // Visited 객체를 사용하는 대신 # 을 배치하여 중복 선택 방지 board[i][j] = '#'; this.find(board, i - 1, j, answer, child); this.find(board, i + 1, j, answer, child); this.find(board, i, j + 1, answer, child); this.find(board, i, j - 1, answer, child); // 탐색 후 다시 원래 단어 배치 board[i][j] = char; } } /** * board 에 있는 단어들을 상, 하, 좌, 우 탐색하여 * words 배열안에 있으면 해당 단어를 반환 하는 문제 * @param {string[][]} board * @param {string[]} words * @return {string[]} */ const findWords = function (board, words) { const answer = new Set(); const [row, col] = [board.length, board[0].length]; const trie = new Trie(row, col); const root = trie.root.children; for (const word of words) trie.addWord(word); for (let i = 0; i < row; i++) for (let j = 0; j < col; j++) if (root.has(board[i][j])) trie.find(board, i, j, answer); return Array.from(answer); }; findWords([ ['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v'] ], ["oath", "pea", "eat", "rain"]); findWords([["a", "b"], ["c", "d"]], ["ab", "cb", "ad", "bd", "ac", "ca", "da", "bc", "db", "adcb", "dabc", "abb", "acb"]); ================================================ FILE: LeetCode/Binary_Search/Find_the_Smallest_Divisor_Given_a_Threshold/6047198844.cpp ================================================ class Solution { public: int smallestDivisor(vector& nums, int threshold) { int start = 1; int end = 1e6; while(start < end){ int mid = (start + end) / 2; int sum = 0; for(int i = 0; i < nums.size(); i++){ // sum += nums[i] % mid ? nums[i]/mid + 1: nums[i]/mid; sum += (nums[i] + mid - 1)/ mid; } if(sum > threshold){ start = mid + 1; }else{ end = mid; } } return start; } }; ================================================ FILE: LeetCode/Binary_Search/First_Bad_Version/6047198844.py ================================================ # The isBadVersion API is already defined for you. # @param version, an integer # @return an integer # def isBadVersion(version): class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ ''' first Bad Version을 찾아라. 1, 2, 3, 4, 5, ... , n 이 있다고 해보자. 이분탐색 -> lower bound ''' begin = 0 end = n + 1 # true가 처음으로 들어갈 공간을 찾는다. while begin < end: mid = (begin + end) // 2 # mid가 현재 false이다. if not isBadVersion(mid): begin = mid + 1 else: end = mid return begin ================================================ FILE: LeetCode/Binary_Search/Guess_Number_Higher_or_Lower/6047198844.py ================================================ # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int) -> int: begin = 1 end = n while begin < end: num = (begin + end) // 2 if guess(num) == -1: end = num - 1 elif guess(num) == +1: begin = num + 1 else: return num return begin ================================================ FILE: LeetCode/Binary_Search/Koko_Eating_Bananas/6047198844.cpp ================================================ class Solution { public: int minEatingSpeed(vector& piles, int h) { int start = 1; int end = *max_element(piles.begin(),piles.end()); while(start < end){ int sum = 0; int mid = (start + end ) / 2; for(int pile : piles) sum += (pile + mid - 1) / mid; if(sum > h) start = mid + 1; else end = mid; } return start; } }; ================================================ FILE: LeetCode/Binary_Search/Minimum_Size_Subarray_Sum/JeongShin.js ================================================ /** * @param {number} s * @param {number[]} nums * @return {number} */ const minSubArrayLen = function (s, nums) { let sum = 0, start = 0; const answer = nums.reduce((minLen, num, end) => { sum += num; // 만약 sum 이 기준치를 넘게 되면 최소 길이를 구하기 위해 minLen 을 구합니다. // 앞에서 숫자를 하나씩 빼면서 최소 길이를 유지 합니다. while (sum >= s) { minLen = Math.min(minLen, end - start + 1); sum -= nums[start++]; } return minLen; }, Infinity); return answer === Infinity ? 0 : answer; }; console.log(minSubArrayLen(7, [2, 3, 1, 2, 4, 3])); ================================================ FILE: LeetCode/Binary_Search/Minimum_Size_Subarray_Sum/eyabc.js ================================================ /** * https://leetcode.com/problems/minimum-size-subarray-sum/ * @param s, 양의 정수 s * @param nums, 양의 정수 배열 * @return 연속되는 서브배열의 원소의 합이 s 이상인 배열의 최소 크기 * 합이 s 이상인 서브 배열이 없으면 0 을 리턴한다. */ // 내 솔루션 204 ms 40.2 MB // better brute force const getPrefixSum = (originArr) => { return originArr.reduce((prefixSum, num, key) => { prefixSum.push((num + prefixSum[key])); return prefixSum; }, [0]); }; const minSubArrayLen = function(s, nums) { const prefixSum = getPrefixSum(nums); let min = Infinity; const prefixSumLength = prefixSum.length; prefixSum.forEach((sum, key) => { for (let j = key + 1 ; j < prefixSumLength ; j++) { if ((prefixSum[j] - sum) >= s) { min = Math.min(min, j - key); break; } } }); return min === Infinity ? 0 : min; }; // Brute Force const minSubArrayLen2 = function(s, nums) { const n = nums.length; let ans = Infinity; for (let i = 0 ; i < n ; i++) { for (let j = i ; j < n ; j++) { let sum = 0; for (let k = i ; k <= j ; k++) { sum += nums[k]; } if (sum >= s) { ans = min(ans, (j - i + 1)); break; //Found the smallest subarray with sum>=s starting with index i, hence move to next index } } } return (ans != Infinity) ? ans : 0; }; // Using Binary search 88 ms 41.1 MB /* https://blockdmask.tistory.com/168 leetcode 의 C++ lower_bound 란? - 이진탐색(Binary Search)기반의 탐색 방법입니다. (배열 또는 리스트가 정렬 되어있어야 한다.) - @return 찾으려 하는 key 값이 "없으면" key 값보다 큰, 가장 작은 정수 값을 찾습니다. - 같은 원소가 여러개 있어도 상관 없으며, 항상 유일한 해를 구할 수 있습니다. - 구간이 [start, end]인 배열이 있을때, 중간위치의 index 를 mid 라고 하면, arr[mid-1] < key 이면서 arr[mid] >= key 인 최소의 m 값을 찾으면 됩니다. (m>=2) */ const lowerBound = (arr, key) => { let [start, end, mid] = [0, arr.length, arr.length]; while (end - start > 0) { // start 가 end 와 같지 않고, 넘지 않을 때 mid = ~~((start + end) / 2); //중앙 index (arr[mid] < key) ? (start = mid + 1) : (end = mid); } return end + 1; }; const minSubArrayLen3 = function(s, nums) { const n = nums.length; let ans = Infinity; if (n === 0) return 0; const prefixSum = getPrefixSum(nums); const end = prefixSum.length + 1; prefixSum.forEach((sum, key) => { if (key === 0 || key === n) return; const to_find = s + prefixSum[key - 1]; const bound = lowerBound(prefixSum, to_find); if (bound !== end) { ans = Math.min(ans, bound - (key)); } }); return (ans != Infinity) ? ans : 0; }; // Using 2 pointers 64 ms 39.4 MB const minSubArrayLen4 = function(s, nums) { let ans = Infinity; let left = 0; let sum = 0; nums.forEach((num, i) => { sum += nums[i]; while (sum >= s) { ans = Math.min(ans, i + 1 - left); sum -= nums[left++]; } }); return (ans != Infinity) ? ans : 0; }; console.log(minSubArrayLen4(7, [2, 3, 1, 2, 4, 3]) === 2); console.log(minSubArrayLen4(15, [1, 2, 3, 4, 5]) === 5); ================================================ FILE: LeetCode/Binary_Search/Path With Minimum Effort/6047198844.py ================================================ typedef pair> P; class Solution { private: int dy[4] = {0,1,0,-1}; int dx[4] = {-1,0,1,0}; const int INF = 987654321; public: bool isValid(int y, int x, int yn, int xn){ return (0<=y&&y>& heights) { priority_queue, greater

> pq; int yn = heights.size(); int xn = heights[0].size(); vector> mef(yn,vector(xn,INF)); mef[0][0] = 0; pq.push({mef[0][0],{0,0}}); while(!pq.empty()){ P tmp = pq.top(); pq.pop(); int y = tmp.second.first; int x = tmp.second.second; int effort = tmp.first; if(mef[y][x] < effort) continue; for(int i = 0; i < 4; i++){ int ny = y + dy[i]; int nx = x + dx[i]; if(isValid(ny,nx,yn,xn)){ int dif = abs(heights[ny][nx] - heights[y][x]); int r = max(effort,dif); if(mef[ny][nx] > r){ mef[ny][nx] = r; pq.push({mef[ny][nx],{ny,nx}}); } } } } return mef[yn-1][xn-1]; } }; ================================================ FILE: LeetCode/Binary_Search/Search-in-Rotated-Sorted-Array/JeongShin.js ================================================ /** * @param {number[]} nums * @param {number} target * @return {number} */ // var search = function(nums, target) { // return nums.indexOf(target); // }; const search = function(nums, target) { let start = 0; let end = nums.length - 1; while (start <= end){ const mid = ~~((start + end) / 2); if (nums[mid] === target) return mid; if (nums[start] <= nums[mid]){ if (target < nums[mid] && target >= nums[start]) end = mid - 1; else start = mid + 1; } if (nums[mid] <= nums[end]){ if (target > nums[mid] && target <= nums[end]) start = mid + 1; else end = mid - 1; } } return -1; } ================================================ FILE: LeetCode/Breadth-first_Search/01_Matrix/JeongShin.js ================================================ /** * @param {number[][]} matrix * @return {number[][]} */ const updateMatrix = function (matrix) { const [row, col] = [matrix.length, matrix[0].length]; const answer = []; for (let i = 0; i < row; i++) { answer[i] = answer[i] || []; for (let j = 0; j < col; j++) { if (matrix[i][j] === 0) { answer[i][j] = 0; continue; } answer[i][j] = bfs([i, j], matrix); } } return answer; }; const key = ([x, y]) => `${x},${y}`; const bfs = function (coordinates, matrix) { const stack = [[coordinates[0], coordinates[1], 0]]; const visited = new Map(); visited.set(key(coordinates), true); while (stack[0]) { let [i, j, distance] = stack.shift(); if (matrix[i][j] === 0) return distance; [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]] .forEach(([x, y]) => { const k = key([x, y]); if (matrix[x] !== undefined && matrix[x][y] !== undefined && !visited.get(k)) { visited.set(k, true); stack.push([x, y, distance + 1]); } }) } }; ================================================ FILE: LeetCode/Breadth-first_Search/Shortest_Path_in_Binary_Matrix/6047198844.cpp ================================================ class Solution { private: int d[3] = {-1,0,+1}; public: bool isValid(int y, int x, int n){ return (0<=y&&y>& grid) { if(grid[0][0]) return -1; int n = grid.size(); int res = 1; if(n==1) return res; queue > q; q.push({0,0}); while(!q.empty()){ int m = q.size(); for(int i = 0; i < m ; i++){ pair cord = q.front(); q.pop(); if(cord.first == n-1 && cord.second == n-1) return res; for(int j = 0; j < 9; j++){ int ny = cord.first + d[j/3]; int nx = cord.second + d[j%3]; if(isValid(ny,nx,n)&&!grid[ny][nx]){ grid[ny][nx] = 1; q.push({ny,nx}); } } } res++; } return -1; } }; ================================================ FILE: LeetCode/Breadth-first_Search/Word_Ladder/6047198844.cpp ================================================ class Solution { public int ladderLength(String beginWord, String endWord, List wordList) { int res = 0; Queue queue = new LinkedList(); HashSet check = new HashSet(); queue.add(beginWord); check.add(beginWord); while(!queue.isEmpty()){ res++; int Qsize = queue.size(); while(Qsize!=0){ Qsize--; String curWord = queue.poll(); if(endWord.equals(curWord)) return res; for(String w : wordList){ if(!check.contains(w)){ int cnt = 0; for(int i = 0; i < w.length() && cnt <= 1; i++){ if(w.charAt(i) != curWord.charAt(i)) cnt++; } if(cnt == 1){ queue.add(w); check.add(w); } } } } } return 0; } } ================================================ FILE: LeetCode/Breadth-first_Search/Word_Ladder/JeongShin.js ================================================ /** * @param {string} beginWord * @param {string} endWord * @param {string[]} wordList * @return {number} */ // 나의 처음 풀이 👉 시간 초과 const ladderLength = function (beginWord, endWord, wordList) { const graph = {}; const len = beginWord.length; wordList.push(beginWord); for (const currWord of wordList) { graph[currWord] = graph[currWord] || []; for (const nextWord of wordList) { let difference = 0; for (let i = 0; i < len; i++) difference += (currWord[i] !== nextWord[i]); if (difference === 1) graph[currWord].push(nextWord) } } return bfs(graph, beginWord, endWord) }; const bfs = function (graph, beginWord, endWord) { const visited = new Map(); visited.set(beginWord, true); const stack = [{word: beginWord, count: 1, visited: visited}]; let answer = Infinity; while (stack[0]) { const {word, count, visited} = stack.pop(); if (word === endWord) { answer = Math.min(answer, count); continue; } if (!graph[word]) continue; graph[word].forEach((nextWord) => { if (!visited.has(nextWord)) { const visitedCopy = new Map(visited); visitedCopy.set(nextWord, true); stack.push({word: nextWord, count: count + 1, visited: visitedCopy}); } }) } return answer === Infinity ? 0 : answer; }; // 그래프를 사용하지 않는 풀이 const ladderLength2 = function (beginWord, endWord, wordList) { return wordList.includes(endWord) ? bfs(beginWord, endWord, wordList) : 0; }; function bfs(beginWord, endWord, wordList) { const listLen = wordList.length; const wordLen = beginWord.length; const visited = new Array(listLen).fill(false); let queue = []; queue.push({word: beginWord, count: 1}); while (queue[0]) { const {word, count} = queue.pop(); if (word === endWord) return count; for (let i = 0; i < listLen; i++) { if (visited[i]) continue; let difference = 0; for (let j = 0; j < wordLen; j++) difference += (wordList[i][j] !== word[j]); if (difference === 1) { queue.unshift({word: wordList[i], count: count + 1}); visited[i] = true; } } } return 0; } ================================================ FILE: LeetCode/Breadth-first_Search/Word_Ladder_II/JeongShin.js ================================================ ================================================ FILE: LeetCode/DP/Best_Time_to_Buy_and_Sell_Stock/sangmandu.py ================================================ ''' https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 기본적인 dp 문제인데 아직 분할 개념은 없는 듯 ''' class Solution: def maxProfit(self, prices: List[int]) -> int: m = ret = 0 for p in prices[::-1]: m = max(m, p) ret = max(m-p, ret) return ret ''' ''' ================================================ FILE: LeetCode/DP/Climbing Stairs/6047198844.py ================================================ class Solution: def climbStairs(self, n: int) -> int: memo = [-1 for _ in range(n+1)] def dp(n): if n <= 2: return n if memo[n] != -1: return memo[n] memo[n] = dp(n-1) + dp(n-2) return memo[n] return dp(n) ================================================ FILE: LeetCode/DP/Climbing Stairs/sangmandu.py ================================================ ''' https://leetcode.com/problems/climbing-stairs/ DP : 피보나치 이용 ''' class Solution: def climbStairs(self, n: int) -> int: a, b = 1, 2 for i in range(1, n): a, b = b, a+b return a ''' ''' ================================================ FILE: LeetCode/DP/Coin_Change/JeongShin.js ================================================ /** * @param {number[]} coins * @param {number} amount * @return {number} */ const coinChange = function (coins, amount) { const len = coins.length; const dp = new Array(amount + 1).fill(Infinity); dp[0] = 0; coins.sort((a, b) => a - b); for (let i = 0; i < len; i++) { const coin = coins[i]; for (let j = 1; j <= amount; j++) { const prev = (dp[j - coin] + 1) || Infinity; dp[j] = Math.min(prev, dp[j]); } } return dp[amount] === Infinity ? -1 : dp[amount]; }; coinChange([1, 2, 5], 11); ================================================ FILE: LeetCode/DP/Count_Sorted_Vowel_Strings/sangmandu.py ================================================ ''' https://leetcode.com/problems/count-sorted-vowel-strings/ Count Sorted Vowel Strings DP 문제인데 DP로 풀지못한.. ''' class Solution(object): def countVowelStrings(self, n): vowel = [1, 1, 1, 1, 1] while n != 1: n -= 1 temp = vowel[:] for idx in range(5): for idx2 in range(idx+1, 5): vowel[idx2] += temp[idx] return sum(vowel) ''' 2차원 행렬 선언해서 DP쪽으로 풀고싶었는데, 잘 생각이 안났다. 세부적인 원리는 비슷한 것 같다. 왜냐하면 a가 eiou로, e가 iou로, ... 하나씩 추가해주는 메커니즘이 DP 방식이랑 동일하기 때문 아래 코드는 DP로 구현한 코드. class Solution: def countVowelStrings(self, n: int) -> int: dp = [[ 0 for col in range(6)] for row in range(n + 1)] for str_len in range(1, n + 1): for vowel_len in range(1, 6): if str_len == 1: dp[str_len][vowel_len] = dp[str_len][vowel_len - 1] + 1 else: dp[str_len][vowel_len] = dp[str_len - 1][vowel_len] + dp[str_len][vowel_len - 1] return dp[n][5] ''' ================================================ FILE: LeetCode/DP/Counting_Bits/sangmandu.py ================================================ ''' https://leetcode.com/problems/counting-bits/ Counting Bits 이진수 표현. format을 알면 쉽게 풀 수 있다 ''' class Solution(object): def countBits(self, n): return [format(i, 'b').count('1') for i in range(n + 1)] ''' 완벽하게 푼듯 하다 ''' ================================================ FILE: LeetCode/DP/Divisor_Game/sangmandu.py ================================================ ''' https://leetcode.com/problems/divisor-game/ 기본적인 dp 문제(인줄 알았다) ''' class Solution: def divisorGame(self, N: int) -> bool: dp = [False] * (N+1) for num in range(2, N+1): divisor = [1] for i in range(2, int(num**0.5)+1): if num % i == 0: divisor.append(i) divisor.append(num // i) dp[num] = True if False in [dp[num-d] for d in divisor] else False return dp[N] ''' 아니 겁나 열심히 풀었는데 짝홀수 구별 문제라니 아마 숨겨진 전제조건이 있다면 alice와 bob은 이기기 위한 최선의 결정을 한다는 점. ''' ================================================ FILE: LeetCode/DP/Edit_Distance/JeongShin.js ================================================ const minDistance = function (word1, word2) { let dp = new Array(word1.length + 1).fill(null).map(() => (new Array(word2.length + 1).fill(0))); const [len2, len1] = [dp.length, dp[0].length]; for (let i = 0; i < len2; i++) dp[i][0] = i; for (let i = 0; i < len1; i++) dp[0][i] = i; for (let i = 1; i < len2; i++) for (let j = 1; j < len1; j++) dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (word1[i - 1] !== word2[j - 1])); return dp[len2 - 1][len1 - 1]; }; ================================================ FILE: LeetCode/DP/House_Robber_III/6047198844.py ================================================ #Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right import urllib.request from functools import lru_cache @lru_cache(None) def max_binary(root: TreeNode, check: bool) -> int: # 이전에 안뽑았으면 True, 뽑았으면 False if not root: return 0 pick = 0 not_pick = 0 not_pick = max_binary(root.left, True) + max_binary(root.right, True) if check: pick = root.val + max_binary(root.left, False) + max_binary(root.right, False) return max(pick, not_pick) class Solution: def rob(self, root: TreeNode) -> int: return max_binary(root, True) ================================================ FILE: LeetCode/DP/Is Subsequence/sangmandu.py ================================================ ''' https://leetcode.com/problems/is-subsequence 인덱스 순서 비교 ''' class Solution: def isSubsequence(self, s: str, t: str) -> bool: i = 0 for word in t: if i == len(s): return True if s[i] == word: i += 1 return i == len(s) ''' ''' ================================================ FILE: LeetCode/DP/Longest_Increasing_Subsequence/6047198844.py ================================================ class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) sub = [1] * n for cur in range(1,n): for past in range(cur): if nums[past] < nums[cur] and sub[past] + 1 > sub[cur]: sub[cur] = sub[past] + 1 return max(sub) ================================================ FILE: LeetCode/DP/Maximum Subarray/sangmandu.py ================================================ ''' https://leetcode.com/problems/maximum-subarray/ DP : max값을 기록하면서, cur값을 갱신해가기 ''' class Solution: def maxSubArray(self, nums: List[int]) -> int: maxSum = curSum = nums[0] for num in nums[1:]: curSum=max(num, curSum+num) maxSum=max(curSum, maxSum) return maxSum ''' ''' ================================================ FILE: LeetCode/DP/Min Cost Climbing Stairs/sangmandu.py ================================================ ''' https://leetcode.com/problems/min-cost-climbing-stairs/ 역으로 생각해서, 내가 이 계단과 저 계단 중 무얼 밞을 까 하는 단계 ''' class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: a = b = 0 for x in cost[::-1]: a, b = x + min(a, b), a return min(a, b) ''' ''' ================================================ FILE: LeetCode/DP/MinimumPathSum/JeongShin.js ================================================ const minPathSum = function (grid) { const col = grid.length, row = grid[0].length; const dp = grid.map((v, i) => i === 0 ? v : v.map((v, i) => i === 0 ? v : 0)); let [i, j] = [0, 0]; for (i = 0; i < col; i++) { for (j = 0; j < row; j++) { if (i === 0 && j === 0) continue; let up; if ( (up = (dp[i - 1] || [])[j]) === undefined) up = Infinity; let left; if ((left = dp[i][j - 1]) === undefined) left = Infinity; dp [i][j] = Math.min(left, up) + grid[i][j]; } } return dp[col - 1][row - 1]; }; minPathSum([[0,0],[0,0]]); /* 다른 사람 코드를 참고한 풀이 */ const minPathSum2 = function (grid) { const col = grid.length; const row = grid[0].length; for (let i = 1; i < col; i++) { grid[i][0] += grid[i - 1][0]; } for (let j = 1; j < row; j++) { grid[0][j] += grid[0][j - 1]; } for (let i = 1; i < col; i++) { for (let j = 1; j int: return sum(self.nums[i:j+1]) # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # param_1 = obj.sumRange(i,j) ''' 너무 대충 푸나.. ''' ================================================ FILE: LeetCode/DP/Stone_Game II/6047198844.cpp ================================================ class Solution { private: int memo[100][100]; public: int dp(vector& presum, int p , int m){ if(presum.size() - p <= 2 * m) // presum.size() - p : 남은 숫자의 수 / 2 * m 최대 뽑을수있는 숫자의 수 return presum[p]; int &res = memo[p][m]; if(res) return res; for(int x = 1; x <= 2*m; x++){ int s = presum[p] - presum[p+x]; res = max(res, s + (presum[p+x] - dp(presum, p+x, max(m,x)))); } return res; } int stoneGameII(vector& piles) { vector presum = piles; for(int i = piles.size()-2; i >= 0; i--) presum[i] += presum[i+1]; memset(memo,0,sizeof(memo)); return dp(presum,0,1); } }; //presum을 이용한다. //memo를 제대로 이용한다. ================================================ FILE: LeetCode/DP/Stone_Game II/6047198844.py ================================================ class Solution: def stoneGameII(self, piles: List[int]) -> int: N = len(piles) for i in range(N - 2, -1, -1): piles[i] += piles[i + 1] # piles는 현재 presum으로 변경되었다. from functools import lru_cache # memoization에 사용. @lru_cache(None) # 크기 제한이 없음. def dp(p, m): if p + 2 * m >= N: return piles[p] # p는 현재 인덱스이고. 2*m 만큼 더할수있다. return piles[p] - min(dp(p + x, max(m,x)) for x in range(1, 2 * m +1)) return dp(0,1) ================================================ FILE: LeetCode/DP/Unique_Paths/6047198844.py ================================================ class Solution: def uniquePaths(self, m: int, n: int) -> int: memo = [[-1 for x in range(n)] for y in range(m)] memo[m-1][n-1] = 1 #y,x에서의 경우의수 def dfs(y,x): #예외처리 if not (0 <= y < m and 0 <= x < n): return 0 #메모이제이션 if memo[y][x] != -1: return memo[y][x] memo[y][x] = dfs(y+1,x) + dfs(y,x+1) return memo[y][x] return dfs(0,0) ================================================ FILE: LeetCode/DP/Unique_Paths/JeongShin.js ================================================ const uniquePaths = function (m, n) { let dp = Array(m).fill(1); for (let i = 1; i < n; i++) { for (let j = 1; j < m; j++) { dp[j] += dp[j - 1]; } } return dp[m - 1]; }; uniquePaths(7, 3); ================================================ FILE: LeetCode/DP/Unique_Paths/ReadMe.md ================================================ 출처 : https://leetcode.com/problems/unique-paths/ ================================================ FILE: LeetCode/DP/Word_Break/JeongShin.js ================================================ class Node { constructor(key) { this.children = new Map(); this.key = key; this.isEnd = false; } } class Trie { constructor() { this.root = new Node(null); } addWord(word, node = this.root) { for (const char of word) { if (!node.children.has(char)) node.children.set(char, new Node(char)); node = node.children.get(char); } node.isEnd = true; } /** * @param {string} word * @param {number} startIdx word 의 substring 중 탐색을 시작할 인덱스 * @param {number} endIdx word 의 substring 중 탐색이 끝나는 인덱스 * @param {Object} node * @return {boolean} */ findWord(word, startIdx, endIdx, node = this.root) { for (let i = startIdx; i < endIdx; i++) { const char = word[i]; node = node.children.get(char); if (!node) return false; } return node.isEnd; } } /** * @param {string} s * @param {string[]} wordDict * @return {boolean} */ const wordBreak = function (s, wordDict) { const len = s.length; const trie = new Trie(); const memo = {0: true}; for (const word of wordDict) { trie.addWord(word); } for (let endIdx = 1; endIdx <= len; endIdx++) { for (let startIdx = 0; startIdx < endIdx; startIdx++) { if (memo[startIdx] && trie.findWord(s, startIdx, endIdx)) { if (endIdx === len) return true; memo[endIdx] = true; break; } } } return false; }; ================================================ FILE: LeetCode/DP/Word_Break_II/6047198844.cpp ================================================ class Solution { private: vector words[21]; int check[21]; vector res; public: void makeSentence(int idx, string s, int maxIdx, vector& wordDict){ if(idx > maxIdx){ return; } if(idx == maxIdx){ res.push_back(s); return; } for(int i : words[idx]){ //res.push_back(wordDict[i]); string temp = s; if(temp==""){ temp = wordDict[i]; }else{ temp = temp + " " + wordDict[i]; } makeSentence(idx+wordDict[i].size(),temp,maxIdx, wordDict); } return; } bool isEqual(string &s, string word){ return s==word; } bool isPossible(int idx, string& s, vector& wordDict){ if(s.size() < idx) return false; if(check[idx]==1) return true; if(check[idx]==-1) return false; for(int i = 0; i < wordDict.size(); i++){ if(isEqual(wordDict[i],s.substr(idx,wordDict[i].size()))&& isPossible(idx+wordDict[i].size(), s, wordDict)){ words[idx].push_back(i); } } check[idx] = words[idx].size() ? 1 : -1; return words[idx].size(); } vector wordBreak(string s, vector& wordDict) { fill_n(check,21,0); check[s.size()] = 1; isPossible(0,s,wordDict); makeSentence(0, "", s.size(), wordDict); return res; } }; ================================================ FILE: LeetCode/Database/Duplicate_Emails/6047198844 ================================================ # Write your MySQL query statement below select Email from Person group by Email having count(*) > 1 ================================================ FILE: LeetCode/Depth-first_Search/Convert_BST_to_Greater_Tree/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: int acc = 0; public: void Traversal(TreeNode* root) { if(root == NULL) return; Traversal(root->right); root->val += acc; acc = root->val; Traversal(root->left); } TreeNode* convertBST(TreeNode* root) { Traversal(root); return root; } }; ================================================ FILE: LeetCode/Depth-first_Search/Course_Schedule/6047198844.py ================================================ class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = collections.defaultdict(list) for pre_course, course in prerequisites: graph[pre_course].append(course) traced = set() visited = set() def dfs(precourse): if precourse in traced: return False if precourse in visited: return True traced.add(precourse) for course in graph[precourse]: if not dfs(course): return False #for문을 나와서 제거해야한다. 모든 재귀 호출은 traced에 해당 precourse가 존재해야한다. traced.remove(precourse) visited.add(precourse) return True for i in list(graph): if not dfs(i): return False return True ================================================ FILE: LeetCode/Depth-first_Search/Course_Schedule/JeongShin.js ================================================ /** * @param {number} numCourses * @param {number[][]} prerequisites * @return {boolean} */ const canFinish = function (numCourses, prerequisites) { const graph = new Map(); const visited = new Map(); for (const [course, prerequisite] of prerequisites) { const courseArr = graph.get(course) || graph.set(course, []).get(course); courseArr.push(prerequisite); } for (const course of graph.keys()) { if ((numCourses = dfs(graph, course, numCourses, visited)) === false) return false; } return true; }; const dfs = function (graph, course, num, visited) { if (visited.get(course) || num < 0) return false; visited.set(course, true); for (const pre of graph.get(course)) { if (!graph.has(pre)) continue; if (!dfs(graph, pre, num, visited)) return false; } visited.set(course, false); return num; }; ================================================ FILE: LeetCode/Depth-first_Search/Course_Schedule/eyabc.js ================================================ /** * https://leetcode.com/problems/course-schedule/ * @param numCourses : courses you have to take / 들을 수 있는 course 의 수 * 코스의 라벨은 0 부터 numCourses - 1 까지임. * @param prerequisites 선수 과목을 담고 있는 배열 * [0,1] : 0 이 1의 선수 과목임 * @return 모든 코스를 수강을 할 수 있으면 true 리턴 * * Topological Sort 위상 정렬을 이용해 풀 수 있다. * https://blog.naver.com/ndb796/221236874984 * 순서가 정해져 있는 작업을 차례로 수행해야 할 때 그 순서를 결정해 주기 위해 사용하는 알고리즘 * 사이클이 발생하지 않는 방향 그래프에서만 가능하다. 사이클이 있으면 시작점을 찾을 수 없기 때문. * * 후기: topology 알고리즘 이라는 힌트를 얻어서 아이디어는 쉽게 얻을 수 있었으나 대부분의 테스트 케이스에서 오답이 나왔다. * 테스트 케이스를 보고 알고리즘을 수정하였습니다. */ // 정점별 진입차수 count const inDegree = (prerequisites) => ( prerequisites.reduce((hash, prerequisite) => { prerequisite.forEach((vertex, j) => { // 초기화 if (!hash[vertex]) { const vertexObj = hash[vertex] = {}; vertexObj.after = []; vertexObj.before = 0; } const vertexObj = hash[vertex]; const [before, after] = [prerequisite[j - 1], prerequisite[j + 1]]; after !== undefined && vertexObj.after.push(after); before !== undefined && (vertexObj.before += 1); }); return hash; }, {}) ); const canFinish = function(numCourses, prerequisites) { if (prerequisites.length === 0) return true; /* { '0': { after: [], before: 2 }, '1': { after: [ 0 ], before: 0 }, '2': { after: [ 0 ], before: 0 } } */ const hash = inDegree(prerequisites); // 정점의 방문을 check 한다. const check = new Array(numCourses).fill(false); let queue = []; // 진입차수가 0 인 것(before 가 없는것) 을 큐에 넣고 방문처리 한다.. // { queue: [ '1', '2' ], check: [ false, true, true ] } Object.entries(hash).forEach(([key, { before }]) => { if (before !== 0) return; queue.push(key); check[key] = true; }); // 큐가 빌때까지 반복 while (queue.length > 0) { // 큐에서 꺼낸다음. const shifted = queue.shift(); hash[shifted].after.forEach((vertex) => { // 연결되어 있던 간선을 다 제거해 준다. hash[vertex].before -= 1; // 진입차수가 0 인 것을 큐에 넣고 반복처리 if (hash[vertex].before !== 0) return; queue.push(vertex); check[vertex] = true; }); } // 모든 정점을 방문하기 전에 큐가 빈다면 사이클이 존재하는 것임. // 만약 선수 과목의 대상이 아닌 정점들은 false 로 표시될 것임. 하지만 선수 과목이 아니기 때문에 false 여도 상관없는 문제의 케이스도 고려함. // check [ true, true, true ] 모든 정점을 방문함 return !check.some((c, k) => !c && hash[k]); }; console.log( canFinish(1, []) === true, canFinish(2, [[1, 0]]) === true, canFinish(2, [[1, 0], [0, 1]]) === false, canFinish(3, [[0, 2], [1, 2], [2, 0]]) === false, canFinish(7, [[1, 0], [0, 3], [0, 2], [3, 2], [2, 5], [4, 5], [5, 6], [2, 4]]) === true, canFinish(3, [[1, 0], [2, 0], [0, 2]]) === false, canFinish(3, [[1, 0]]) === true, canFinish(3, [[1, 0], [2, 0]]) === true, canFinish(4, [[3, 0], [0, 1]]), ); ================================================ FILE: LeetCode/Depth-first_Search/Course_Schedule_II/JeongShin.js ================================================ /** * @param {number} numCourses * @param {number[][]} prerequisites * @return {number[]} */ const findOrder = function (numCourses, prerequisites) { const graph = new Map(); const visited = new Map(); const answer = []; for (const [course, prerequisite] of prerequisites) { const courseArr = graph.get(course) || graph.set(course, []).get(course); courseArr.push(prerequisite); } for (let i = 0; i < numCourses; i++) { if (dfs(graph, i, numCourses, visited, answer) === false) return []; } return answer; }; const dfs = function (graph, course, num, visited, answer) { // 싸이클이 발생한 경우 if (visited.get(course) === -1) return false; // 이미 들은 과목인 경우 스킵 if (visited.get(course) === 1) return true; // 현재 과목 수강 visited.set(course, -1); if (graph.has(course)) { for (const pre of graph.get(course)) { if (dfs(graph, pre, num - 1, visited, answer) === false) return false; } } visited.set(course, 1); answer.push(course); return true; }; // Kahn's algorithm const findOrder2 = function (numCourses, prerequisites) { const graph = new Array(numCourses).fill(null).map((v)=> []); const edges = new Array(numCourses).fill(0); const sorted = []; for (const [course, prerequisite] of prerequisites) { graph[prerequisite].push(course); edges[course]++; } const queue = []; // 선수 과목이 없는 과목을 시작으로 for (let i = 0; i < numCourses; i++) edges[i] === 0 ? queue.push(i) : null; while (queue[0] !== undefined){ const curr = queue.shift(); sorted.push(curr); for (const next of graph[curr]){ edges[next]--; edges[next] === 0 ? queue.push(next) : null; } } return sorted.length === numCourses ? sorted : []; }; ================================================ FILE: LeetCode/Depth-first_Search/Course_Schedule_II/eyabc.js ================================================ /** * https://leetcode.com/problems/course-schedule-ii/ * * @param {number} numCourses 코스의 개수 (인덱스 0 ~ (n-1)) * @param {number[a][b]} prerequisites a 가 선수과목 b 가 후수과목 * * @return {number[]} 모든 과정을 마치기 위해 수강해야 하는 과정의 순서. * 모든 과정을 마칠 수 없는 경우 빈 배열을 반환한다. (사이클이 있을경우 / 과정들의 순서가 없을 경우) */ // 정점의 before 의 수와 다음 정점 after 를 가지고 있는 배열을 반환한다. const getVertex = (hash, vertex) => { return hash[vertex] ? hash[vertex] : hash[vertex] = { before: 0, after: [], }; }; const getDegree = (prerequisites) => ( prerequisites.reduce((hash, [preVertex, postVertex]) => { const pre = getVertex(hash, preVertex); const post = getVertex(hash, postVertex); pre.after.push(postVertex); post.before += 1; return hash; }, {}) ); // numCourses 이 3 일 경우 [2, 1, 0] 혹은 [0, 1, 2] 순서로 수강하게 된다. const noPrerequisites = (numCourses) => { const answer = []; for (let i = 0 ; i < numCourses ; i++) answer.push(i); return answer; }; const pushQueue = (queue, check, answer, key) => { queue.push(key); check[key] = true; answer.push(key); }; const initQueue = (hash, check, answer) => ( Object.entries(hash) .reduce((queue, [key, { before }]) => { if (before === 0) pushQueue(queue, check, answer, Number(key)); return queue; }, []) ); // 80 ms 43.4 MB const findOrder = function(numCourses, prerequisites) { // prerequisites 이 [] 비었을 때 수강하는 순서 if (prerequisites.length === 0) return noPrerequisites(numCourses); // 1. 정점 별 진입차수를 담고 있는 hash const hash = getDegree(prerequisites); // 2. 정점의 방문을 check 하는 배열 const check = new Array(numCourses).fill(false); const answer = []; // before 가 0 인것. 첫 시작 정점이 될 수 있는 키들 queue 에 넣는다. const queue = initQueue(hash, check, answer); // before 가 0 인 것이 없는 배열, queue: [] 은 사이클이 존재하는 것이다. if (queue.length === 0) return []; // 큐가 빌때까지 반복 while (queue.length > 0) { const shifted = queue.shift(); hash[shifted].after.forEach((vertex) => { // 연결되어 있던 간선을 다 제거해 준다. hash[vertex].before -= 1; if (hash[vertex].before !== 0) return; pushQueue(queue, check, answer, vertex); }); } const test = !check.some((c, k) => { // hash[k] === undefined 은 선후수 과목에 포함되지 않는 과목을 의미한다. if (hash[k] === undefined) answer.push(k); // 선후수 과목에도 포함되어 있지만(hash[k]) 방문하지 않은 과목은(c: false) 가 남아 있으면 과목전체를 수강하지 않았다는 의미 return !c && hash[k]; }); return !test ? [] : answer.reverse(); }; console.log(findOrder(2, [[1, 0]])); //[0,1] console.log(findOrder(4, [[1, 0], [2, 0], [3, 1], [3, 2]])); // [0,2,1,3] console.log(findOrder(1, [])); // [0] console.log(findOrder(2, [])); // [1, 0] console.log(findOrder(2, [[0, 1], [1, 0]])); console.log(findOrder(3, [[1, 0]])); // [2,0,1] console.log(findOrder(3, [[1, 0], [2, 0]])); // [0,2,1] ================================================ FILE: LeetCode/Depth-first_Search/Flatten Binary Tree to Linked List/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: TreeNode* prev = NULL; public: void flatten(TreeNode* root) { if(root==NULL) return; flatten(root->left); flatten(root->right); TreeNode* left = root->left; TreeNode* right = root->right; root->left = NULL; root->right = left; TreeNode* cur = root; while(cur->right) cur = cur->right; cur->right = right; } }; ================================================ FILE: LeetCode/Depth-first_Search/Letter Combinations of a Phone Number/6047198844.cpp ================================================ class Solution { private: string num[8] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; vectorres; public: void dfs(string temp, string digits){ if(digits=="") return res.push_back(temp); int numIdx = digits[0]-'0'; for(char c : num[numIdx-2]) dfs(temp+c,digits.substr(1)); } vector letterCombinations(string digits) { if(digits.size()) dfs("", digits); return res; } }; ================================================ FILE: LeetCode/Depth-first_Search/Maximum_Depth_of_Binary_Tree/6047198844.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int depth = 0; public int getMaxDepth(TreeNode root,int depth){ if(root==null){ return Math.max(this.depth,depth); } depth++; int res = depth; res = Math.max(getMaxDepth(root.left,depth),res); res = Math.max(getMaxDepth(root.right,depth),res); return res; } public int maxDepth(TreeNode root) { return getMaxDepth(root,0); } } ================================================ FILE: LeetCode/Depth-first_Search/Maximum_Depth_of_N-ary_Tree/6047198844.java ================================================ /* // Definition for a Node. class Node { public int val; public List children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List _children) { val = _val; children = _children; } }; */ class Solution { public int maxDepth(Node root) { if(root==null) return 0; int depth = 0; for(Node N : root.children) depth = Math.max(depth,maxDepth(N)); return 1 + depth; } } ================================================ FILE: LeetCode/Depth-first_Search/Minimum_Depth_of_Binary_Tree/6047198844.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int minDepth(TreeNode root) { if(root==null) return 0; int leftDepth = minDepth(root.left); int rightDepth = minDepth(root.right); if(leftDepth==0) return 1 + rightDepth; if(rightDepth==0) return 1 + leftDepth; return 1 + Math.min(leftDepth,rightDepth); //조심. } } ================================================ FILE: LeetCode/Depth-first_Search/Number of Closed Islands/6047198844.cpp ================================================ class Solution { private: int dy[4] = {-1,0,0,+1}; int dx[4] = {0,-1,+1,0}; public: bool isValid(int y, int x, int yn, int xn){ return (y >= 0 && y < yn) && (x >=0 && x < xn); } bool dfs(int y, int x, int yn, int xn, vector>& grid){ bool flag = true; for(int i = 0; i < 4; i++){ int ny = y + dy[i]; int nx = x + dx[i]; if(isValid(ny, nx, yn, xn)){ if(!grid[ny][nx]){ grid[ny][nx] = 1; if(!dfs(ny, nx, yn, xn, grid)) flag = false; } }else{ flag = false; } } return flag; } int closedIsland(vector>& grid) { int res = 0; int yn = grid.size(); int xn = grid[0].size(); for(int y = 0; y < yn; y++){ for(int x = 0; x < xn; x++){ if(!grid[y][x]&&dfs(y,x,yn,xn,grid)) res ++; } } return res; } }; ================================================ FILE: LeetCode/Depth-first_Search/Number_of_Islands/6047198844.cpp ================================================ class Solution { private: int dy[4] = {-1,+1, 0, 0}; int dx[4] = { 0, 0,-1,+1}; public: void dfs(int y, int x, const int max_y, const int max_x, vector>& grid){ grid[y][x] = '0'; for(int d = 0 ; d < 4; d++){ int there_y = y + dy[d]; int there_x = x + dx[d]; if(0 <= there_y&& there_y>& grid){ int res = 0; int max_y = grid.size(); int max_x = grid[0].size(); for(int y=0; y < max_y; y++) for(int x=0; x < max_x; x++) if(grid[y][x] == '1'){ dfs(y, x, max_y, max_x, grid); res++; } return res; } int numIslands(vector>& grid) { return dfsAll(grid); } }; ================================================ FILE: LeetCode/Depth-first_Search/Number_of_Islands/6047198844.py ================================================ class Solution: def dfs_sol(self, y: int, x: int, grid: List[List[str]]): grid[y][x] = "0" for dy, dx in (-1,0), (1,0), (0,1), (0,-1): ny = y + dy nx = x + dx if 0 <= ny < len(grid) and 0 <= nx < len(grid[0]) and grid[ny][nx] == "1": self.dfs_sol(ny,nx,grid) def numIslands(self, grid: List[List[str]]) -> int: res = 0 for y in range(len(grid)): for x in range(len(grid[0])): if grid[y][x] == "1": res += 1 self.dfs_sol(y,x,grid) return res #숫자가 아닌 문자열임. #if문 개행? ================================================ FILE: LeetCode/Depth-first_Search/Number_of_Islands/JeongShin.js ================================================ /** Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] 위와 같이 1이 육지고 0이 물일 떄, 육지를 찾는 문제 Output: 1 */ const numIslands = function (grid) { const visited = {}; if (!grid[0]) return 0; const [row, col] = [grid.length, grid[0].length]; let answer = 0; for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { const key = i + ',' + j; if (visited[key]) continue; visited[key] = true; if (grid[i][j] !== '1') continue; dfs(grid, visited, i, j, row, col); answer++; } } return answer; }; const dfs = (grid, visited, i, j, row, col) => { const neighbors = [[i - 1, j], [i + 1, j], [i, j + 1], [i, j - 1]]; for (const [i, j] of neighbors) { if (i < 0 || i >= row || j < 0 || j >= col) continue; const key = i + ',' + j; if (grid[i] && grid[i][j] && !visited[key]) { visited[key] = true; if (grid[i][j] === '1') dfs(grid, visited, i, j, row, col); } } }; ================================================ FILE: LeetCode/Depth-first_Search/PathSum_II/JeongShin.js ================================================ /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} target * @return {number[][]} */ const pathSum = function (root, target) { const answer = []; dfs(root, [], 0, answer, target); return answer; }; function dfs(node, route, sum, answer, target) { if (!node) return; const val = node.val; if (!node.right && !node.left) return sum + val === target ? answer.push([...route, val]) : null; if (node.right) dfs(node.right, [...route, val], sum + val, answer, target); if (node.left) dfs(node.left, [...route, val], sum + val, answer, target); } ================================================ FILE: LeetCode/Depth-first_Search/Reconstruct Itinerary/6047198844.py ================================================ #경로가 최소 하나 존재한다 -> 어디로 가든 경로가 있다. #다시풀기 class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: #변수이름 graph = collections.defaultdict(list) #티켓을 sort하면 알파벳 순으로 리스트가 만들어짐. for depart, arrival in sorted(tickets): graph[depart].append(arrival) result = [] def dfs(depart): while graph[depart]: dfs(graph[depart].pop(0)) result.append(depart) dfs("JFK") return result[::-1] ''' #pre_itinerary = 이미 방문한 경로 #누적 경로 / index로 저장. #ticket[0] -> 출발 / ticket[1] -> 도착 def dfs(pre_itinerary: List): if len(pre_itinerary) == len(tickets): result_itinerary.append(pre_itinerary[:]) return #pre_itinerary는 무조건 존재. 초기값은 JFK 출발. #가장 최근 경로 last_itinerary = tickets[pre_itinerary[-1]] for idx, ticket in enumerate(tickets): #직전 도착지가 출발지와 같은 티켓이면서 이전에 방문하지 않았던 경로. if ticket[0] == last_itinerary[1] and not idx in pre_itinerary: pre_itinerary.append(idx) dfs(pre_itinerary) pre_itinerary.pop() result_itinerary = [] for idx, ticket in enumerate(tickets): if ticket[0] == "JFK": dfs([idx]) #출발지점인 "JFK"를 붙여줘야할것임. result_itinerary = [["JFK"] + [tickets[idx][1] for idx in result] for result in result_itinerary] #result_itinerary에는 도착경로가 저장되어있음. return min(result_itinerary) #실수한 부분. 같은 간선이 중복된다면? #TLE -> 다시 접근 ''' ================================================ FILE: LeetCode/Depth-first_Search/Recover_Binary_Search_Tree/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: vector _arr; public: void inorder(TreeNode* root){ if(root==NULL) return; inorder(root->left); _arr.push_back(root->val); inorder(root->right); } void recover(TreeNode* root,int&idx){ if(root==NULL) return; recover(root->left,idx); root->val = _arr[idx++]; recover(root->right,idx); } void recoverTree(TreeNode* root) { inorder(root); sort(_arr.begin(),_arr.end()); int idx = 0; recover(root,idx); } }; ================================================ FILE: LeetCode/Depth-first_Search/Symmetric_Tree/6047198844.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { ArrayList left = new ArrayList(); ArrayList right = new ArrayList(); public void inOrderLeft(TreeNode root){ //nothing if(root==null){ left.add(null); return; } //root left.add(root.val); //left inOrderLeft(root.left); //right inOrderLeft(root.right); } public void inOrderRight(TreeNode root){ //nothing if(root==null){ right.add(null); return; } //root right.add(root.val); //right inOrderRight(root.right); //left inOrderRight(root.left); } public boolean isSymmetric(TreeNode root) { inOrderLeft(root); inOrderRight(root); return left.equals(right); } } ================================================ FILE: LeetCode/Depth-first_Search/Target_Sum/JeongShin.js ================================================ /** * @param {number[]} nums * @param {number} target * @return {number} * nums 가 주어졌을때 각 요소 별로 +, - 값을 가질때 합이 target 과 같아지는 방법의 개수를 구하는 문제 */ const findTargetSumWays = function (nums, target) { return dfs(nums, 0, 0, target, nums.length); }; const dfs = function (nums, idx ,sum, target, len) { if (idx === len) return sum === target; const num = nums[idx]; let result = 0; result += dfs(nums, idx + 1, sum + num, target, len); result += dfs(nums, idx + 1, sum - num, target, len); return result; }; console.log(findTargetSumWays([1, 1, 1, 1, 1], 3)) ================================================ FILE: LeetCode/Depth-first_Search/Validate_Binary_Search_Tree/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ /* 이진 탐색 트리 문제 */ class Solution { private: vector arr_; public: void dfs(TreeNode* root){ if(root==NULL) return; dfs(root->left); arr_.push_back(root->val); dfs(root->right); } bool isValidBST(TreeNode* root) { dfs(root); int arrSize = arr_.size(); for(int i = 1; i < arrSize; i++) if(arr_[i-1]>=arr_[i]) return false; return true; } }; ================================================ FILE: LeetCode/Divide_and_Conquer/Kth_Largest_Element_in_an_Array/6047198844.py ================================================ class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: heapq.heapify(nums) for _ in range(len(nums) - k): heapq.heappop(nums) return heapq.heappop(nums) ================================================ FILE: LeetCode/Divide_and_Conquer/Kth_Largest_Element_in_an_Array/HyeonJeong.java ================================================ package LeetCode.Divide_and_Conquer.Kth_Largest_Element_in_an_Array; import java.util.Arrays; class HyeonJeong { public int findKthLargest(int[] nums, int k) { Arrays.sort(nums); return nums[nums.length-k]; // k 번째 큰 요소 } } ================================================ FILE: LeetCode/Graph/787. Cheapest Flights Within K Stops/wongue.shin/._test.dart ================================================ import 'package:flutter_test/flutter_test.dart'; int _setTestCase(int n, List> flights, int src, int dst, int k) { final Solution solution = Solution(); return solution.findCheapestPrice(n, flights, src, dst, k); } void main() { test( "case 01", () => expect( _setTestCase( 4, [ [0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200] ], 0, 3, 1, ), equals(700), ), ); test( "case02", () => expect( _setTestCase( 3, [ [0, 1, 100], [1, 2, 100], [0, 2, 500] ], 0, 2, 1), equals(200), ), ); test( "case03", () => expect( _setTestCase( 3, [ [0, 1, 100], [1, 2, 100], [0, 2, 500] ], 0, 2, 0), equals(500), ), ); test( "case04", () => expect( _setTestCase( 17, [ [0, 12, 28], [5, 6, 39], [8, 6, 59], [13, 15, 7], [13, 12, 38], [10, 12, 35], [15, 3, 23], [7, 11, 26], [9, 4, 65], [10, 2, 38], [4, 7, 7], [14, 15, 31], [2, 12, 44], [8, 10, 34], [13, 6, 29], [5, 14, 89], [11, 16, 13], [7, 3, 46], [10, 15, 19], [12, 4, 58], [13, 16, 11], [16, 4, 76], [2, 0, 12], [15, 0, 22], [16, 12, 13], [7, 1, 29], [7, 14, 100], [16, 1, 14], [9, 6, 74], [11, 1, 73], [2, 11, 60], [10, 11, 85], [2, 5, 49], [3, 4, 17], [4, 9, 77], [16, 3, 47], [15, 6, 78], [14, 1, 90], [10, 5, 95], [1, 11, 30], [11, 0, 37], [10, 4, 86], [0, 8, 57], [6, 14, 68], [16, 8, 3], [13, 0, 65], [2, 13, 6], [5, 13, 5], [8, 11, 31], [6, 10, 20], [6, 2, 33], [9, 1, 3], [14, 9, 58], [12, 3, 19], [11, 2, 74], [12, 14, 48], [16, 11, 100], [3, 12, 38], [12, 13, 77], [10, 9, 99], [15, 13, 98], [15, 12, 71], [1, 4, 28], [7, 0, 83], [3, 5, 100], [8, 9, 14], [15, 11, 57], [3, 6, 65], [1, 3, 45], [14, 7, 74], [2, 10, 39], [4, 8, 73], [13, 5, 77], [10, 0, 43], [12, 9, 92], [8, 2, 26], [1, 7, 7], [9, 12, 10], [13, 11, 64], [8, 13, 80], [6, 12, 74], [9, 7, 35], [0, 15, 48], [3, 7, 87], [16, 9, 42], [5, 16, 64], [4, 5, 65], [15, 14, 70], [12, 0, 13], [16, 14, 52], [3, 10, 80], [14, 11, 85], [15, 2, 77], [4, 11, 19], [2, 7, 49], [10, 7, 78], [14, 6, 84], [13, 7, 50], [11, 6, 75], [5, 10, 46], [13, 8, 43], [9, 10, 49], [7, 12, 64], [0, 10, 76], [5, 9, 77], [8, 3, 28], [11, 9, 28], [12, 16, 87], [12, 6, 24], [9, 15, 94], [5, 7, 77], [4, 10, 18], [7, 2, 11], [9, 5, 41] ], 13, 4, 13, ), equals(47), ), ); } ================================================ FILE: LeetCode/Graph/787. Cheapest Flights Within K Stops/wongue.shin/solution.dart ================================================ import 'dart:collection'; /* Runtime: 326 ms Beats 100% ---------- Memory 164.6 MB Beats 20% * */ class Solution { static const int INT_MAX = 2147483647; final Map> _map = {}; int _ans = INT_MAX; final Map _memo = {}; void _makeAllNode(int n) { for (int i = 0; i < n; i++) { _map[i] = {}; } } void _initializeMap(int n, List> flights) { for (final List edge in flights) { final int start = edge[0]; final int end = edge[1]; final int cost = edge[2]; // dart 3 의 패턴매칭이 있었으면 코드가 짧아졌을탠데. _map[start]![end] = cost; } } void _addLinkedNode(int k, int des, Queue queue, QueueUnit current) { if (current.stopCounter > k) { return; } if (current.currentNode == des && _ans > current.currentCost) { _ans = current.currentCost; return; } if (_memo.containsKey(current.currentNode) && _memo[current.currentNode]! < current.currentCost) { return; } _memo[current.currentNode] = current.currentCost; _map[current.currentNode]?.forEach((key, value) { final int nextNode = key; final int cost = value; queue.add(QueueUnit( currentCost: current.currentCost + cost, currentNode: nextNode, stopCounter: current.stopCounter + 1, )); }); } void _bfs(int start, int des, int k) { Queue queue = Queue(); _addLinkedNode(k, des, queue, QueueUnit(currentCost: 0, currentNode: start, stopCounter: -1)); while (queue.isNotEmpty) { QueueUnit current = queue.removeFirst(); _addLinkedNode(k, des, queue, current); } } int findCheapestPrice(int n, List> flights, int src, int dst, int k) { _makeAllNode(n); _initializeMap(n, flights); _bfs(src, dst, k); return _ans == INT_MAX ? -1 : _ans; } } class QueueUnit { final int currentCost; final int currentNode; final int stopCounter; const QueueUnit({ required this.currentCost, required this.currentNode, required this.stopCounter, }); } ================================================ FILE: LeetCode/Graph/All Paths From Source to Target/sangmandu.py ================================================ ''' https://leetcode.com/problems/all-paths-from-source-to-target/ 그래프 : DFS 방식 ''' class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: stack = [[0]] size = len(graph) ans = [] while stack: path = stack.pop(0) if path[-1] == size - 1: ans.append(path) continue for node in graph[path[-1]]: stack.append(path + [node]) return ans ''' ''' ================================================ FILE: LeetCode/Graph/Find the Town Judge/sangmandu.py ================================================ ''' https://leetcode.com/problems/find-the-town-judge/ 기본적인 그래프 문제이지만 그래프 개념은 없는 듯 ''' class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: g1 = set() g2 = [] for a, b in trust: g1.add(a) g2.append(b) g1 = set(range(1, N+1)) - g1 if len(g1) != 1: return -1 ret = list(g1)[0] return ret if g2.count(ret) == N-1 else -1 ''' ''' ================================================ FILE: LeetCode/Graph/Find_Center_of_Star_Graph/sangmandu.py ================================================ ''' https://leetcode.com/problems/find-center-of-star-graph/ 1791. Find Center of Star Graph 그래프 ''' class Solution(object): def findCenter(self, edges): return edges[0][0] if edges[0][0] in edges[1] else edges[0][1] ''' ''' ================================================ FILE: LeetCode/Graph/Find_the_City_With_the_Smallest_Number_of_Neighbors_at_a_Threshold_Distance/6047198844.cpp ================================================ class Solution { private: const int INF = 987654321; public: int findTheCity(int n, vector>& edges, int distanceThreshold) { vector>> edge(n); for(int i = 0; i < edges.size(); i++){ int u = edges[i][0]; int v = edges[i][1]; int e = edges[i][2]; edge[u].push_back({v,e}); edge[v].push_back({u,e}); } int res_cnt = INF; int res_v = 0; for(int i = 0; i < n; i++){ vector dist(n,INF); int here = i; dist[here] = 0; priority_queue,vector>,greater>> pq; int cnt = 0; pq.push({dist[here],here}); while(!pq.empty()){ int here = pq.top().second; int d = pq.top().first; pq.pop(); if(d > distanceThreshold) break; if(d > dist[here]) continue; for(auto p : edge[here]){ int there = p.first; int e = p.second; if(d+e < dist[there] && d+e<=distanceThreshold){ if(dist[there] > distanceThreshold) cnt ++ ; dist[there] = d+e; pq.push({dist[there],there}); } } } if(res_cnt >= cnt){ res_cnt = cnt; res_v = i; } } return res_v; } }; ================================================ FILE: LeetCode/Graph/Minimum Number of Vertices to Reach All Nodes/sangmandu.py ================================================ ''' https://leetcode.com/problems/all-paths-from-source-to-target/ 그래프 : 목적지만 제거. set 이용 ''' class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: st, ed = list(zip(*edges)) return list(set(range(n)) - set(ed)) ''' ''' ================================================ FILE: LeetCode/Graph/Path_With_Minimum_Effort/6047198844.cpp ================================================ typedef pair> P; class Solution { private: int dy[4] = {0,1,0,-1}; int dx[4] = {-1,0,1,0}; const int INF = 987654321; public: bool isValid(int y, int x, int yn, int xn){ return (0<=y&&y>& heights) { priority_queue, greater

> pq; int yn = heights.size(); int xn = heights[0].size(); vector> mef(yn,vector(xn,INF)); mef[0][0] = 0; pq.push({mef[0][0],{0,0}}); while(!pq.empty()){ P tmp = pq.top(); pq.pop(); int y = tmp.second.first; int x = tmp.second.second; int effort = tmp.first; if(mef[y][x] < effort) continue; for(int i = 0; i < 4; i++){ int ny = y + dy[i]; int nx = x + dx[i]; if(isValid(ny,nx,yn,xn)){ int dif = abs(heights[ny][nx] - heights[y][x]); int r = max(effort,dif); if(mef[ny][nx] > r){ mef[ny][nx] = r; pq.push({mef[ny][nx],{ny,nx}}); } } } } return mef[yn-1][xn-1]; } }; ================================================ FILE: LeetCode/Graph/Path_with_Maximum_Probability/6047198844.cpp ================================================ class Solution { public: double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { int src = start; int dst = end; vector< vector>> edg(n); for(int i = 0; i < edges.size(); i++){ int u = edges[i][0]; int v = edges[i][1]; double d = succProb[i]; edg[u].push_back({v,d}); edg[v].push_back({u,d}); } priority_queue > pq; vector dist(n,0); dist[src] = 1; pq.push({dist[src],src}); while(!pq.empty()){ pair p = pq.top(); pq.pop(); int here = p.second; double adj = p.first; if(dist[here] > adj) continue; for(auto e : edg[here]){ int there = e.first; double d = e.second; if(dist[there] < adj * d){ dist[there] = adj * d; pq.push({dist[there],there}); } } } return dist[dst]; } }; //자료형 주의자료형 주의 ================================================ FILE: LeetCode/Graph/Redundant_Connection/sangmandu.py ================================================ ''' https://leetcode.com/problems/redundant-connection/ 684. Redundant Connection 그래프 ''' class Solution(object): def findRedundantConnection(self, edges): disjoint_set=[i for i in range(len(edges)+1)] def find_parent(i): while i!=disjoint_set[i]: i=disjoint_set[i] return i def union(a,b): source=find_parent(a) target=find_parent(b) disjoint_set[source]=target if source==target: return False return True for x,y in edges: if not union(x,y): return [x,y] ''' 개념 이해 https://bowbowbow.tistory.com/26 코드 참고 https://leetcode.com/problems/redundant-connection/discuss/1240764/almost-perfect-solution-simple-and-powerful-or-disjoint-set-union-or-python3 이 문제를 풀려면 Union-Find : Disjoint Set 이라는 개념을 알아야 한다. DFS로도 풀수 있지만 시간 복잡도가 O(N) 이다. Disjoint Set 은 시간 복잡도가 O(N) 이하 이다. (트리 구조가 연결리스트로 될 떄 O(N)) 참고로 이 방법은 Union 시에 rank를 고려하지 않는 방법이다. (최적화도 고려하지 않았다) 여기서 rank와 최적화 까지 고려하면 머리가 더 아플듯... ''' ================================================ FILE: LeetCode/Graph/Regions Cut By Slashes/sangmandu.py ================================================ ''' https://leetcode.com/problems/regions-cut-by-slashes/ GRAPH : BFS 이용 한 개의 정사각형이 9개의 작은 정사각형으로 이루어져있다고 생각. 이 때 대각선을 그으면 BFS로 visited 여부 확인 가능 (4개의 정사각형은 대각선방향으로 있는 영역을 visited 여부 확인 불가) ''' class Solution: def regionsBySlashes(self, grid: List[str]) -> int: N = len(grid) square = [[0] * N * 3 for _ in range(N * 3)] for j in range(N): for i in range(N): if grid[j][i] == ' ': continue if grid[j][i] == '/': for k in range(3): square[j * 3 + k][i * 3 + 2 - k] = 1 continue if grid[j][i] == '\\': for k in range(3): square[j * 3 + k][i * 3 + k] = 1 continue def bfs(y, x): for ay, ax in [(0, 1), (0, -1), (1, 0), (-1, 0)]: ny, nx = y + ay, x + ax if 0 <= ny < 3 * N and 0 <= nx < 3 * N and visited[ny][nx] == 0 and square[ny][nx] == 0: visited[ny][nx] = 1 bfs(ny, nx) visited = [[0] * N * 3 for _ in range(N * 3)] cnt = 0 for y in range(N * 3): for x in range(N * 3): if visited[y][x] == 0 and square[y][x] == 0: visited[y][x] = 1 bfs(y, x) cnt += 1 return cnt ''' 코드 속도가 좀 느려서 아쉽. ''' ================================================ FILE: LeetCode/Graph/Sort Integers by The Power Value/sangmandu.py ================================================ ''' https://leetcode.com/problems/sort-integers-by-the-power-value/ Graph : 시행 한 결과를 매번 cache에 저장하여 속도 향상 ''' class Solution: def getKth(self, lo: int, hi: int, k: int) -> int: ans = [] cache = {} for o_num in range(lo, hi + 1): num = o_num prior = [] cnt = 0 while num != 1: cnt += 1 if num in cache: cnt += cache[num] break prior.append(num) num = 3 * num + 1 if num % 2 else num // 2 ans.append((cnt, o_num)) for ele in prior: cnt -= 1 cache[ele] = cnt return sorted(ans)[k - 1][1] ''' ''' ================================================ FILE: LeetCode/Graph/keys-and-rooms/sangmandu.py ================================================ ''' https://leetcode.com/problems/keys-and-rooms/ GRAPH ''' class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: n = len(rooms) visited = [0] * n stack = [0] while stack: key = stack.pop() if not visited[key]: visited[key] = 1 for room in rooms[key]: stack.append(room) return visited.count(1) == n ''' ''' ================================================ FILE: LeetCode/Greedy/ Split_a_String_in_Balanced_Strings/eyabc.js ================================================ const balancedStringSplit = function (s) { let [R, L, cnt] = [0, 0, 0]; Array.from(s, (char) => { (char === 'R') ? (R += 1) : (L += 1); (R === L) && ([R, L, cnt] = [0, 0, cnt + 1]); }); return cnt; }; console.log(balancedStringSplit('RLRRLLRLRL') === 4); console.log(balancedStringSplit('RLLLLRRRLR') === 3); console.log(balancedStringSplit('LLLLRRRR') === 1); console.log(balancedStringSplit('RLRRRLLRLL') === 2); ================================================ FILE: LeetCode/Greedy/Assign_Cookies/HyeonJeong.java ================================================ package LeetCode.Greedy.Assign_Cookies; import java.util.Arrays; class HyeonJeong { public int findContentChildren(int[] g, int[] s) { //아이들이 만족하는 쿠키의 최소 크기가 담긴 g와 쿠키 크기가 담긴 s 배열을 이용해 만족하는 최대 경우를 구하는 문제 int count = 0, g_len = g.length, s_len = s.length, start = g_len-1; // 자주 사용될 두 배열의 길이를 변수에 저장 // start를 s[s_len-1] >= g[g_len-1]일 경우 사용될 값으로 선언 if (s_len == 0) { // 줄 수 있는 쿠키 크기가 담긴 값이 없는 경우 return count; } Arrays.sort(g); Arrays.sort(s); for (int i = g_len-1; i > -1 ; i--) { if (g[i] <= s[s_len-1]) { start = i; break; } } int c = 0; // s 배열에서 사용될 수 있는 최대 값의 인덱스를 가리키기 위해 사용 for (int i = start; i > -1; i--) { if (s_len == c) { break; } if (g[i] <= s[s_len-(1+c)]) { count++; c++; } } return count; } } ================================================ FILE: LeetCode/Greedy/Can_Place_Flowers/HyeonJeong.java ================================================ package LeetCode.Greedy.Can_Place_Flowers; class HyeonJeong { public boolean canPlaceFlowers(int[] flowerbed, int n) { int len = flowerbed.length; if (n == 0) // 심을 꽃이 없는 경우 return true; if (len == 1) { // 주어진 화단이 1자리인 경우 if (flowerbed[0] == 0 && n == 1) return true; else return false; } int result = 0, j = 0; if (flowerbed[0] + flowerbed[1] == 0) { // 화단의 첫 번째 자리에 심을 수 있는 경우 flowerbed[0] = 1; result += 1; } if (flowerbed[len-2] + flowerbed[len-1] == 0) { // 화단의 마지막 자리에 심을 수 있는 경우 flowerbed[len-1] = 1; result += 1; } if (result >= n) return true; while (j < n) { for (int i = 1; i < len-1; i++) { if (flowerbed[i-1] + flowerbed[i] + flowerbed[i+1] == 0) { // 2 ~ (끝-1) 번째 자리에 꽃을 심을 수 있는 경우 flowerbed[i] = 1; result += 1; } if (result == n) return true; } j++; } return false; } } ================================================ FILE: LeetCode/Greedy/Car_Pooling/HyeonJeong.py ================================================ class Solution(object): def carPooling(self, trips, capacity): # 모든 여행에서 모든 승객을 태우고 내릴 수 있는지를 확인하는 문제 for trip in range(min([x[1] for x in trips]), max([x[2] for x in trips])+1): people = 0 for num, start, end in trips: if start <= trip < end: people += num if people > capacity: return False return True ================================================ FILE: LeetCode/Greedy/Group_the_People_Given_the_Group_Size_They_Belong_To/HyeonJeong.py ================================================ class Solution: def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: order_s = [[] for x in range(max(groupSizes))] result = [] for i, x in enumerate(groupSizes): # 그룹의 크기별로 사람들을 나누는 과정 order_s[x-1] += [i] for i, n in enumerate(order_s): length = len(n) if length == i+1: result.append(n) if length > i+1: index = 0 for j in range(int(length/(i+1))): # 필요한 크기로 그룹을 쪼개는 과정 result.append(n[index:index+(i+1)]) index += i+1 return result ================================================ FILE: LeetCode/Greedy/Group_the_People_Given_the_Group_Size_They_Belong_To/sangmandu.py ================================================ ''' https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/ Group the People Given the Group Size They Belong To dictionary 사용 ''' class Solution(object): def groupThePeople(self, groupSizes): dic = {} for idx, val in enumerate(groupSizes): dic.setdefault(val, []) dic[val].append(idx) answer = [] for key in dic.keys(): size = len(dic[key]) for idx in range(0, size, key): answer.append(dic[key][idx:idx + key]) return answer ''' dict.setdefault 보다 더 좋은 방법이 있는 것을 알았다. collections.defaultdict(param) param에 int를 넘기면 0으로 초기화가 되며 list를 넘기면 []]로 초기화가 된다 ''' ================================================ FILE: LeetCode/Greedy/Is_Subsequence/HyeonJoeng.py ================================================ class Solution: def isSubsequence(self, s: str, t: str) -> bool: slist = list(s) tlist = list(t) j = 0 i = 0 while j < len(slist) and i < len(tlist): if slist[j] != tlist[i]: tlist.pop(i) else: i += 1 j += 1 print(slist) print(tlist) return True if slist == tlist[:len(slist)] else False ================================================ FILE: LeetCode/Greedy/Jump_Game/JeongShin.js ================================================ /** * 출처 : https://leetcode.com/problems/jump-game/ * * 문제: * 양의 정수로 주어진 배열이 있을때, 가장 첫번째 요소는 최초 위치를 나타낸다. * 그 다음부터 요소들 마다 점프할 수 있는 최대 범위를 나타낸다. * 마지막 인덱스에 도달 할 수 있는지 여부에 대해 반환 하여라. * * @param {number[]} nums * @return {boolean} */ // Sol 1. Runtime : 2496 ms Memory : 42.3 MB // 👉 Greedy X const canJump = function (nums) { const target = nums.length - 1; const possible = [true]; for (const [idx, num] of nums.entries()) { if (possible[target]) return true; if (!possible[idx]) continue; const end = idx + num; for (let i = idx; i <= end; i++) { possible[i] = true; } } return false; }; // Sol2. Runtime : 76ms, Memory : 42.3 MB const canJump2 = function (nums) { let distance = 0; const target = nums.length - 1; for (let i = 0; i <= distance; i++) { distance = Math.max(distance, i + nums[i]); if (distance >= target) return true } return false; }; console.log(canJump([2, 3, 1, 1, 4])) // true console.log(canJump([3, 2, 1, 0, 4])) // false ================================================ FILE: LeetCode/Greedy/Maximize_Sum_Of_Array_After_K_Negations/6047198844.cpp ================================================ class Solution { public: int largestSumAfterKNegations(vector& A, int K) { sort(A.begin(),A.end()); int res = 0; for(int i = 0 ; i < A.size(); i++){ if(K){ if(A[i]<0){ A[i] = -A[i]; K--; }else{ if(K%2){ if(i==0||A[i-1]>A[i]){ A[i] = -A[i]; }else{ res += -A[i-1]*2; } } K=0; } } res += A[i]; } return res; } }; ================================================ FILE: LeetCode/Greedy/Remove_Covered_Intervals/607198844.py ================================================ class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: n = len(intervals) check = [True]*n for i in range(n): for j in range(i+1,n): if check[i] and check[j]: a,b,c,d = intervals[i][0], intervals[i][1], intervals[j][0], intervals[j][1] if c <= a and b <= d: check[i] = False break elif a <= c and d <= b: check[j] = False return check.count(True) ================================================ FILE: LeetCode/Greedy/Remove_Covered_Intervals/HyeonJeong.py ================================================ class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: i = 0 while i+1 < len(intervals): n1, n2 = intervals[i] for j, [m1, m2] in enumerate(intervals[i+1:]): if n1 <= m1 and m2 <= n2: intervals.pop(i+j+1) i -= 1 break elif m1 <= n1 and n2 <= m2: intervals.pop(i) i -= 1 break i += 1 return len(intervals) ================================================ FILE: LeetCode/Hash_Table/Daily Temperatures/6047198844.py ================================================ class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: res = [0] * len(temperatures) stack = [] for i in range(len(temperatures)): while stack and temperatures[stack[-1]] < temperatures[i]: res[stack.pop()] = i - stack[-1] stack.append(i) return res ================================================ FILE: LeetCode/Hash_Table/Find the Difference/6047198844.py ================================================ class Solution: def findTheDifference(self, s: str, t: str) -> str: return (Counter(t) - Counter(s)).most_common(1)[0][0] ================================================ FILE: LeetCode/Hash_Table/First_Unique_Character_in_a_String/6047198844.py ================================================ class Solution: def firstUniqChar(self, s: str) -> int: table = Counter(s) for idx, char in enumerate(s): if table[char] == 1: return idx return -1 ================================================ FILE: LeetCode/Hash_Table/Grid Illumination/6047198844.cpp ================================================ class Solution { private: unordered_map cols, rows, leftDiag, rightDiag; unordered_map > lampGrid; int d[3] = {-1,0,1}; public: vector gridIllumination(int N, vector>& lamps, vector>& queries) { vector ans; for(int i = 0; i < lamps.size(); i++){ int y = lamps[i][0]; int x = lamps[i][1]; if(lampGrid[y].insert(x).second){ cols[x]++; rows[y]++; leftDiag[y-x]++; rightDiag[y+x]++; } } for(int i = 0; i bool: visited = set() while True: tmp = 0 while n > 0: tmp += (n % 10) ** 2 n //= 10 if tmp == 1: return True elif tmp in visited: return False visited.add(tmp) n = tmp ================================================ FILE: LeetCode/Hash_Table/Implement_Trie_(Prefix_Tree)/6047198844.py ================================================ import collections class TrieNode: def __init__(self): self.word = False self.children = collections.defaultdict(TrieNode) class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def insert(self, word: str) -> None: """ Inserts a word into the trie. """ node = self.root for char in word: node = node.children[char] node.word = True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self.root for char in word: if char not in node.children: return False node = node.children[char] return node.word def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ node = self.root for char in prefix: if char not in node.children: return False node = node.children[char] return True # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix) ================================================ FILE: LeetCode/Hash_Table/Integer_to_Roman/6047198844.py ================================================ class Solution: def intToRoman(self, num: int) -> str: table = { 1: "I", 4: "IV", 5: "V", 9: "IX", 10: "X", 40: "XL", 50: "L", 90: "XC", 100: "C", 400: "CD", 500: "D", 900: "CM", 1000: "M", 5000: "" } ans = "" for div in (1000, 100, 10, 1): converted = num // div if converted*div in table: ans += table[converted*div] else: five, one = converted//5, converted%5 ans += table[5*div]*five ans += table[div]*one num %= div return ans ================================================ FILE: LeetCode/Hash_Table/Intersection_of_Two_Arrays/6047198844.cpp ================================================ class Solution { public: vector intersection(vector& nums1, vector& nums2) { sort(nums1.begin(),nums1.end()); sort(nums2.begin(),nums2.end()); nums1.erase(unique(nums1.begin(),nums1.end()),nums1.end()); nums2.erase(unique(nums2.begin(),nums2.end()),nums2.end()); int i = 0; int j = 0; vector res; while(i nums2[j]){ j++; }else{ i++; } } return res; } }; ================================================ FILE: LeetCode/Hash_Table/Isomorphic Strings/6047198844.py ================================================ class Solution: def isIsomorphic(self, s: str, t: str) -> bool: #s를 dict에 등록하자 dict1 = {} dict2 = {} idx = 0 for char in zip(s,t): c1, c2 = char if c1 not in dict1: dict1[c1] = c2 elif dict1[c1] != c2: return False if c2 not in dict2: dict2[c2] = c1 elif dict2[c2] != c1: return False return True ================================================ FILE: LeetCode/Hash_Table/Linked_List_Cycle/6047198844.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: walker = head runner = head while runner and runner.next: walker = walker.next runner = runner.next.next if walker == runner: return True return False ================================================ FILE: LeetCode/Hash_Table/Top_K_Frequent_Elements/6047198844.py ================================================ #dictionary 사용법 #https://dojang.io/mod/page/view.php?id=2308 #Counter 사용법 #https://www.daleseo.com/python-collections-counter class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: return [i for (i,v) in Counter(nums).most_common()[:k]] ================================================ FILE: LeetCode/Hash_Table/Two_Sum/6047198844.cpp ================================================ class Solution { public: vector twoSum(vector& nums, int target) { unordered_map map; for(int i=0; i < nums.size(); i++){ if(map.find(target - nums[i])==map.end()){ map[nums[i]] = i; } else{ return vector({i,map[target - nums[i]]}); } } return vector(); } }; ================================================ FILE: LeetCode/Hash_Table/Valid_Anagram/6047198844.py ================================================ class Solution: def isAnagram(self, s: str, t: str) -> bool: return Counter(s) == Counter(t) ================================================ FILE: LeetCode/Hash_Table/Valid_Sudoku/6047198844.py ================================================ class Solution: def is_column_valid(self, board): for column in zip(*board): if not self.is_unit_valid(column): return False return True def is_row_valid(self, board): for row in board: if not self.is_unit_valid(row): return False return True def is_square_valid(self, board): for i in (0,3,6): for j in (0,3,6): square = [board[y][x] for x in range(j,j+3) for y in range(i,i+3)] if not self.is_unit_valid(square): return False return True def is_unit_valid(self, unit): unit = [i for i in unit if i != '.'] return len(set(unit)) == len(unit) def isValidSudoku(self, board: List[List[str]]) -> bool: return (self.is_column_valid(board) and self.is_row_valid(board) and self.is_square_valid(board)) ================================================ FILE: LeetCode/Heap/Network_Delay_Time/6047198844.cpp ================================================ class Solution { private: const int INF = 987654321; public: int networkDelayTime(vector>& times, int n, int k) { vector>> edges(n+1); for(int i = 0; i < times.size(); i++){ int u = times[i][0]; int v = times[i][1]; int e = times[i][2]; edges[u].push_back({v,e}); } vector dist(n+1,INF); // check안하면 0 priority_queue ,vector>,less>> pq; dist[0] = 0; dist[k] = 0; pq.push({dist[k],k}); while(!pq.empty()){ int here = pq.top().second; int cost = pq.top().first; pq.pop(); if(cost > dist[here]) continue; for(auto p : edges[here]){ int there = p.first; int e = p.second; if(cost + e < dist[there]){ dist[there] = cost + e; pq.push({dist[there],there}); } } } int res = *max_element(dist.begin(),dist.end()); return res == INF ? -1 : res; } }; ================================================ FILE: LeetCode/Linked_List/Add_Two_Numbers/6047198844.py ================================================ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: carry = 0 res = cur = ListNode(0) while l1 or l2 or carry: # l1, l2가 모두 널이면서 carry가 없을때 종료한다. val1 = 0 if l1: val1 = l1.val l1 = l1.next val2 = 0 if l2: val2 = l2.val l2 = l2.next carry, val = divmod(val1 + val2 + carry, 10) cur.next = ListNode(val) cur = cur.next return res.next ================================================ FILE: LeetCode/Linked_List/Add_Two_Numbers/HyeonJeong.py ================================================ class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: nlist = [] carry = 0 while 1: if l1 == None and l2 == None: break x = l1.val if l1 != None else 0 y = l2.val if l2 != None else 0 add = x + y + carry if add > 9: carry = add//10 nlist += [add%10] else: carry = 0 nlist += [add] l1 = l1.next if l1 != None else None l2 = l2.next if l2 != None else None if carry != 0: nlist += [carry] result = None for n in nlist: if result != None: tmp.next = ListNode(n) tmp = tmp.next else: result = ListNode(n) tmp = result return result ================================================ FILE: LeetCode/Linked_List/Convert_Sorted_List_to_Binary_Search_Tree/6047198844.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* toBST(ListNode* head, ListNode* tail){ if(head==tail) return NULL; ListNode* fast = head; ListNode* slow = head; while(fast!=tail&&fast->next!=tail){ fast = fast->next->next; slow = slow->next; } TreeNode* root = new TreeNode(slow->val); root->left = toBST(head,slow); root->right = toBST(slow->next,tail); return root; } TreeNode* sortedListToBST(ListNode* head) { return toBST(head,NULL); } }; ================================================ FILE: LeetCode/Linked_List/Delete_Node_in_a_Linked_List/6047198844.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next ================================================ FILE: LeetCode/Linked_List/Merge Two Sorted Lists/6047198844.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(0); ListNode* p = dummy; while(l1!=NULL&&l2!=NULL){ if(l1->val < l2->val){ p->next = l1; l1 = l1->next; }else{ p->next = l2; l2 = l2->next; } p = p->next; } p->next = l1 ? l1 : l2; return dummy->next; } }; ================================================ FILE: LeetCode/Linked_List/Merge k Sorted Lists/6047198844.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: l = [] for list in lists: while list: l.append(list.val) list = list.next l.sort() root = cur = ListNode(None) for val in l: node = ListNode(val) cur.next = node cur = cur.next return root.next ================================================ FILE: LeetCode/Linked_List/Odd Even Linked List/6047198844.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: root = head odd = odd_cur = ListNode(0) even = even_cur = ListNode(0) while head and head.next: odd_cur.next, even_cur.next = head, head.next odd_cur, even_cur = odd_cur.next, even_cur.next head = head.next.next if head: odd_cur.next = head odd_cur = odd_cur.next even_cur.next = None odd_cur.next = even.next return root ================================================ FILE: LeetCode/Linked_List/Palindrome_Linked_List/HyeonJeong.java ================================================ package Palindrome_Linked_List; import java.util.ArrayList; class HyeonJeong { public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) return true; int len = 0; ArrayList list = new ArrayList(); while (head != null) { list.add(head.val); head = head.next; len++; } for (int i = 0; i < len/2; i++) { if ((int)list.get(i) != (int)list.get(len-(i+1))) { // 회문 확인을 위해서 중간을 기준으로 확인 return false; } } return true; } } class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val;} ListNode(int val, ListNode next) { this.val = val; this.next = next; } } ================================================ FILE: LeetCode/Linked_List/Partition List/6047198844.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]: first = dummy_first = ListNode(0) second = dummy_second = ListNode(0) while head: if head.val < x: dummy_first.next = ListNode(head.val) dummy_first = dummy_first.next else: dummy_second.next = ListNode(head.val) dummy_second = dummy_second.next head = head.next dummy_first.next = second.next return first.next ================================================ FILE: LeetCode/Linked_List/Remove_Duplicates_from_Sorted_List/6047198844.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: cur = head while cur: next_cur = cur while next_cur and next_cur.val == cur.val: next_cur = next_cur.next cur.next = next_cur cur = cur.next return head ================================================ FILE: LeetCode/Linked_List/Remove_Duplicates_from_Sorted_List/HyeonJeong.py ================================================ class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: result = None value = -101 # 정렬된 링크드 리스트의 중복요소 제거에 사용 while head != None: if value < head.val: value = head.val if result != None: tmp.next = ListNode(value) tmp = tmp.next else: result = ListNode(value) tmp = result head = head.next return result ================================================ FILE: LeetCode/Linked_List/Remove_Linked_List_Elements/HyeonJeong.java ================================================ package Remove_Linked_List_Elements; class HyeonJeong { public ListNode removeElements(ListNode head, int val) { if (head == null) // 노드 값이 없는 경우 return null; while (head != null && head.val == val) { // 시작 노드의 값을 제거 head = head.next; } if (head == null) // 노드 값이 모두 제거되는 경우 return null; ListNode copy = head; // 반환할 링크드 리스트의 시작 while (head != null) { if (head.next != null && head.next.val == val) { // val과 노드의 값이 같은 경우 head.next = head.next.next; continue; } head = head.next; } return copy; } } class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val;} ListNode(int val, ListNode next) { this.val = val; this.next = next; } } ================================================ FILE: LeetCode/Linked_List/Remove_Nth_Node_From_End_of_List/6047198844.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: size = 0 cur = head while cur: size += 1 cur = cur.next removed_n = size - n cur = head prev = None for _ in range(removed_n): prev, cur = cur, cur.next if prev: prev.next = cur.next else: head = head.next return head ================================================ FILE: LeetCode/Linked_List/Reverse_Linked_List_II/HyeonJeong.py ================================================ class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: nlist = [] while head != None: nlist += [head.val] head = head.next for i in range((n-m)//2+1): num = nlist[m-1+i] nlist[m-1+i] = nlist[n-1-i] nlist[n-1-i] = num result = 0 for n in nlist: if result != 0: tmp.next = ListNode(n) tmp = tmp.next else: result = ListNode(n) tmp = result return result ================================================ FILE: LeetCode/Linked_List/Rotate List/6047198844.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: # 엣지처리 if not head: return head # 길이 last = head LEN = 1 while last.next: last = last.next LEN += 1 # k계산 k = k % LEN # 예외케이스 if k == 0: return head cur = head for _ in range(LEN - k - 1): cur = cur.next dummy_head = cur.next # cur은 마지막 노드이다. cur.next = None last.next = head return dummy_head ================================================ FILE: LeetCode/Linked_List/Swap_Nodes_in_Pairs/6047198844.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: root = cur = ListNode(0) cur.next = head while cur.next and cur.next.next: p, q = cur.next, cur.next.next cur.next, p.next, q.next = q, q.next, p cur = p return root.next ================================================ FILE: LeetCode/Linked_List/Swap_Nodes_in_Pairs/HyeonJeong.java ================================================ package Swap_Nodes_in_Pairs; class HyeonJeong { ListNode swapPairs(ListNode head) { ListNode node = head; int tmp; while (node != null && node.next != null) { tmp = node.val; node.val = node.next.val; node = node.next; node.val = tmp; node = node.next; } return head; } } class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val;} ListNode(int val, ListNode next) { this.val = val; this.next = next; } } ================================================ FILE: LeetCode/Linked_List/sangmandu.py ================================================ ''' https://leetcode.com/problems/add-two-numbers/ Linked_List 문제 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: num1 = num2 = '' while l1 != None: num1 = str(l1.val) + num1 l1 = l1.next while l2 != None: num2 = str(l2.val) + num2 l2 = l2.next ret = list(str(int(num1) + int(num2))) tmp = None for num in ret: curNode = ListNode(num, tmp) tmp = curNode return curNode ''' ''' ================================================ FILE: LeetCode/Math/Add_Binary/6047198844.py ================================================ class Solution: def addBinary(self, a: str, b: str) -> str: # 더한다. -> 더한몫을 2로 나눈다. 나머지는 그 자리수가 되고 몫은 다음자리수로 넘어간다. AN = len(a) BN = len(b) N = max(AN, BN) res = '' rnd = 0 for idx in range(1, N + 1): if idx <= AN and a[-idx] == '1': rnd += 1 if idx <= BN and b[-idx] == '1': rnd += 1 res = str(rnd % 2) + res rnd //= 2 if rnd == 1: res = '1' + res return res ================================================ FILE: LeetCode/Math/Add_Binary/HyeonJeong.py ================================================ class Solution: def addBinary(self, a: str, b: str) -> str: sum = int(a, 2) + int(b, 2) # int(문자열, 2) : 문자열을 읽어서 2진수로 바꿈 # sum에는 두 숫자가 합쳐진 10진수가 저장됨 return bin(sum)[2:] # bin()이 해당 숫자를 이진수로 만들고 문자열로 반환시킴 ================================================ FILE: LeetCode/Math/Add_Digits/6047198844.py ================================================ class Solution: def addDigits(self, num: int) -> int: while num // 10 != 0: tmp = 0 while num != 0: tmp += num % 10 num //= 10 num = tmp return num ================================================ FILE: LeetCode/Math/Add_Digits/HyeonJeong.py ================================================ class Solution: def addDigits(self, num: int) -> int: s = str(num) while 1: if len(s) == 1: return int(s) #한 자리 수이면 문자를 숫자로 리턴 s = str(sum([int(i) for i in s])) #숫자를 문자로 만들어서 while문에서 다시 길이 검사 할 수 있게 함 # addDigits(38) == 2 # 38 -> 3 + 8 = 11 -> 1 + 1 = 2 ================================================ FILE: LeetCode/Math/Check_If_It_Is_a_Straight_Line/HyeonJeong.java ================================================ package LeetCode.Math.Check_If_It_Is_a_Straight_Line; import java.util.Arrays; class HyeonJeong { public boolean checkStraightLine(int[][] coordinates) { int check = 0, len = coordinates.length; float [] slope = new float[len-1]; for (int i = 1; i < len; i++) { if (coordinates[i-1][0] == coordinates[i][0]) check += 1; } if (check == len-1) { // 주어진 [x,y]들로 x축과 평행한 직선이 만들어지는 경우 return true; } else if (check != 0) return false; for (int i = 1; i < len; i++) // 기울기 값을 배열에 넣음 slope[i-1] = (float)(coordinates[i][1]-coordinates[i-1][1])/(coordinates[i][0]-coordinates[i-1][0]); Arrays.sort(slope); if (slope[0] != slope[len-2]) // 가장 큰 값과 가장 작은 값을 비교해서 모두 같은 값을 가지는지 확인 return false; return true; } } ================================================ FILE: LeetCode/Math/Complement_of_Base_10_Integer/HyeonJeong.py ================================================ class Solution: def bitwiseComplement(self, N: int) -> int: num = bin(N) answer = '' for i in num[2:]: if i == '0': answer += '1' else: answer += '0' return int(answer, 2) # 2진수를 10진수로 ================================================ FILE: LeetCode/Math/Day_of_the_Week/6047198844.py ================================================ class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: return datetime.date(year, month, day).strftime("%A") ================================================ FILE: LeetCode/Math/Day_of_the_Year/6047198844.py ================================================ class Solution: def dayOfYear(self, date: str) -> int: day = datetime.date.fromisoformat(date) return int(day.strftime('%j')) ================================================ FILE: LeetCode/Math/Day_of_the_Year/HyeonJeong.py ================================================ class Solution: def dayOfYear(self, date: str) -> int: mlist = [31,28,31,30,31,30,31,31,30,31,30,31] year, month, day = map(int, dat.split('-') # year = int(date[0:4]) # month = int(date[5:7]) # day = int(date[8:10]) if (year % 100 != 0 and year % 4 == 0) or year % 400 == 0: mlist[1] = 29 answer = 0 for i in range(month-1): answer += mlist[i] return answer + day ================================================ FILE: LeetCode/Math/Distribute_Candies_to_People/HyeonJeong.java ================================================ package LeetCode.Math.Distribute_Candies_to_People; class HyeonJeong { public int[] distributeCandies(int candies, int num_people) { /* 첫번째 사람부터 1개의 사탕을 주기 시작해서 1개씩 사탕을 늘려서 다음 사람에게 주고, 마지막 사람에게 주고도 사탕이 남은 경우에는 다시 첫번째 사람에게 사탕을 나눠준 사탕의 배열을 반환하는 문제 */ int []result = new int[num_people]; int n = 1, i = 0; while (true) { if (candies >= n) { result[i] += n; candies -= n; n += 1; } else { result[i] += candies; break; } i += 1; if (i == num_people) { i = 0; } } return result; } } ================================================ FILE: LeetCode/Math/Divide_Two_Integers/6047198844.py ================================================ class Solution: def divide(self, dividend: int, divisor: int) -> int: positive = (dividend < 0) is (divisor < 0) dividend, divisor = abs(dividend), abs(divisor) if dividend < divisor: return 0 res = 0 cnt = 1 ndivisor = divisor while dividend >= ndivisor: dividend -= ndivisor res += cnt # 2배 cnt <<= 1 ndivisor <<= 1 res += self.divide(dividend, divisor) if positive == False: res = -res if -2 ** 31 <= res <= 2 ** 31 - 1: return res return 2 ** 31 - 1 ================================================ FILE: LeetCode/Math/Divisor_Game/HyeonJeong.java ================================================ package Divisor_Game; class HyeonJeong { public boolean divisorGame(int N) { int state = 0; while (N > 1) { for (int divisor = 1; divisor < N/2+1; divisor++) { if (N%divisor == 0) { N = N-divisor; break; } } state++; } return (state%2 == 0)?false:true; } } ================================================ FILE: LeetCode/Math/Factorial_Trailing_Zeroes/HyeonJeong.py ================================================ from math import factorial class Solution: def trailingZeroes(self, n: int) -> int: # n!의 결과에서 후행 0의 개수 구하는 문제 if n == 0: return 0 result = list(str(factorial(n))) # n!의 결과의 길이와 각 자리수를 분리해서 보기 위해 list 처리 index = len(result) - 1 cnt = 0 while (index >= 0): if result[index] != '0': break else: index -= 1 cnt += 1 return cnt ================================================ FILE: LeetCode/Math/Find_Numbers_with_Even_Number_of_Digits/HyeonJeong.py ================================================ class Solution: # 짝수의 개수 찾는 문제 def findNumbers(self, nums: List[int]) -> int: return len([n for n in nums if len(str(n))%2 == 0]) ================================================ FILE: LeetCode/Math/Happy_Number/HyeonJeong.py ================================================ class Solution: def isHappy(self, n: int) -> bool: s = str(n) slist = [] while 1: c_sum = 0 for c in s: c_sum += int(c)*int(c) s = str(c_sum) if s in slist or s == '1': # 무한반복 중지 break slist += [s] if s == '1': return True return False ================================================ FILE: LeetCode/Math/Maximum_Product_of_Three_Numbers/HyeonJeong.java ================================================ package LeetCode.Math.Maximum_Product_of_Three_Numbers; import java.util.Arrays; class HyeonJeong { public int maximumProduct(int[] nums) { int result = 1; Arrays.sort(nums); // 배열을 오름차순으로 정렬 for (int i = nums.length-3; i str: num1 = num1[::-1] num2 = num2[::-1] # 최대값. 실제로는 이보다 작음. 넉넉히 잡음 arr = [[] for _ in range(len(num1) + len(num2))] for i in range(len(num1)): for j in range(len(num2)): num = int(num1[i]) * int(num2[j]) arr[i + j + 1].append(num // 10) arr[i + j].append(num % 10) ans = "" # sum을 해결하자. carry = 0 for s in arr: num = sum(s) + carry carry = num // 10 ans = str(num % 10) + ans pos = 0 # 마지막 0 제외. 앞에서 부터 0제외 while pos < len(ans) - 1 and ans[pos] == '0': pos += 1 return ans[pos:] ================================================ FILE: LeetCode/Math/Number_of_Steps_to_Reduce_a_Number_to_Zero/HyeonJeong.py ================================================ class Solution: def numberOfSteps(self, num: int) -> int: cnt = 0 # 단계 수 while (num != 0) : cnt += 1 if num % 2 == 0: num /= 2 continue num -= 1 return cnt ================================================ FILE: LeetCode/Math/Palindrome Number/6047198844.cpp ================================================ class Solution { public: bool isPalindrome(int x) { if(x<0) return false; string s = to_string(x); int start = 0; int end = s.size()-1; while(start<=end){ if(s[start]!=s[end]) break; start ++; end --; } return start > end; } }; ================================================ FILE: LeetCode/Math/Permutation Sequence/6047198844.py ================================================ class Solution: def getPermutation(self, n: int, k: int) -> str: s = map(str,range(1,n+1)) cnt = 1 for i in permutations(s): if k == cnt: return ''.join(i) cnt += 1 ================================================ FILE: LeetCode/Math/Pow(x,_n)/6047198844.py ================================================ class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 1 if n < 0: n = -n x = 1 / x #짝수? return self.myPow(x*x,n//2) if n % 2 == 0 else x*self.myPow(x*x,n//2) ================================================ FILE: LeetCode/Math/Power_of_Four/6047198844.py ================================================ class Solution: def isPowerOfFour(self, n: int) -> bool: i = 0 while n > (4 ** i): i += 1 return n == (4 ** i) ================================================ FILE: LeetCode/Math/Power_of_Three/HyeonJeong.py ================================================ class Solution: def isPowerOfThree(self, n: int) -> bool: if n == 0: return False while (n % 3) == 0: # 3으로 나눠지는 경우에만 계속 나눠서 1이 될때까지 n /= 3 if n == 1: return True return False ================================================ FILE: LeetCode/Math/Power_of_Two/6047198844.py ================================================ class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and 1 == format(n,'b').count('1') ================================================ FILE: LeetCode/Math/Powerful_Integers/HyeonJeong.py ================================================ class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: # x와 y가 주어졌을 때, bound와 작거나 같은 x**i + y**j의 결과를 리스트로 반환하는 문제 result = [] if bound < 2: return result if x > y: x,y = y,x m = 0 # y의 제곱수 if x == 1 and y == 1: return [2] elif x == 1: while (y**m + 1<= bound): result += [y**m+1] m += 1 return result n = 0 while (y**m <= bound): while (y**m + x**n <= bound): result += [y**m + x**n] n += 1 n = 0 m += 1 return set(result) ================================================ FILE: LeetCode/Math/Prime Arrangements/6047198844.py ================================================ class Solution: def numPrimeArrangements(self, n: int) -> int: # 소수 2개. 일반수 3개 2! * 3! # prime = [True for _ in range(n + 1)] prime[0] = False prime[1] = False for i in range(1, n + 1): if prime[i]: for j in range(i + i, n + 1, i): prime[j] = False cnt = math.factorial(prime.count(True)) * math.factorial(prime.count(False) - 1) return (cnt % (10 ** 9 + 7)) ================================================ FILE: LeetCode/Math/Reverse_Integer/6047198844.py ================================================ class Solution: def reverse(self, x: int) -> int: #부호값이 정해지지 않은 답. ans = int(str(abs(x))[::-1]) if ans == 0 or ans < -2**31 or ans > 2**31 - 1: return 0 return x // abs(x) * ans ================================================ FILE: LeetCode/Math/Reverse_Integer/HyeonJeong.py ================================================ class Solution: def reverse(self, x: int) -> int: if x < 0: # 주어진 수가 음수일 경우 -가 맨 앞에 작성될 수 있게 answer = '-' + str(x)[-1:0:-1] else: answer = str(x)[-1::-1] answer = int(answer) # 가장 앞에 오는 숫자가 0인 경우 0 제거 if -2**31 <= answer <= 2**31 - 1: #해당 범위의 수 이상인 경우는 0 반환 return answer return 0 ================================================ FILE: LeetCode/Math/Reverse_Integer/SeokBin.java ================================================ package Reverse_Integer; public class SeokBin { //정수 범위를 넘어가는 int 다루는 법 주의! public int reverse(int x) { //결과로 나갈 변수 int reversed = 0; //일의 자리를 뽑아낼 변수 int pop; while(x != 0) { pop = x % 10; //1의 자리를 뽑아내기 위해 % 사용!!! x /= 10; //이전값 * 10 하고 1의자리 채우기 // -2147483648 <= reversed <= 2147483647!! 일의 자리 비교조건 주의! if(reversed>Integer.MAX_VALUE/10 || reversed==Integer.MAX_VALUE/10 && pop > 7) { return 0; } if(reversed int: roman_code = {"I":"1", "V":"5", "X":"10", "L":"50", "C":"100", "D":"500", "M":"1000"} s = list(s) s = [int(roman_code[i]) for i in s] result = 0 print(s) i = 0 while i < len(s): if i+1 < len(s) and s[i] < s[i+1]: result += s[i+1] - s[i] i += 2 else: result += s[i] i += 1 return result #XLIX ================================================ FILE: LeetCode/Math/Rotate_Image/HyeonJeong.py ================================================ class Solution: def rotate(self, matrix: List[List[int]]) -> None: n = len(matrix[0]) copy_matrix = copy.deepcopy(matrix) for c in range(n): for r in range(n): matrix[r][c]= copy_matrix[n-c-1][r] ================================================ FILE: LeetCode/Math/Sqrt(x)/6047198844.cpp ================================================ class Solution { public: int mySqrt(int x) { if(x==0) return 0; long long begin = 1; long long end = (long long)x+1; int ans = 0; while(begin int: n = sqrt(x) if n != int(n): return floor(n) #제곱근이 정수가 아닐 경우는 내림 return int(n) ================================================ FILE: LeetCode/Math/String_to_Integer_(atoi)/6047198844.py ================================================ #lstrip #삼항연산자 #정규표현식 #join #findall함수 class Solution: def myAtoi(self, s: str) -> int: s = s.strip() s = re.findall('^[+\-]?\d+', s) print(s) print(''.join(s)) try: res = int(''.join(s)) MAX = 2147483647 MIN = -2147483648 if res > MAX: return MAX if res < MIN: return MIN return res except: return 0 ================================================ FILE: LeetCode/Math/Ugly Number/6047198844.py ================================================ class Solution: def isUgly(self, n: int) -> bool: if n <= 0: return False # 2로 나누기 while n % 2 == 0: n //= 2 # 3로 나누기 while n % 3 == 0: n //= 3 # 5로 나누기 while n % 5 == 0: n //= 5 return n == 1 ================================================ FILE: LeetCode/Math/Unique Binary Search Trees/6047198844.py ================================================ class Solution: def numTrees(self, n: int) -> int: memo = [0]*(n+1) memo[0] = memo[1] = 1 for i in range(2, n+1): for j in range(i): memo[i] += memo[j]*memo[i-j-1] return memo[n] ================================================ FILE: LeetCode/Math/Valid_Perfect_Square/6047198844.py ================================================ class Solution: def isPerfectSquare(self, num: int) -> bool: root = 1 while root**2 < num: root += 1 return root**2 == num ================================================ FILE: LeetCode/Math/Water_Bottles/6047198844.py ================================================ class Solution: def numWaterBottles(self, numBottles: int, numExchange: int) -> int: res = numBottles while numBottles // numExchange > 0: res += numBottles // numExchange numBottles = numBottles // numExchange + numBottles % numExchange return res ================================================ FILE: LeetCode/Queue/Design_Circular_Deque/HyeonJeong.py ================================================ from collections import deque class MyCircularDeque: # 순환 양방향 큐 구현을 설계 def __init__(self, k: int): self.q = deque() self.k = k def insertFront(self, value: int) -> bool: if self.isFull(): return False self.q.append(value) return True def insertLast(self, value: int) -> bool: if self.isFull(): return False self.q.appendleft(value) return True def deleteFront(self) -> bool: if self.isEmpty(): return False self.q.pop() return True def deleteLast(self) -> bool: if self.isEmpty(): return False self.q.popleft() return True def getFront(self) -> int: if self.isEmpty(): return -1 return self.q[len(self.q)-1] def getRear(self) -> int: if self.isEmpty(): return -1 return self.q[0] def isEmpty(self) -> bool: if len(self.q) == 0: return True return False def isFull(self) -> bool: if len(self.q) == self.k: return True return False ================================================ FILE: LeetCode/Queue/Number_of_Recent_Calls/HyeonJeong.py ================================================ from collections import deque class RecentCounter: # 최근 3000밀리 초 이내에 요청된 개수를 계산하는 클래스 def __init__(self): self.time = deque() def ping(self, t: int) -> int: self.time.append(t) # 인덱스 0이 항상 존재하게 됨 while t-3000 > self.time[0]: self.time.popleft() # 큐에서 처음 요소 제거 if len(self.time) == 0: return null return len(self.time) ================================================ FILE: LeetCode/Sliding_Window/Longest_Substring_Without_Repeating_Characters/JeongShin.js ================================================ /** * @param {string} s * @return {number} * 가장 긴 substring 을 중복 없이 구하는 문제 * s = "abcabcbb" 일 경우 * "abc" 3 을 반환해야 한다. * * s = "bbbb" 일 경우 * "b" 1 을 반환해야 한다. * * s = "pwwkew" 일 경우 * "wke" 3 을 반환해야 한다. "pwke" 는 subsequence 이지 substring 이 아니다. */ const lengthOfLongestSubstring = function (s) { let answer = 0; let window = []; let idx; for (const char of s) { if (!~(idx = window.indexOf(char))) { window.push(char); continue; } answer = Math.max(answer, window.length); window = window.splice(idx + 1); window.push(char); } answer = Math.max(answer, window.length); return answer; }; lengthOfLongestSubstring("ohvhjdml"); ================================================ FILE: LeetCode/Sliding_Window/Minimum_Window_Substring/6047198844.cpp ================================================ class Solution { public: string minWindow(string s, string t) { map reqAlphabet; for(char c : t) reqAlphabet[c]++; int startPointer = 0; int endPointer = 0; int n = s.size(); string resS = ""; while(startPointer!=n){ //현재 찾았는가 bool flag = true; for(auto it:reqAlphabet) if(it.second>0){ flag = false; break; } //t가 s에 포함되는 경우 if(flag){ int findSize = endPointer - startPointer; if(resS.size()==0||resS.size()>findSize) resS = string(s.begin()+startPointer,s.begin()+endPointer); if(reqAlphabet.find(s[startPointer])!=reqAlphabet.end()) reqAlphabet[s[startPointer]]++; startPointer++; } //t가 s에 포함되지 않는 경우 else{ //더 이상 확장이 안되는 경우 if(endPointer==n) return resS; if(reqAlphabet.find(s[endPointer])!=reqAlphabet.end()) reqAlphabet[s[endPointer]]--; endPointer++; } } return resS; } }; ================================================ FILE: LeetCode/Sliding_Window/Minimum_Window_Substring/JeongShin.js ================================================ /** * @param {string} s * @param {string} t * @return {string} */ const minWindow = function (s, t) { const map = Array.from(t).reduce((m, v) => { m[v] = (m[v] || 0) + 1; return m }, {}); let start = 0, end = 0, counter = t.length, minStart = 0, minLen = Infinity, len = s.length; while (end < len) { const char = s[end]; console.log(char, map); // 만약 char 가 t안에 있다면 counter 를 줄인다. counter -= (map[char] > 0); // map 에서 해당 char 의 개수를 줄여준다. if (map[char] !== undefined) map[char]--; end++; // 만약 t 의 모든 단어를 찾은 경우 // start 를 현재 len 범위 내에서 새로 찾는다 while (counter === 0) { const startChar = s[start]; if (end - start < minLen) { minStart = start; minLen = end - start; } if (map[startChar] !== undefined) map[startChar]++; counter += (map[startChar] > 0); start++; } } return minLen !== Infinity ? s.substring(minStart, minStart + minLen) : ''; }; console.log(minWindow("ADOBECODEBANC", "ABC")); ================================================ FILE: LeetCode/Sort/6047198844.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* sortList(ListNode* head) { vector arr; ListNode *tmp = head; while(tmp!=nullptr){ arr.push_back(tmp->val); tmp = tmp->next; } sort(arr.begin(),arr.end()); tmp = head; int cnt = 0; while(tmp!=nullptr){ tmp->val = arr[cnt++]; tmp = tmp-> next; } return head; } }; ================================================ FILE: LeetCode/Stack/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] if root: res.append(root.val) res += self.preorderTraversal(root.left) res += self.preorderTraversal(root.right) return res ================================================ FILE: LeetCode/Stack/Backspace-String-Compare/6047198844.cpp ================================================ class Solution { public: string makeString(string s){ string res; for(char c : s){ if(c=='#'){ if(!res.empty()) res.pop_back(); } else res.push_back(c); } return res; } bool backspaceCompare(string S, string T) { S = makeString(S) ; T = makeString(T) ; return S==T; } }; ================================================ FILE: LeetCode/Stack/Binary Tree Inorder Traversal/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] # root -> left -> right 순으로 순회한다. if root: res += self.inorderTraversal(root.left) res.append(root.val) res += self.inorderTraversal(root.right) return res ================================================ FILE: LeetCode/Stack/Binary Tree Postorder Traversal/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: res = [] if root: res += self.postorderTraversal(root.left) res += self.postorderTraversal(root.right) res.append(root.val) return res ================================================ FILE: LeetCode/Stack/Implement Stack using Queues/6047198844.py ================================================ class MyStack: def __init__(self): """ Initialize your data structure here. """ self.q = collections.deque() def push(self, x: int) -> None: """ Push element x onto stack. """ self.q.append(x) for _ in range(len(self.q) - 1): self.q.append(self.q.popleft()) return None def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ return self.q.popleft() def top(self) -> int: """ Get the top element. """ print(self.q) return self.q[0] def empty(self) -> bool: """ Returns whether the stack is empty. """ return not self.q # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty() ================================================ FILE: LeetCode/String/Complex_Number_Multiplication/HyeonJeong.py ================================================ class Solution: def complexNumberMultiply(self, a: str, b: str) -> str: cnt = a.find('+') x = [int(a[0:cnt]), int(a[cnt+1:-1])] cnt = b.find('+') y = [int(b[0:cnt]), int(b[cnt+1:-1])] n1 = x[0]*y[0] - x[1]*y[1] n2 = x[0]*y[1] + x[1]*y[0] answer = str(n1) + "+" + str(n2) + "i" return answer ================================================ FILE: LeetCode/String/Count_and_Say/6047198844.py ================================================ class Solution: def countAndSay(self, n: int) -> str: def say(cnt, s): if cnt == n + 1: return s res = "" if cnt == 1: res = "1" else: # 앞에서부터 count한다. cur = "" cur_cnt = 0 for char in s: if cur == char: cur_cnt += 1 else: if cur_cnt != 0: res += str(cur_cnt) + cur cur = char cur_cnt = 1 res += str(cur_cnt) + cur return say(cnt + 1, res) return say(1, "") ================================================ FILE: LeetCode/String/Defanging_an_IP_Address/6047198844.py ================================================ class Solution: def defangIPaddr(self, address: str) -> str: return address.replace(".","[.]") ================================================ FILE: LeetCode/String/Generate_Parentheses/6047198844.py ================================================ import itertools class Solution: def generateParenthesis(self, n: int) -> List[str]: answer = [] candidate = itertools.product([")","("],repeat=n) def is_valid(element): stack = [] for parentheses in element: if parentheses == '(': stack.append('(') else: if stack: stack.pop() else: return False if stack: return False return True for j in itertools.product(candidate,repeat=2): k, l = j element = ''.join(k+l) if is_valid(element): answer.append(element) return answer ================================================ FILE: LeetCode/String/Group_Anagrams/JeongShin.js ================================================ /** * @param {string[]} strings * @return {string[][]} */ const groupAnagrams = function (strings) { const answer = []; const map = new Map(); const charOffSet = "a".charCodeAt(0); for (const string of strings) { const charCount = new Array(26).fill(0); for (const char of string) charCount[char.charCodeAt(0) - charOffSet]++; const val = charCount.join(","); let index; // index 가 0 인 경우 고려하여 undefined 와 비교 if ((index = map.get(val)) !== undefined) { answer[index].push(string); continue; } map.set(val, index = answer.length); answer[index] = [string]; } return answer; }; ================================================ FILE: LeetCode/String/Implement_strStr()/6047198844.py ================================================ class Solution: def strStr(self, haystack: str, needle: str) -> int: return haystack.find(needle) ================================================ FILE: LeetCode/String/Implement_strStr()/HyeonJeong.py ================================================ class Solution: def strStr(self, haystack: str, needle: str) -> int: if needle == '': return 0 elif needle in haystack: return haystack.index(needle) else: return -1 ================================================ FILE: LeetCode/String/Length_of_Last_Word/6047198844.py ================================================ class Solution: def lengthOfLastWord(self, s: str) -> int: return len(s.split(' ')[-1]) ================================================ FILE: LeetCode/String/Length_of_Last_Word/HyeonJeong.py ================================================ class Solution: def lengthOfLastWord(self, s: str) -> int: slist = list(s.rstrip()) slist.reverse() answer = 0 for c in slist: if c != ' ': answer += 1 else: return answer return answer ================================================ FILE: LeetCode/String/Letter_Combinations_of_a_Phone_Number/6047198844.py ================================================ class Solution: def letterCombinations(self, digits: str) -> List[str]: phone_table = { "2" : "abc", "3" : "def", "4" : "ghi", "5" : "jkl", "6" : "mno", "7" : "pqrs", "8" : "tuv", "9" : "wxyz" } res = [] #틀림 N = len(digits) if N == 0: return res res.append("") #digit를 모든 res에 붙인다. for digit in digits: res_n = len(res) for _ in range(res_n): tmp = res.pop(0) for alpha in phone_table[digit]: res.append(tmp+alpha) return res ================================================ FILE: LeetCode/String/Letter_Combinations_of_a_Phone_Number/HyeonJeong.py ================================================ class Solution: def letterCombinations(self, digits: str) -> List[str]: length = len(digits) if length == 0: return [] answer = [] s = "" slist = [] for c in digits: if int(c) < 7: for i in range(3): s += chr(97+ i+ 3*(int(c)-2)) elif c == '7': for n in 'pqrs': s += n elif c == '8': for n in 'tuv': s += n elif c == '9': for n in 'wxyz': s += n slist += [s] s = "" for c1 in slist[0]: if length == 1: answer += [c1] else: for c2 in slist[1]: if length == 2: answer += [c1+c2] else: for c3 in slist[2]: if length == 3: answer += [c1+c2+c3] else: for c4 in slist[3]: answer += [c1+c2+c3+c4] return answer ================================================ FILE: LeetCode/String/Longest Valid Parentheses/6047198844.py ================================================ class Solution: def longestValidParentheses(self, s: str) -> int: N = len(s) if N <= 1: return 0 longest = [0] * N # dp 사용 # longest[idx]에는 s[idx]로 끝나는 Longest Valid Parentheses중 가장 긴 길이가 저장된다. for idx in range(1, N): # '('로 끝나는 Valid Parentheses는 없다. if s[idx] == '(': longest[idx] = 0 else: # ')'로 끝나는 Valid Parentheses가 되려면. 직전 Longest Valid Parentheses의 앞 괄호가 '('이여야한다. if idx - 1 - longest[idx - 1] >= 0 and s[idx - 1 - longest[idx - 1]] == '(': # '(' + Longest Valid Parentheses길이 + ')' longest[idx] = 1 + longest[idx - 1] + 1 # 범위가 된다면, 바로 직전의 Longest Valid Parentheses도 더해준다. if idx - 1 - longest[idx - 1] - 1 >= 0: longest[idx] += longest[idx - 1 - longest[idx - 1] - 1] return max(longest) ================================================ FILE: LeetCode/String/Longest_Common_Prefix/6047198844.cpp ================================================ class Solution { public: string longestCommonPrefix(vector& strs) { int minSize = 0; for(int i = 0; i < strs.size(); i++) if(!minSize||minSize < strs[i].size()) minSize = strs[i].size(); for(int j = 0; j < minSize; j++){ for(int i = 1; i < strs.size(); i++){ if(strs[0][j] != strs[i][j]) return strs[0].substr(0,j); } } return strs.size() ? strs[0] : ""; } }; ================================================ FILE: LeetCode/String/Longest_Palindrome/HyeonJeong.py ================================================ class Solution: def longestPalindrome(self, s: str) -> int: alpha = list(set(list(s))) # 사용되는 알파벳 종류 if len(alpha) == 1: return len(s) num = 0 odd = 0 for n in alpha: cnt = s.count(n) if cnt%2 == 0: num += cnt else: num += cnt-1 # 홀수도 최대한 많은 알파벳 이용 odd = 1 return num + odd ================================================ FILE: LeetCode/String/Longest_Substring_Without_Repeating_Characters/HyeonJoeng.py ================================================ class Solution: def lengthOfLongestSubstring(self, s: str) -> int: slist = [] for x in range(len(s)): #문자의 시작점 설정 word = "" n = x while 1: if n < len(s) and s[n] not in word: #문자열에서 다른 문자인 경우는 누적 word += s[n] n += 1 else: slist.append(len(word)) #이미 담긴 문자인 경우는 길이를 배열에 담고 while문 종료 break return 0 if slist == [] else max(slist) ================================================ FILE: LeetCode/String/Make_The_String_Great/HyeonJeong.py ================================================ class Solution: def makeGood(self, s: str) -> str: result = [c for c in s] i = 0 while i < len(result)-1: if ord(result[i])-32 == ord(result[i+1]) or ord(result[i]) == ord(result[i+1])-32: # 연속된 인덱스에 같은 알파벳의 대문자와 소문자인 경우 result.pop(i+1) result.pop(i) if i != 0: i -= 1 else: i += 1 return "".join(result) ================================================ FILE: LeetCode/String/Maximum_69_Number/HyeonJeong.py ================================================ class Solution: def maximum69Number (self, num: int) -> int: s = str(num) for i, n in enumerate(str(num)): if n == '6': return s[:i] + '9' + s[i+1:] return s ================================================ FILE: LeetCode/String/Number of Strings That Appear as Substrings in Word/6047198844.py ================================================ class Solution: def numOfStrings(self, patterns: List[str], word: str) -> int: res = 0 for pattern in patterns: res += int(word.count(pattern) > 0) return res ================================================ FILE: LeetCode/String/Palindromic_Substrings/이준수.py ================================================ import urllib.request from functools import lru_cache @lru_cache(None) def is_palindromic(s: str) -> bool: if len(s) <= 1: return True if s[0] != s[-1]: return False return is_palindromic(s[1:len(s) - 1]) class Solution: def countSubstrings(self, s: str) -> int: res = 0 for substr_len in range(1, len(s) + 1): for idx in range(0, len(s) - substr_len + 1): if is_palindromic(s[idx:idx + substr_len]): res += 1 return res ================================================ FILE: LeetCode/String/Ransom_Note/HyeonJeong.java ================================================ package LeetCode.String.Ransom_Note; class HyeonJeong { public boolean canConstruct(String ransomNote, String magazine) { char[] n = ransomNote.toCharArray(); char[] m = magazine.toCharArray(); int state; for (int i = 0; i < ransomNote.length(); i++) { state = 0; for (int j = 0; j < magazine.length(); j++) { if (n[i] == m[j]) { m[j] = ' '; state = 1; break; } } if(state == 0) return false; } return true; } } ================================================ FILE: LeetCode/String/Rearrange_Words_in_a_Sentence/HyeonJeong.py ================================================ class Solution: def arrangeWords(self, text: str) -> str: slist = text.split(' ') slist[0] = slist[0][0].lower() + slist[0][1:] # 문장의 첫번째 글자를 소문자로 바꿈 slist.sort(key = lambda s: len(s)) slist[0] = slist[0][0].upper() + slist[0][1:] # 문장의 첫번째 글자를 대문자로 바꿈 return ' '.join(slist) ================================================ FILE: LeetCode/String/Regular_Expression_Matching/6047198844.py ================================================ class Solution: def isMatch(self, s: str, p: str) -> bool: memo = [[None for i in range(len(p) + 1)] for j in range(len(s) + 1)] def matching(s, p) -> bool: m = len(s) n = len(p) if memo[m][n] != None: return memo[m][n] if not s: if not p: memo[m][n] = True return memo[m][n] elif len(p) > 1 and p[1] == '*': # *를 무시한다. memo[m][n] = matching(s, p[2:]) return memo[m][n] else: # p를 줄일수없다. memo[m][n] = False return memo[m][n] elif not p: # s는 있는데 p가 없으면 False memo[m][n] = False return memo[m][n] if p[0] == '.' or s[0] == p[0]: # 앞자리가 같은 경우 if len(p) > 1 and p[1] == '*': # *를 한번 더 쓰는 경우. *를 쓰는 경우, *를 무시하는 경우 memo[m][n] = matching(s[1:], p) or matching(s[1:], p[2:]) or matching(s, p[2:]) return memo[m][n] else: # 이외의 경우는 무시할수없다. memo[m][n] = matching(s[1:], p[1:]) return memo[m][n] elif len(p) > 1 and p[1] == '*': # 같지 않은 경우. *를 무시할수있다. memo[m][n] = matching(s, p[2:]) return memo[m][n] else: # 방법이없다. memo[m][n] = 0 return memo[m][n] return matching(s, p) ================================================ FILE: LeetCode/String/Restore IP Addresses/6047198844.py ================================================ class Solution: def restoreIpAddresses(self, s: str) -> List[str]: # IP길이가 4개~12개사이여야한다. if not (4 <= len(s) <= 12): return [] res = [] for i in product([1, 2, 3], repeat=4): if sum(i) == len(s): IP = '' pointer = 0 for j in i: k = s[pointer:pointer + j] if 0 <= int(k) <= 255: IP += '.' + str(int(k)) pointer += j else: break else: if len(IP) == len(s) + 4: res.append(IP[1:]) return res ================================================ FILE: LeetCode/String/Reverse_String/HyeonJeong.java ================================================ package LeetCode.String.Reverse_String; class HyeonJeong { public void reverseString(char[] s) { int len = s.length; char tmp; for (int i = 0; i < len/2; i++) { tmp = s[i]; s[i] = s[len-(i+1)]; s[len-(i+1)] = tmp; } } } ================================================ FILE: LeetCode/String/Robot Return to Origin/6047198844.py ================================================ class Solution: def judgeCircle(self, moves: str) -> bool: x, y = 0, 0 for move in moves: if move == 'R': x += 1 elif move == 'L': x -= 1 elif move == 'U': y -= 1 else: y += 1 return x == 0 and y == 0 ================================================ FILE: LeetCode/String/Roman_to_Integer/HyeonJoeng.py ================================================ class Solution: def romanToInt(self, s: str) -> int: answer = 0 d = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} i = 0 length = len(s) while i < length: if i+1 < length and d[s[i]] < d[s[i+1]]: answer += d[s[i+1]]- d[s[i]] i += 2 else: answer += d[s[i]] i += 1 return answer ================================================ FILE: LeetCode/String/Rotate String/6047198844.py ================================================ class Solution: def rotateString(self, s: str, goal: str) -> bool: s = deque(s) for _ in range(len(s)-1): tmp = ''.join(s) if tmp == goal: return True s.rotate(1) return False ================================================ FILE: LeetCode/String/Simplify Path/6047198844.py ================================================ class Solution: def simplifyPath(self, path: str) -> str: stack = [] for directory in path.split('/'): # / 로 나눠보자 #..일경우 상위 directory으로 올라간다. 상위 directory는 ..으로 표현된다. if directory == '..': if stack: stack.pop() elif directory and directory != '.': stack.append(directory) return '/' + '/'.join(stack) ================================================ FILE: LeetCode/String/String_to_Integer_(atoi)/6047198844.py ================================================ class Solution: def myAtoi(self, s: str) -> int: s = s.lstrip() if not s: return 0 sign = "" if s[0] == "-" or s[0] == "+": sign = s[0] s = s[1:] res = sign + "0" for n in s: if n.isdigit(): res += n else: break res = int(res) min_value = -2 ** 31 max_value = 2 ** 31 - 1 if res < min_value: return min_value if res > max_value: return max_value return res ================================================ FILE: LeetCode/String/Thousand Separator/6047198844.py ================================================ class Solution: def thousandSeparator(self, n: int) -> str: n = str(n) res = list() for i in range(len(n),0,-3): if i - 3 >= 0: res.append(n[i-3:i]) else: res.append(n[0:i]) return ".".join(res[::-1]) ================================================ FILE: LeetCode/String/To_Lower_Case/HyeonJeong.java ================================================ package LeetCode.String.To_Lower_Case; class HyeonJeong { public String toLowerCase(String str) { return str.toLowerCase(); // 문자열을 모두 소문자로 변경시켜 반환 /* StringBuffer sb = new StringBuffer(); int n; for (int i = 0; i < str.length(); i++) { n = str.charAt(i); if (65 <= n && n <= 90) // 대문자인 경우 sb.append((char)(n + 32)); else sb.append((char)n); } String s = new String(sb); return s; */ } } ================================================ FILE: LeetCode/String/Valid_Parentheses/6047198844.py ================================================ class Solution: def isValid(self, s: str) -> bool: stack = [] dict = {')':'(', ']':'[', '}':'{'} for char in s: if char in dict.values(): stack.append(char) else: if not stack: return False if stack.pop()!=dict[char]: return False return not stack ================================================ FILE: LeetCode/String/Valid_Parentheses/HyeonJeong.py ================================================ class Solution: def isValid(self, s: str) -> bool: slist = [] for i, c in enumerate(s): if c in '({[': slist.append(c) else: if len(slist) < 1: return False elif ')' == c and '(' == slist[-1]: slist.pop() elif ']' == c and '[' == slist[-1]: slist.pop() elif '}' == c and '{' == slist[-1]: slist.pop() else: return False if slist == []: return True return False ================================================ FILE: LeetCode/String/ZigZag_Conversion/6047198844.py ================================================ class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s board =[[] for _ in range(numRows)] step = numRows - 1 cur_row = 0 cur_col = 0 #s.length, numRows -> 최대 1000 이므로 브루트포스 for char in s: #일직선 if cur_col % step == 0: board[cur_row].append(char) cur_row += 1 if cur_row == step: cur_col += 1 #우상으로 else: cur_row -= 1 cur_col += 1 board[cur_row].append(char) print(board) ================================================ FILE: LeetCode/String/ZigZag_Conversion/HyeonJeong.py ================================================ class Solution: def convert(self, s: str, numRows: int) -> str: nlist = [] alist = [] for i in range(numRows): nlist += [i] alist += [[]] number = nlist + sorted(nlist, reverse=True)[1:-1] # numRows에 따라 인덱스 순서의 반복 구간이 number에 리스트로 담김 n = 0 i = 0 while 1: alist[number[i]] += s[n] # 해당하는 리스트 위치에 주어진 s를 넣음 n += 1 i += 1 if i == len(number): # 반복 구간을 반복될 수 있게 함 i = 0 if n == len(s): # s의 길이만큼 s의 문자들이 들어갈 수 있게 함 break answer = [] for s in alist: answer += s # 지그재그로 정리된 문자들이 answer에 담기게 됨 return ''.join(answer) ================================================ FILE: LeetCode/String/ZigZag_Conversion/Seokbin.java ================================================ package LeetCode.String.ZigZag_Conversion; public class Seokbin { public String convert(String s, int numRows) { char[] chars = s.toCharArray(); int idx = 0; // StringBuffer sb = new StringBuffer(numRows); // 스트링버퍼 배열로 선언!! StringBuffer[] sb = new StringBuffer[numRows]; // 배열에 스트링 버퍼 각각 저장 for (int i = 0; i < numRows; i++) { sb[i] = new StringBuffer(); } while (idx < s.length()) { // 수직으로 내려갈 때 for (int i = 0; i < numRows && idx < s.length(); i++) { sb[i].append(chars[idx++]); } // 대각선으로 올라갈 때 for (int i = numRows - 2; i > 0 && idx < s.length(); i--) { sb[i].append(chars[idx++]); } } //스트링 버퍼 합치기 for (int i = 1; i < numRows; i++) { sb[0].append(sb[i]); } String answer = new String(sb[0]); return answer; } } ================================================ FILE: LeetCode/Tree/Balanced_Binary_Tree/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isBalanced(self, root: TreeNode) -> bool: def check(root): if not root: return 0 left = check(root.left) right = check(root.right) if left == -1 or right == -1 or abs(left-right) > 1: return -1 return 1 + max(left, right) return check(root) != -1 ================================================ FILE: LeetCode/Tree/Binary_Search_Tree_to_Greater_Sum_Tree/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: acc: int = 0 def bstToGst(self, root: TreeNode) -> TreeNode: #현재노드의 부모와 부모오른쪽의 합, 현재노드 if root: self.bstToGst(root.right) self.acc += root.val root.val = self.acc self.bstToGst(root.left) return root ================================================ FILE: LeetCode/Tree/Binary_Tree_Paths/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: vector res; public: void TreePaths(TreeNode* root, string &paths){ if(root==NULL) return; string temp = paths; if(root->left==NULL&&root->right==NULL){ paths += to_string(root->val); res.push_back(paths); paths = temp; return; } paths += to_string(root->val)+"->"; TreePaths(root->left, paths); TreePaths(root->right, paths); paths = temp; } vector binaryTreePaths(TreeNode* root) { string paths = ""; TreePaths(root,paths); return res; } }; ================================================ FILE: LeetCode/Tree/Convert Sorted Array to Binary Search Tree/6047198844.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode toBST(TreeNode root, int[] nums, int start, int end){ if(start>end) return null; int mid = (start+end)/2; root = new TreeNode(nums[mid]); root.left = toBST(root.left,nums,start,mid-1); root.right = toBST(root.right,nums,mid+1,end); return root; } public TreeNode sortedArrayToBST(int[] nums) { return toBST(null,nums,0,nums.length-1); } } ================================================ FILE: LeetCode/Tree/Convert Sorted Array to Binary Search Tree/6047198844.py ================================================ Convert Sorted Array to B# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None mid = len(nums)//2 root = TreeNode(nums[mid]) root.left = self.sortedArrayToBST(nums[:mid]) root.right = self.sortedArrayToBST(nums[mid+1:]) return root inary Search Tree ================================================ FILE: LeetCode/Tree/Diameter_of_Binary_Tree/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: longest: int = 0 def diameterOfBinaryTree(self, root: TreeNode) -> int: #상태를 반환한다. 상태란 현재노드에서 리프노드까지의 거리이다. #거리는 간선의 개수를 뜻한다. def dfs(root): #이 부분이 매우 중요하다. 리프노드의 경우 상태로 0. 거리로 0을 가져야한다. if not root: return -1 #left의 상태와 right의 상태를 얻는다. left = dfs(root.left) right = dfs(root.right) self.longest = max(self.longest, 2 + left + right) return 1 + max(left, right) dfs(root) return self.longest ================================================ FILE: LeetCode/Tree/Find_Bottom_Left_Tree_Value/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int findBottomLeftValue(TreeNode* root) { int leftmost; //Queue에 넣는다. BFS queue q; q.push(root); while(!q.empty()){ TreeNode* temp = q.front(); q.pop(); leftmost = temp->val; if(temp->right) q.push(temp->right); if(temp->left) q.push(temp->left); } return leftmost; } }; //10000 ================================================ FILE: LeetCode/Tree/Find_Bottom_Left_Tree_Value/val ================================================ ================================================ FILE: LeetCode/Tree/Increasing_Order_Search_Tree/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: vector res; public: void makeTree(TreeNode* root){ if(root==NULL) return; makeTree(root->left); res.push_back(root->val); makeTree(root->right); return; } TreeNode* increasingBST(TreeNode* root) { makeTree(root); TreeNode* r = new TreeNode(res[0]); TreeNode* temp = r; for(int i = 1 ; i < res.size(); i++){ temp->right = new TreeNode(res[i]); temp = temp->right; } return r; } }; ================================================ FILE: LeetCode/Tree/Invert_Binary_Tree/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def invertTree(self, root: TreeNode) -> TreeNode: Q = collections.deque([root]) while Q: node = Q.popleft() if node: node.left, node.right = node.right, node.left Q.append(node.left) Q.append(node.right) return root ================================================ FILE: LeetCode/Tree/Leaf-Similar_Trees/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void leaf(TreeNode* root,vector&res){ if(root==NULL) return; if(root->left==NULL&&root->right==NULL){ res.push_back(root->val); return; } leaf(root->left,res); leaf(root->right,res); } bool leafSimilar(TreeNode* root1, TreeNode* root2) { vector left; vector right; leaf(root1,left); leaf(root2,right); if(left.size()!=right.size()) return false; return equal(left.begin(),left.end(),right.begin()); } }; ================================================ FILE: LeetCode/Tree/Longest_Univalue_Path/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: longest: int = 0 def longestUnivaluePath(self, root: TreeNode) -> int: #상태를 반환한다. #상태란 univalue를 가진 리프까지의 거리이다. def dfs(root): if not root: return -1 left = dfs(root.left) right = dfs(root.right) if root.left and root.left.val == root.val: left += 1 else: left = 0 if root.right and root.right.val == root.val: right += 1 else: right = 0 self.longest = max(self.longest, left + right) return max(left, right) dfs(root) return self.longest ================================================ FILE: LeetCode/Tree/Maximum_Depth_of_Binary_Tree/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) ================================================ FILE: LeetCode/Tree/Merge_Two_Binary_Trees/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: if not root1 and not root2: return None if not root1: return root2 if not root2: return root1 root = TreeNode(root1.val+root2.val) root.left = self.mergeTrees(root1.left, root2.left) root.right = self.mergeTrees(root1.right, root2.right) return root ================================================ FILE: LeetCode/Tree/Minimum_Height_Trees/6047198844.py ================================================ class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: #예외처리 if n <= 1: return [0] #graph를 만든다. graph = defaultdict(deque) for u, v in edges: graph[u].append(v) graph[v].append(u) #하나만 연결되있으면 leaf이다. leaves = [] for i in range(n+1): if len(graph[i]) == 1: leaves.append(i) #leaves의 길이가 2이하일때까지 leaf들을 다 때낸다. while n > 2: n -= len(leaves) new_leaves = [] for leaf in leaves: #leaf를 때낸다. leaf와 연결된 이웃을 없애고 자신도 없앤다. neighbor = graph[leaf].popleft() graph[neighbor].remove(leaf) #때낸후 이웃도 leaf가 될수있다. if len(graph[neighbor]) == 1: new_leaves.append(neighbor) leaves = new_leaves return leaves ================================================ FILE: LeetCode/Tree/Path_Sum/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool hasPathSum(TreeNode* root, int targetSum) { if(root==NULL) return false; int _ = targetSum-root->val; if(root->left==NULL&&root->right==NULL) return !(_); return hasPathSum(root->left,_)||hasPathSum(root->right,_); } }; ================================================ FILE: LeetCode/Tree/Path_Sum_II/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: vector> res; public: void pSum(TreeNode*root, int targetSum,vector&temp){ if(root==NULL) return; temp.push_back(root->val); if(root->left==NULL&&root->right==NULL&&targetSum==root->val) res.push_back(temp); pSum(root->left,targetSum-root->val,temp); pSum(root->right,targetSum-root->val,temp); temp.pop_back(); } vector> pathSum(TreeNode* root, int targetSum) { vector temp; pSum(root, targetSum, temp); return res; } }; ================================================ FILE: LeetCode/Tree/Path_Sum_III/JeongShin.js ================================================ /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {number[]} root * @param {number} sum * @return {number} */ const pathSum = function (root, sum) { const memo = { 0: 1 }; const self = this; self.answer = 0; dfs.call(self, root, sum, 0, memo); return self.answer; }; function dfs(node, target, currSum, memo) { if (!node) return; currSum += node.val; this.answer += (memo[currSum - target] || 0); memo[currSum] = (memo[currSum] || 0) + 1; dfs.call(this, node.left, target, currSum, memo); dfs.call(this, node.right, target, currSum, memo); memo[currSum]--; } ================================================ FILE: LeetCode/Tree/Same Tree/6047198844.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if((p==NULL)^(q==NULL)) return false; if(p==NULL&&q==NULL) return true; if(!isSameTree(p->left,q->left)) return false; if(p->val!=q->val) return false; if(!isSameTree(p->right,q->right)) return false; return true; } }; ================================================ FILE: LeetCode/Tree/Serialize_and_Deserialize_Binary_Tree/6047198844.py ================================================ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ res = "" Q = collections.deque([root]) while Q: node = Q.popleft() if not node: res += "N " else: res += str(node.val)+" " Q.append(node.left) Q.append(node.right) return res def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ data = data.split() if data[0] == 'N': return None root = TreeNode(int(data[0])) Q = collections.deque([root]) idx = 1 while Q: node = Q.popleft() if data[idx] != 'N': node.left = TreeNode(int(data[idx])) Q.append(node.left) idx += 1 if data[idx] != 'N': node.right = TreeNode(int(data[idx])) Q.append(node.right) idx += 1 return root # Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # ans = deser.deserialize(ser.serialize(root)) ================================================ FILE: LeetCode/Tree/Unique_Binary_Search_Trees/JeongShin.js ================================================ /** * Catalan Number 을 구하는 문제 * @param {number} n * @return {number} */ const numTrees = function (n) { const dp = new Array(n + 1).fill(0); dp[0] = 1; for (let i = 1; i <= n; i++) for (let j = 1; j <= i; j++) // F (i, n) = G (i-1) * G (n-i) dp[i] += dp[j - 1] * dp[i - j]; return dp[n]; }; numTrees(3); ================================================ FILE: LeetCode/Trie/Design_Add_and_Search_Words_Data_Structure/JeongShin.js ================================================ class Node { constructor(key) { this.key = key; this.children = new Map(); this.isEnd = false; } } const WordDictionary = class { constructor() { this.root = new Node(null); }; /** * @param {string} word * @return {void} */ addWord(word) { const len = word.length; let node = this.root; for (let i = 0; i < len; i++) { const curr = word[i]; if (!node.children.has(curr)) node.children.set(curr, new Node(curr)); node = node.children.get(curr); } node.isEnd = true; }; /** * 단어가 Trie 에 포함 되어 있는지 판단. '.'으로 모든 단어 대체 가능 * @param {string} word * @return {boolean} */ search(word) { return find(word, 0, this.root, word.length); }; }; /* * Backtracking * @param {string} word * @param {number} idx * @param {Node} node * */ function find(word, idx, node) { if (idx === word.length) { return node.isEnd; } const curr = word[idx]; if (curr === '.' && [...node.children.values()].find(child => find(word, idx + 1, child))) return true; // if (curr === '.') // for (let child of node.children.values()) // if (find(word, idx + 1, child)) if (!node.children.has(curr)) return false; return find(word, idx + 1, node.children.get(curr)); } ================================================ FILE: LeetCode/Trie/Palindrome_Pairs/JeongShin.js ================================================ const isPalindrome = function (word, start, end) { while (start < end) { if (word[start++] !== word[end--]) return false; } return true; }; /* * index : word 에서의 index 를 가집니다. 단어의 끝에는 양수의 words 에서의 word 인덱스를 가집니다. * children : trie 자료구조에서 자식 노드. * palindromeList : 단어 처음 ~ 현재 까지 palindrome 리스트. * */ class Node { constructor(key) { this.key = key; this.index = -1; this.children = new Map(); this.palindromeList = []; } } class Trie { constructor() { this.root = new Node(null); } // trie 에 word 를 삽입 합니다. 이때 단어가 역순으로 삽입 됩니다. addWord(word, idx, node = this.root) { const len = word.length; for (let i = len - 1; i >= 0; i--) { const char = word[i]; if (!node.children.has(char)) node.children.set(char, new Node(char)); // 0 ~ i 까지의 substring 이 palindrome 에 해당되는지 확인 합니다. i/2 의 cost가 발생 합니다. // ex) 'sssll' 을 저장할 때 'llsss' 의 순서대로 삽입 되는데 'sss' 부분은 항상 palindrome 을 만족하기 때문에 // 'll' 으로 시작하는 모든 단어들은 pair 가 가능합니다. 따라서 'll'과 같이 단어 prefix 가 일치 하는 단어들의 pair 를 찾아주기 위해 리스트 형태로 저장해 둡니다. if (isPalindrome(word, 0, i)) node.palindromeList.push(idx); node = node.children.get(char); } node.palindromeList.push(idx); node.index = idx; } // 현재 단어 word 와 words 에서의 idx 를 기준으로 palindrome 을 만들 수 있는 pair 를 찾습니다. findPair(word, idx, answer, node = this.root) { const len = word.length; for (let i = 0; i < len; i++) { // 현재 탐색중인 노드가 words 에 존재 하는 단어이고 && 현재 고려중인 단어가 아니고 && i ~ 단어 끝까지 palindrome 에 해당되는지 검사합니다. // 단어가 역순으로 저장되어 있기 때문에 앞으로 오는 단어가 모두 palindrome 을 만족해야 합니다. // ex) 'sssll' 이 's' 를 탐색할 때 's' 이후에 substring 'ssll' 이 palindrome 이 따져봐야 합니다. if (node.index >= 0 && node.index !== idx && isPalindrome(word, i, word.length - 1)) answer.push([idx, node.index]); node = node.children.get(word[i]); if (!node) return; } // 현재 단어를 끝까지 탐색하고 나서도 palindrome 을 만들 수 있는 경우 // ex) 현재 단어 'lls' 의 경우 이전에 palindromeList 에 저장해주었던 'sssll' 과 같이 prefix 가 일치하는 단어를 찾아 push 해줍니다. answer.push(...node.palindromeList.filter(pairIdx => idx !== pairIdx).map((pairIdx) => [idx, pairIdx])); } } /** * @param {string[]} words * @return {number[][]} */ const palindromePairs = function (words) { const len = words.length; const trie = new Trie(); const answer = []; for (let i = 0; i < len; i++) trie.addWord(words[i], i); for (let i = 0; i < len; i++) trie.findPair(words[i], i, answer); return answer; }; palindromePairs(["bat", "tab", "cat"]); palindromePairs(["abcd", "dcba", "lls", "s", "sssll"]); palindromePairs(["aaa", ""]); ================================================ FILE: LeetCode/Trie/Palindrome_Pairs/eyabc.js ================================================ /** * https://leetcode.com/problems/palindrome-pairs/ * @param words 단어들의 유니크한 배열 * @return 두 words[i] + words[j]의 연결이 회문이되도록 주어진 목록에서 고유 한 색인 (i, j)의 모든 쌍을 반환합니다. * 성능 개선을 위해 Trie 알고리즘 공부 * https://brunch.co.kr/@springboot/75 * https://www.youtube.com/watch?v=7e1b70dTAd4 */ /* * https://www.youtube.com/watch?v=9nqiphzFbFc * 2968 ms 52 MB */ // 두 단어를 합쳤을 때 회귀문이 되는지 판별 한다. const recursion = (word1, word2) => { const combined = word1 + word2; const combinedLen = combined.length; let a = 0; let b = combinedLen - 1; while (a < b) { if (combined.charAt(a) !== combined.charAt(b)) return false; a += 1; b -= 1; } return true; }; const palindromePairs0 = function(words) { const len = words.length; return words.reduce((result, word1, i) => { for (let j = i + 1 ; j < len ; j++) { const word2 = words[j]; if (recursion(word1, word2)) result.push([i, j]); if (recursion(word2, word1)) result.push([j, i]); } return result; }); }; // 시간 초과 const palindromePairs2 = function(words) { const result = []; words.forEach((word1, i) => { words.forEach((word2, j) => { if (i === j) return; const combined = word1 + word2; const combinedLen = combined.length; if (combinedLen === 1) { result.push([i, j]); return; } const isEven = (combinedLen % 2) === 0; let first, second; let middle = combinedLen / 2; if (isEven) { first = combined.slice(0, middle); second = [...combined.slice(middle, combinedLen)].reverse().join(''); } else { middle = ~~middle; first = combined.slice(0, middle); second = [...combined.slice(middle + 1, combinedLen)].reverse().join(''); } if (first === second) result.push([i, j]); }); }); return result; }; // 시간 초과 const palindromePairs3 = function(words) { const result = []; const recursion = (word1, word2, i, j) => { const combined = word1 + word2; const combinedLen = combined.length; if (combinedLen === 1) { result.push([i, j]); return; } const isEven = (combinedLen % 2) === 0; let first, second; let middle = combinedLen / 2; if (isEven) { first = combined.slice(0, middle); second = [...combined.slice(middle, combinedLen)].reverse().join(''); } else { middle = ~~middle; first = combined.slice(0, middle); second = [...combined.slice(middle + 1, combinedLen)].reverse().join(''); } if (first === second) result.push([i, j]); }; words.forEach((word1, i) => { for (let j = i + 1 ; j < words.length ; j++) { const word2 = words[j]; recursion(word1, word2, i, j); recursion(word2, word1, j, i); } }); return result; }; // https://www.youtube.com/watch?v=7e1b70dTAd4 class Trie { head = {}; add(word) { let currNode = this.head; for (const char of word) { currNode[char] = currNode[char] || {}; currNode = currNode[char]; } currNode['*'] = true; } search(word) { let currNode = this.head; for (const char of word) { if (currNode[char] === undefined) { return false; } currNode = currNode[char]; } return !!currNode['*']; } } console.log(palindromePairs(['abcd', 'dcba', 'lls', 's', 'sssll']) === [[0, 1], [1, 0], [3, 2], [2, 4]]); // console.log(palindromePairs(['bat', 'tab', 'cat']) === [[0, 1], [1, 0]]); // console.log(palindromePairs(['a', '']) === [[0, 1], [1, 0]]); // console.log(palindromePairs(['a', 'abc', 'aba', '']) === [[0, 3], [3, 0], [2, 3], [3, 2]]); ================================================ FILE: LeetCode/Trie/Replace_Words/JeongShin.js ================================================ class Node { constructor(key) { this.key = key; this.children = new Map(); this.isEnd = false; } } class Trie { constructor() { this.root = new Node(null); } addWord(word, node = this.root) { for (const char of word) { if (!node.children.has(char)) { node.children.set(char, new Node(char)) } node = node.children.get(char); } node.isEnd = true; } findAndReplaceWord(word, node = this.root) { let path = ''; for (const char of word) { if (!node.children.has(char)) return word; node = node.children.get(char); path += char; if (node.isEnd) return path; } return word; } } const replaceWords = function (dictionary, sentence) { const trie = new Trie(); for (const word of dictionary) trie.addWord(word); return sentence.split(' ').map((word) => trie.findAndReplaceWord(word)).join(' '); }; replaceWords(['cat', 'bat', 'rat'], 'the cattle was rattled by the battery'); ================================================ FILE: LeetCode/Trie/Top_K_Frequent_Words/JeongShin.js ================================================ ================================================ FILE: LeetCode/Trie/Word_Break/6047198844.py ================================================ import collections class TrieNode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.check = False class Trie: def __init__(self): self.root = TrieNode() #현재 트라이에 삽입한다. def insert(self, word): node = self.root for char in word: node = node.children[char] node.check = True #단어가 존재하는지 확인. def find(self, word): node = self.root for char in word: if char not in word: return False node = node.children[char] return node.check class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: res = Trie() for word in wordDict: res.insert(word) #방문했으면 True. 방문했다는것은 해당 인덱스로 접근했을때 답이 아니라는것임. N = len(s) memo = [False for _ in range(N)] def dfs(start): if N == start: return True if memo[start]: return False for end in range(start + 1, N + 1): if res.find(s[start:end]) and dfs(end): return True memo[start] = True return False return dfs(0) ================================================ FILE: LeetCode/Two_Pointers/Is Subsequence/604719844.py ================================================ class Solution: def isSubsequence(self, s: str, t: str) -> bool: m = len(s) n = len(t) if m > n: return False i = 0 j = 0 while i < m and j < n: if s[i] == t[j]: i += 1 j += 1 else: j += 1 if i == m: return True return False ================================================ FILE: LeetCode/Two_Pointers/Reverse_String/6047198844.py ================================================ class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ s[:] = s[::-1] ================================================ FILE: LeetCode/Two_Pointers/Reverse_Vowels_of_a_String/6047198844.py ================================================ class Solution: def reverseVowels(self, s: str) -> str: word = '' N = len(s) begin, end = 0, N - 1 vowels = set(['a','e','i','o','u','A','E','I','O','U']) while begin < N: if s[begin] in vowels: while s[end] not in vowels: end -= 1 word += s[end] end -= 1 else: word += s[begin] begin += 1 return word ================================================ FILE: LeetCode/Two_Pointers/Sort_Colors/JeongShin.js ================================================ /** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ const sortColors = function (nums) { if (nums[1] === undefined) return; let [pointer, left, right] = [0, 0, nums.length - 1]; while (left <= right) { let temp = nums[left]; if (temp === 2) { nums[left] = nums[right]; nums[right] = temp; right--; continue; } if (temp === 0) { nums[left] = nums[pointer]; nums[pointer] = temp; pointer++; } left++; } }; sortColors([2, 0, 2, 1, 1, 0]); ================================================ FILE: LeetCode/Two_Pointers/Valid Palindrome/6047198844.py ================================================ import re class Solution: def isPalindrome(self, s: str) -> bool: s = re.sub('[^a-z0-9A-Z]','',s).lower() return s == s[::-1] ================================================ FILE: LeetCode/Union_Find/Friend_Circles/JeongShin.js ================================================ /** * @param {number[][]} M * @return {number} */ const findCircleNum = function (M) { const N = M.length; const group = new Map(); let groupNum = 0; for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { if (M[i][j] === 1 && !group.has(i)) { group.set(i, ++groupNum); dfs(i, group, groupNum, N, M); } } } return groupNum; }; function dfs(student, group, groupNum, N, M) { for (let friend = 0; friend < N; friend++) { if (M[student][friend] === 1 && !group.has(friend)) { group.set(friend, groupNum); dfs(friend, group, groupNum, N, M); } } } ================================================ FILE: LeetCode/Union_Find/Longest_Consecutive_Sequence/JeongShin.js ================================================ /* * [100, 4, 200, 1, 3, 2] 와 같이 배열이 있을때 * 가장 긴 연속된 숫자의 길이를 반환 하는 문제 * 따라서 [1, 2, 3, 4] 의 연속된 숫자가 존재하기 때문에 4를 반환 해야함. * */ /* 나의 풀이 */ class Node { constructor(end, parent, children) { this.end = end; this.parent = parent; this.children = children; } } const longestConsecutive = function (nums) { const map = new Map(); const find = (num) => { let parent = num; while (!map.get(parent).end) parent = map.get(parent).parent; return parent; }; const union = (p1, p2) => { const [c1, c2] = [map.get(p1).children, map.get(p2).children]; const [parent, child] = c1 > c2 ? [p2, p1] : [p1, p2]; map.set(parent, new Node(true, null, c1 + c2)); map.set(child, new Node(false, parent, 0)); }; for (const num of nums) { const [left, right] = [num - 1, num + 1]; if (map.has(num)) continue; map.set(num, new Node(true, null, 1)); if (map.has(left)) union(...[num, left].map(find)); if (map.has(right)) union(...[num, right].map(find)); } let answer = 0; for (const [k, v] of map) answer = Math.max(v.children, answer); return answer; }; longestConsecutive([100, 4, 200, 1, 3, 2]); /* 다른 사람 코드를 참고한 풀이 */ const longestConsecutive2 = function (nums) { const map = new Map(); let answer = 0; for (const num of nums) { if (map.has(num)) continue; let left = map.has(num - 1) ? map.get(num - 1) : 0; let right = map.has(num + 1) ? map.get(num + 1) : 0; let sum = left + right + 1; map.set(num, sum); answer = Math.max(sum, answer); map.set(num - left, sum); map.set(num + right, sum); } return answer; }; longestConsecutive2([100, 4, 200, 1, 3, 2]); ================================================ FILE: LeetCode/Union_Find/Redundant_Connection/JeongShin.js ================================================ const find = function (child, map) { let parent = child; while (map.has(parent)) { parent = map.get(parent); } return parent; }; /** * @param {number[][]} edges * @return {number[]} */ const findRedundantConnection = function (edges) { const map = new Map(); const answer = []; for (let edge of edges) { let [from, to] = edge; to = map.has(to) ? find(to, map) : to; from = map.has(from) ? find(from, map) : from; from === to ? answer.push(edge) : map.set(to, from); } return answer.pop(); }; findRedundantConnection([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]); // [1, 4] ================================================ FILE: LeetCode/Union_Find/Redundant_Connection_II/JeongShin.js ================================================ ================================================ FILE: LeetCode/Union_Find/Surrounded_Regions/JeongShin.js ================================================ /** * @param {string[][]} board * @return {void} Do not return anything, modify board in-place instead. */ const solve = function (board) { if (!board[0]) return; const [row, col] = [board.length, board[0].length]; const visited = new Map(); const parent = new Map(); let num = 1; for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { const key = i + ',' + j; if (board[i][j] === 'O' && !visited.has(key)) { parent.set(num, true); union(board, [i, j], visited, parent, num); } if (parent.get(visited.get(key))) board[i][j] = 'X'; num++; } } }; const union = function (board, start, visited, map, num, coords) { const stack = [start]; while (stack[0]) { const [i, j] = stack.pop(); const key = i + ',' + j; visited.set(key, num); [[i - 1, j], [i + 1, j], [i, j + 1], [i, j - 1]].forEach(([i, j]) => { const key = i + ',' + j; // 만약 undefined 를 마주할 경우 ('X'로 둘러 쌓이지 않은 경우) 해당 전체 set 은 false 로 바꿔준다. if (!board[i] || !board[i][j]) map.set(num, false); // 아직 방문하지 않은 'O' 구역의 coords 는 스택에 푸쉬 if (board[i] && board[i][j] === 'O' && !visited.get(key)) { stack.push([i, j]); } }) } }; ================================================ FILE: LeetCode/Union_Find/Surrounded_Regions/eyabc.js ================================================ /** * @param board * 핵심 * O 로 이어진 인덱스들의 동서남북 중 하나가 범위를 벗어나면 X 에 갇혀있지 않다. */ // 동 북 서 남 const dx = [0, -1, 0, 1]; const dy = [1, 0, -1, 0]; const makeTable = (H, W) => { const table = new Array(H); for (let i = 0 ; i < H ; i++) { table[i] = new Array(W).fill(-0); } return table; }; const solve = function(board) { // 배열의 열, 1차원 행렬일 때에는 board 를 그대로 리턴한다. if (!board[0]) return board; // 배열의 높이와 너비을 저장한다. const [H, W] = [board.length, board[0].length]; // 이미 방문한 인덱스를 저장하기 위한 테이블을 만든다. -0 (방문전) 1 (방문함) const table = makeTable(H, W); // 현재 인덱스의 동서남북을 검사하는 함수 const ENSW = (x, y, ref) => { // X 이거나 이미 방문한 인덱스는 동서남북을 검사하지 않는다. if (board[x][y] === 'X' || table[x][y] === 1) return; // 방문처리 한다. table[x][y] = 1; // 현재 인덱스의 동서남북이 모두 존재하는지 검사. let direction = 0; for (let i = 0 ; i < 4 ; i++) { const [nx, ny] = [x + dx[i], y + dy[i]]; // 인덱스의 범위가 존재할 때 if (board[nx] && board[nx][ny]) { const near = board[nx][ny]; direction += 1; // 동/서/남/북 인덱스가 O 일때, O 인덱스의 동서남북을 순회한다. if (near === 'O') ENSW(nx, ny, ref); } } // 동서남북이 모두 있을때, ref 에 해당 O 의 인덱스를 추가한다. direction === 4 ? ref.push([x, y]) // 동서남북이 모두 존재하지 않는다면, X 에 둘러쌓이지 않을 확률은 100% 이다. : (ref[0] = false); }; // board 의 모든 인덱스를 검사한다. for (let x = 0 ; x < H ; x++) { for (let y = 0 ; y < W ; y++) { const thisPos = board[x][y]; // 현재 인덱스가 X 이거나 이미 방문한 인덱스 이면 동서남북을 검사하지 않는다. if (thisPos === 'X' || table[x][y] === 1) continue; // ref: 이어진 O의 좌표를 담는 배열 const ref = []; // x, y 좌표를 시작으로 이어지는 O 를 찾아 ref 배열에 담는 함수 ENSW(x, y, ref); // 사방이 X 로 막힌 O 는 X 로 만들어 준다. ref 에는 O 의 인덱스들이 들어 있다. if (ref[0]) ref.forEach(([x, y]) => board[x][y] = 'X'); } } return board; }; console.log( solve([['X', 'X', 'X', 'X'], ['X', 'O', 'O', 'X'], ['X', 'X', 'O', 'X'], ['X', 'O', 'X', 'X']]).toString() === [['X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X'], ['X', 'O', 'X', 'X']].toString(), ); console.log( solve([ ['X', 'O', 'X', 'O', 'X', 'O'], ['O', 'X', 'O', 'X', 'O', 'X'], ['X', 'O', 'X', 'O', 'X', 'O'], ['O', 'X', 'O', 'X', 'O', 'X'], ]).toString() === [ ['X', 'O', 'X', 'O', 'X', 'O'], ['O', 'X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X', 'O'], ['O', 'X', 'O', 'X', 'O', 'X'], ].toString(), ); console.log(solve(['0'].toString() === ['0'].toString())); console.log( solve([['O', 'O', 'O'], ['O', 'O', 'O'], ['O', 'O', 'O']].toString()) === [['O', 'O', 'O'], ['O', 'O', 'O'], ['O', 'O', 'O']].toString(), ); ================================================ FILE: README.md ================================================ # Welcome! 2020년 04월 24일에 개설된 단국대학교 알고리즘 스터디 그룹입니다. ## 알고리즘 유의사항 - 코드리뷰의 가독성을 위해, 변수명과 로직을 명확하게 하도록 노력합시다 - 현업에서 내가 짠 코드를 나 혹은 다른 사람이 이해할 수 있게 짜는, 배려가 중요합니다 - 주석을 달지 않아도 이해할 수 있을 정도의 코드를 짜봅시다. ## 알고리즘 준비의 중요성 ## 가입 문의 [스터디 참여 신청 알림](https://github.com/DKU-STUDY/Algorithm/issues) 에 코멘트를 남겨주세요. ## PR 규칙 - PR 이름은 알고리즘 푼 문제 이름 - label 에 사용한 언어를 추가합니다 ## 알고리즘 연습하기 - [codility](https://app.codility.com/) - [연습문제풀기](https://app.codility.com/programmers/lessons/1-iterations/) 의 문제를 풉니다. - [codility_training](codility_training) 폴더에 풀이한 내용을 업로드해주세요. - [프로그래머스](https://programmers.co.kr/) - [고득점kit](https://programmers.co.kr/learn/challenges?tab=algorithm_practice_kit) - [스킬체크](https://programmers.co.kr/skill_checks) - [모든문제](https://programmers.co.kr/learn/challenges?tab=all_challenges) - [programmers](https://github.com/JunilHwang/Algorithm/tree/master/programmers) 폴더에 풀이한 내용을 업로드해주세요. 알고리즘 플랫폼 사이트에 상관 없이 파일/폴더 형식만 잘 정리해서 올려주세요! ## 파일 및 폴더 구조 - `플랫폼/카테고리(생략가능)/주제.문제.숫자/깃허브아디` 형식으로 업로드해주세요. - 예시 01: [/codility_training/lesson.01.Iterations.BinaryGap/junilhwang.js](./codility_training/lesson.01.Iterations.BinaryGap/junilhwang.js) - 예시 01: [/codility_training/lesson.01.Iterations.BinaryGap/eyabc.js](./codility_training/lesson.01.Iterations.BinaryGap/eyabc.js) - 예시 02: [/codility_training/lesson.02.Arrays.CyclicRotation/junilhwang.js](codility_training/lesson02.Arrays.CyclicRotation/junilhwang.js) - 예시 03: [/programmers/코딩테스트_고득점kit/2_스택,큐.기능개발/junilhwang.js](./programmers/코딩테스트_고득점kit/2_스택,큐.기능개발/junilhwang.js) ## PR 양식 ### PR 제목 ![image](https://user-images.githubusercontent.com/31977543/94366306-44307e80-0112-11eb-80d3-95a5e4998e64.png) 제목: [알고리즘분류]알고리즘제목 label: 문제푼 곳, 언어, 난이도(옵션) #### PR 본문 1. 문제 출처 2. input 과 output 설명 3. 풀이 아이디어 #### label - asignee : 내 아이디 - reviewer : 이미 문제를 풀었거나, 같은 언어를 쓰는 사람 - label: 문제 출처(Programmers, BOJ, leetcode, codility... ), 푼 언어(Javascript, python, java, c++, c, ...) , 난이도(HARD, EASY, NOMAL) #### Merge 기준 a. assignee 모두 리뷰를 남겼을 때 b. 다음 문제를 풀기 직전 기준 a 혹은 b 둘중 하나만 만족하면됩니다! ## 리뷰 하는 방법 자신의 의견을 망설이지 않고 표출하는것이 가장 중요하다. 개선점, 칭찬, 이모티콘 등 자유롭게 의견을 표현할 수 있다. ## tip - 한 문제를 여러가지 방법으로 풀도록 탐구해보기 - 30분~60분 까지 고민해 본다. - 어려우면 솔루션을 찾아본다. - 문제 풀이의 흔적을 남기기 위해서 당신의 솔루션을 업로드 - 가능 하면 매일 매일 풀이하여 일일커밋에 도전해보기! - [BTS_depth 가이드](https://dku-study.github.io/InfoBoard/BST_depth.html) ================================================ FILE: Tips/BOJ 영업자료.md ================================================ # BOJ 영업자료 #### 개론 BOJ 문제가 가끔 좀 별로인것도 있지만 한국어화 되어 있다는 장점과 엄청 많은 문항수로 자신없는 유형의 문제를 자신있게 될때까지 풀어볼 수 있다는 장점이 있는 바, 여러분들이 저와 같이 백준 문제를 풀었으면 좋겠다는 이유로 Python 유저분들을 위해 제가 처음에 백준 문제를 풀려 했을때 어려웠던 점을 공유합니다. (같이 풀어주세요...) #### 어려웠던 점 프로그레머스나 코딜리티와 다르게 백준은 문제의 입출력을 직접 구현해야한다는 특징이 있습니다. 사실 입출력이라고 하기에는 터미널의 간단한 기능만 사용하는 것 이지만, 입출력에 대한 아무런 지식이 없이 막상 문제를 푸려하니 좀 어려운 부분이 있더라구요. * ##### 기본적으로! BOJ의 문제는 **터미널**을 통해 체점됩니다. 사이트가 정해진 입력값을 터미널을 통해 넣어주고, 저희는 결과값을 터미널을 통해 출력 해주면 그 값을 가지고 사이트는 체점을 시작합니다. **이때!** 터미널을 통해 가져가므로, 가져간 출력값은 문자열이 됩니다. 사이트가 채점을 하는 방식은 가져온 값이 저장된 문자열과 일치하는지 비교하는것이므로 만약 사이트가 원하는 정답이 **65**일 경우 **' 65'** 나 **'6 5'** 혹은 **'65 '** , **'[65]'** 모두 오답처리 될 수 있습니다. **print( )** 함수를 이용하여 출력 할 때, 문제가 원하는 출력값에 완벽하게 부합하는지 확실히 확인해야지 문제를 다 풀어놓고 오답처리되어 당황하는 경우가 없겠죠? * ##### input은 뭘로 받아야하나 Python은 터미널 입력을 받는 함수로 **input( )** 을 사용합니다. 그런데, Python 자체가 많이 느린 언어다 보니 입력되는 데이터의 N수가 커질 경우에 이 과정에서 시간이 많이 소요되어 타임오버되는 경우가 있습니다. 그러한 경우를 피하기 위해서 sys 모듈의 **stdin.readline( )** 함수를 사용합니다. **stdin.readline( )** 함수는 **input( )** 보다는 좀더 날것의 데이터를 받아온다고 생각하시면 될것 같습니다. 터미널에 입력된 **한 줄**을 하나의 **문자열**로 가져옵니다! 심지어 개행문자 **'\n'** 까지 포함해서요. ex) 터미널에 > **test input** 을 입력했을떄, **'test input\n'** 으로 가져옵니다 그래서 문제의 풀이에서 입력된 문자열을 요구하는것이 아니라면 **int( )** 혹은 **float( )** 등을 사용하여 적당한 자료형으로 변환해줘야하는 단점이 있습니다. 흔히 한줄에 하나의 리스트를 받는 경우가 많은데, 이때는 **stdin.readline( )** 으로 받은 문자열을 **.split( )** 메소드를 이용해 분할하고, 필요하다면 **strip('\n')** 을 통해 개행문자를 제거해야 할 수도 있습니다. 분열된 여러개의 문자열을 **map( )** 함수를 이용해서 정수형으로 바꿔줍니다. 변환이 완료된 여러개의 정수형 변수들을 **list( )** 함수를 이용하여 리스트로 엮어줍니다. 한줄로 쓰면, **input_list = list( map( int, stdin.readline.split( ) ) )** 이 되겠네요. > * ##### 코드의 처리과정 > > stdin.readline( ) 터미널에 입력된 값을 가져옵니다 > > ​ > 1 2 3 4 ----> str('1 2 3 4\n') > > split( ) 인자에 아무값을 넣지 않으면 공백을 기준으로 분할합니다. > > ​ > str('1 2 3 4\n') -->( str('1') str('2') str('3') str('4\n') ) > > map( int, input_data) > (str('1') str('2') str('3') str('4\n') )---> (int(1) int(2) int(3) int(4) ) > > list( ) 튜플형태의 input_data를 list로 변환시켜 줍니다. > > ​ >(int(1), int(2), int(3), int(4) ) ---> [int(1), int(2), int(3), int(4)] > > 따라서 input_list = [1, 2, 3, 4]가 됩니다. #### 같이 보면 도움이 될만한 사이트 **solved.ac** 이 사이트에서 BOJ의 문제들을 난이도 별로 분류하고, class 별로 나눠놓아 자신이 많은 문제를 어디서부터 풀어야 할지 막막하시다는 분들은 **solved.ac** 를 활용하시면 많은 도움이 될수 있을겁니다. ================================================ FILE: Tips/Git 깃.md ================================================ 여러분이 컴퓨터에 작성한 코드(프로그래밍 언어로 작성한 파일뿐만 아니라, 이미지, 마크다운, 텍스트파일, 문서파일 모두) 를 다른사람과 공유하고 싶을 때! 바로 Git을 써야 하는 이유 입니다. 왜 작성한 코드를 공유를 할까요? 프로그래밍에 관심있는 모두에게 공유하면 서로에게 도움이 됩니다. 나의 포트폴리오를 만들 수 있습니다. 프로젝트를 다른사람과 같이 작성할 수 있습니다. 이 외 자신의 목적에 맞게 얼마든지 활용가능합니다. git을 통해서 내 컴퓨터에 저장된 코드를 github 홈페이지 에 있는 저장소에 올릴 수 있습니다. 또는 저장소의 코드를 내 컴퓨터에 가져올 수 있습니다. 필요한 준비물 1. github 가입 2. 카카오톡 게시판에 github 아이디를 적는다. 3. 그룹장이 [단국대 알고리즘 저장소](https://github.com/eyabc/DKU_STUDY_GROUP)에 초대를 해준다. 준비가 완료되었다면 [단국대 알고리즘 저장소](https://github.com/eyabc/DKU_STUDY_GROUP) 에 자신의 솔루션을 업로드 해 봅시다. ![upload solution](./images/uploadSolution.png) ================================================ FILE: Tips/Pull-Request.md ================================================ # Pull Request [![Pull Request](https://img.youtube.com/vi/pR5SNFyzdg8/0.jpg)](https://www.youtube.com/watch?v=pR5SNFyzdg8) pull request에 대한 설명입니다. ================================================ FILE: codility_training/11st/2020/1/eyabc.js ================================================ /** * @param S * @return a 가 삽입될 수 있는 최대 개수 * a 삽입의 조건: a 가 최대 2개 연속하여 존재할 수 있다. * a 가 3개 이상 연속하면 -1 을 리턴한다. */ const notAidx = (string) => Array.from(string.matchAll('[^a]', 'g'), v => v.index); const countInsertedA = (notAidx, originLastIdx) => { const notAidxLastIdx = notAidx.length - 1; // 첫번째 notAidx의 인덱스앞에 삽입할 수 있는 a 의 개수와, 마지막 notAidx 의 인덱스 뒤에 삽입할 수 있는 a 의 개수를 미리 구한다. let cnt = 4 - notAidx[0] - (originLastIdx - notAidx[notAidxLastIdx]); notAidx.forEach((v, i) => { // 마지막 인덱스는 계산하지 않는다. (앞에 이미 계산함) if (i === notAidxLastIdx) return; // 현재 인덱스와 다음 인덱스 사이에 삽입할 수 있는 a 의 개수를 구한다. cnt += (3 - notAidx[i + 1] + v); }); return cnt; }; function solution(S) { if (/aaa/.test(S)) return -1; if (S === 'aa') return 0; const originLastIdx = S.length - 1; // a 문자가 아닌 문자들의 인덱스 배열을 반환한다. const found = notAidx(S); // 삽입된 a 개수를 리턴한다. return countInsertedA(found, originLastIdx); } console.log(solution('aabab') === 3); // aabaabaa console.log(solution('dog') === 8); // aadaaoaagaa console.log(solution('dogaa') === 6); // aadaaoaagaa console.log(solution('aa') === 0); // aa console.log(solution('baaaa') === -1); // -1 console.log(solution('baabaa') === 2); // console.log(solution('aabaa') === 0); // ================================================ FILE: codility_training/11st/2020/1/junilhwang.js ================================================ function solution (S) { const N = S.length; if (S.indexOf('aaa') !== -1) return -1; const filtered = S.split('').filter(v => v !== 'a'); if (filtered.length === 0) return 0; const result = filtered.reduce((str, c) => str + c + "aa", "aa"); return result.length - N; } console.log(solution('aabab'), 3); console.log(solution('dog'), 8); console.log(solution('aa'), 0); console.log(solution('baaaa'), -1); ================================================ FILE: codility_training/11st/2020/2/junilhwang.js ================================================ function solution (S) { const map = {}; for (const [k, v] of Object.entries(S)) { v.split('').forEach((c, position) => { const mapKey = `${c},${position}`; map[mapKey] = map[mapKey] || []; map[mapKey].push(k); }) } for (const [k, v] of Object.entries(map)) { if (v.length === 1) continue; const z = k.split(',')[1]; return [ ...v, z ].map(Number); } return []; } console.log(solution(["abc", "bca", "dbe"]), [0, 2, 1]); console.log(solution(["zzzz", "ferz", "zdsr", "fgtd"]), [0, 1, 3]); console.log(solution(["gr", "sd", "rg"]), []); console.log(solution(["bdafg", "ceagi"]), [0, 1, 2]); ================================================ FILE: codility_training/11st/2020/3/junilhwang.js ================================================ function solution (A) { return A.sort().reduce((sum, v, k) => sum + Math.abs(v - (k + 1)), 0); } console.log(solution([1, 2, 1]), 2); console.log(solution([2, 1, 4, 4]), 1); console.log(solution([6, 2, 3, 5, 6, 3]), 4); ================================================ FILE: codility_training/Est2020.07/1.js ================================================ /* 카드번호 유형인지 체크 */ const validForm = (arr) => arr.toString() === [4, 9, 14].toString() || arr.length === 0; /* 카드번호가 16자리인지 체크 */ const validLength = (number) => number.length === 16; const findHyphenIdx = () => (arr, char, key) => { if (char === '-') arr.push(key); return arr; }; const processNumber = () => ([odd, even, isEven], char) => { if (isEven) { let num = Number(char) * 2; if (num > 9) num = 1 + (num - 10); even += num; } else odd += Number(char); return [odd, even, !isEven]; }; function solution (card_numbers) { const reduce = Array.prototype.reduce; return card_numbers.map(card => { const hyphenIdxArr = reduce.call(card, findHyphenIdx(), []); if (!validForm(hyphenIdxArr)) return 0; const number = card.replace(/\-/g, ''); if (!validLength(number)) return 0; const [odd, even] = reduce.call(number, processNumber(), [0, 0, true]); return ((odd + even) % 10 === 0) * 1; }); } console.log(solution(['3285-3764-9934-2453', '3285376499342453', '3285-3764-99342453', '328537649934245', '3285376499342459', '3285-3764-9934-2452'], [1, 1, 0, 0, 0, 0])); ================================================ FILE: codility_training/Est2020.07/2.js ================================================ function solution (scores, k) { const arr = []; const len = scores.length; if (scores.length === 1) return 0; /* 앞 스코어와의 점수 차를 나타내는 배열을 만든다. */ for (let i = 1 ; i < len ; i++) { arr.push({ k: i, v: scores[i] - scores[i - 1], }); } const slicePoint = arr.sort((a, b) => b.v - a.v) // 점수차가 큰 순서대로 정렬한다. .slice(0, k - 1) // 점수차가 가장 큰 key 들을 나누는 지점으로 선택한다. .sort((a, b) => Number(a.k) - Number(b.k)); // key 를 기준으로 다시 정렬한다. console.log({slicePoint}); let before = 0; let sum = 0; for (const v of slicePoint) { /* 반복1: mostBigKey 인 2 기준으로 앞의 그룹을 만든다. 그러면 0~1 인덱스가 되고, 이때 gap 은 2 이다. 그리고 다음 그룹의 시작 인덱스를 v.k 로 재 할당한다. */ /* 반복2: mostBigKey 인 5 기준으로 앞의 그룹을 만든다. 그러면 2~4 인덱스가 되고, 이때 gap 은 3 이다. 그리고 다음 그룹의 시작 인덱스를 v.k 로 재 할당한다. */ sum += scores[v.k - 1] - scores[before]; before = v.k; } /* sum 은 (k - 1) 개 그룹의 gap 의 차이의 합이고, 뒤의 두 항은 마지막 그룹의 인덱스의 합이다. */ return sum + scores[len - 1] - scores[before]; } console.log( solution([1, 3, 7, 8, 10, 15], 3) === 5, // solution([1, 2, 12, 14, 15], 2) === 4, ); /* 오름차순 scores k개의 조 최대한 점수가 비슷한 학생 각 조에서 가장 점수가 높은 학생의 점수와 가장 점수가 낮은 학생의 점수의 차이를 구한 후, 차이의 합이 최소가 되도록 조에 적어도 1명의 학생 한 명이므로 차이가 0 낮은 학생의 차이의 합 */ ================================================ FILE: codility_training/Est2020.07/3.js ================================================ function diff (maps, x, y, r, range) { let cnt = 0; const h = r / 2; for (let i = 0 ; i < r ; i++) { const Y = x + i - h; if (!maps[Y]) continue; for (let j = 0 ; j < r ; j++) { const X = y + j - h; if (!maps[Y][X]) continue; if (maps[Y][X] <= range[i][j]) { cnt += 1; } } } return cnt; } const makeRange = (r) => { const range = new Array(r); for (let i = 0 ; i < r ; i++) { range[i] = new Array(r).fill(0); } return range; }; function solution (maps, p, r) { const range = makeRange(r); const h = r / 2; // 공격 데미지 범위를 나타내는 배열 for (let i = 0 ; i < h ; i++) { range[i][h - i - 1] = p / 2; range[i][h + i] = p / 2; range[h + i][i] = p / 2; range[h + i][r - i - 1] = p / 2; for (let j = h - i ; j < h + i ; j++) { range[i][j] = p; } for (let j = i + 1 ; j < r - i - 1 ; j++) { range[h + i][j] = p; } } let max = 0; const mapsLen = maps.length; for (let i = 0 ; i < mapsLen ; i++) { for (let j = 0 ; j < mapsLen ; j++) { max = Math.max(diff(maps, i, j, r, range), max); } } return max; } console.log( solution([[1, 28, 41, 22, 25, 79, 4], [39, 20, 10, 17, 19, 18, 8], [21, 4, 13, 12, 9, 29, 19], [58, 1, 20, 5, 8, 16, 9], [5, 6, 15, 2, 39, 8, 29], [39, 7, 17, 5, 4, 49, 5], [74, 46, 8, 11, 25, 2, 11]], 19, 6) === 17, // solution([[47, 8, 99, 9, 85, 3, 8], [90, 93, 8, 25, 98, 15, 97], [9, 95, 91, 87, 8, 81, 9], [98, 88, 82, 89, 79, 81, 97], [97, 35, 31, 97, 81, 2, 92], [32, 16, 49, 9, 91, 89, 17], [53, 6, 35, 12, 13, 98, 5]], 78, 6) === 11, // solution([[9, 8, 17, 55, 19, 7], [1, 25, 5, 39, 28, 8], [88, 19, 28, 3, 2, 9], [76, 73, 7, 18, 16, 14], [99, 8, 8, 7, 11, 9], [1, 18, 4, 10, 3, 6]], 16, 4) === 8, // solution([[6, 3, 2, 7, 3], [7, 2, 1, 6, 8], [8, 9, 8, 4, 9], [7, 9, 2, 7, 1], [6, 3, 6, 8, 4]], 5, 2) === 3, ); // r 은 짝수 // 블루는 r * 2 // 옐로는 Y(n-1) + B(n - 1) // 공격범위 좌표: ================================================ FILE: codility_training/Est2020.Exam01/README.md ================================================ # 출처 코딩 테스트라서 출처 없음 ================================================ FILE: codility_training/Est2020.Exam01/junilhwang.js ================================================ function solution (A) { A.sort((a, b) => b - a) const len = A.length let i = 0 while (i < len) { const n = A[i] const idx = A.lastIndexOf(n) if (idx - i + 1 === n) return n i = idx + 1 } return 0 } console.log(solution([3, 8, 2, 3, 3, 2]) === 3) console.log(solution([7, 1, 2, 8, 2]) === 2) console.log(solution([3, 1, 4, 1, 5]) === 0) console.log(solution([5, 5, 5, 5, 5]) === 5) console.log(solution([5, 5, 5, 5, 5, 5]) === 0) console.log(solution([5, 5, 5, 5]) === 0) ================================================ FILE: codility_training/Est2020.Exam02/README.md ================================================ # 출처 코딩 테스트라서 출처 없음 ================================================ FILE: codility_training/Est2020.Exam02/junilhwang.js ================================================ function solution (A) { const obj = {} return A.reduce((max, v, k) => { const n = [...`${v}`].reduce((a, b) => a*1 + b*1) const arr = obj[n] || [] if (arr) { const sum = Math.max(...arr.map(v2 => v + A[v2])) if (sum > max) max = sum } obj[n] = (arr.push(k), arr) return max }, -1) } console.log(solution([51, 71, 17, 42]) === 93) console.log(solution([42, 33, 60]) === 102) console.log(solution([51, 32, 43]) === -1) console.log(solution([11, 2, 3, 21]) === 24) console.log(solution([11, 2, 20]) === 31) console.log(solution([1]) === -1) console.log(solution([199999, 199989, 199998]) === 199989 + 199998) ================================================ FILE: codility_training/Est2020.Exam03/README.md ================================================ # 출처 코딩 테스트라서 출처 없음 ================================================ FILE: codility_training/Est2020.Exam03/junilhwang.js ================================================ function solution (A) { const checker = arr => { const len = arr.length if (len === 1) return true if (arr[0] === arr[1]) return false let before = arr[0] < arr[1] for (let i = 1; i < len - 1; i++) { const now = arr[i] < arr[i+1] if (arr[i] === arr[i+1] || now === before) return false before = now } return true } if (checker(A) === true) return 0 const len = A.length let cnt = 0 for (let i = 0; i < len; i++) { const arr1 = A.slice(0, i) const arr2 = A.slice(i + 1) cnt += checker([...arr1, ...arr2]) ? 1 : 0 arr1.push(arr2.shift()) } return cnt === 0 ? -1 : cnt } console.log(solution([3, 4, 5, 3, 7]) === 3) console.log(solution([1, 2, 3, 4]) === -1) console.log(solution([1, 3, 1, 2]) === 0) console.log(solution([1, 3, 3, 3]) === -1) console.log(solution([1]) === 0) console.log(solution([1, 1]) === 2) console.log(solution([1, 2]) === 0) console.log(solution([2, 2]) === 2) console.log(solution([2, 2, 2]) === -1) console.log(solution([2, 3, 2]) === 0) console.log(solution([10, 20, 30, 20]) === 2) console.log(solution([10, 20, 30, 19]) === 3) console.log(solution([10, 20, 30, 19, 10, 20, 30, 19]) === -1) ================================================ FILE: codility_training/Est2020.Exam04/README.md ================================================ # 출처 코딩 테스트라서 출처 없음 ================================================ FILE: codility_training/Est2020.Exam04/junilhwang.js ================================================ function solution (S, C) { const obj = {} const company = C.toLowerCase() return S.split(';').map(v => { const name = v.trim() const vArr = name.toLowerCase().replace(/\-/g, '').split(' ') let id = `${vArr.pop()}_${vArr[0]}` obj[id] = (obj[id] || 0) + 1 if (obj[id] > 1) id += obj[id] return `${name} <${id}@${company}.com>` }).join('; ') } const C = "Example" const S = "John Doe; Peter Benjamin Parker; Mary Jane Watson-Parker; John Elvis Doe; John Evan Doe; Jane Doe; Peter Brian Parker" const resolve = `John Doe ; Peter Benjamin Parker ; Mary Jane Watson-Parker ; John Elvis Doe ; John Evan Doe ; Jane Doe ; Peter Brian Parker ` // console.log(solution(S, C) === resolve) const S2 = "John Doe; Peter Benjamin Parker; Mary Jane Watson-Parker-a-b-c; John Elvis Doe; John Evan Doe; Jane Doe; Peter Brian Parker" const resolve2 = `John Doe ; Peter Benjamin Parker ; Mary Jane Watson-Parker-a-b-c ; John Elvis Doe ; John Evan Doe ; Jane Doe ; Peter Brian Parker ` // console.log(solution(S2, C) === resolve2) const S3 = "John Doe; Peter Benjamin Parker P2 P3 P4; Mary Jane Watson-Parker-a-b-c; John Elvis Doe; John Evan Doe; Jane Doe; Peter Brian Parker" const resolve3 = `John Doe ; Peter Benjamin Parker P2 P3 P4 ; Mary Jane Watson-Parker-a-b-c ; John Elvis Doe ; John Evan Doe ; Jane Doe ; Peter Brian Parker ` console.log(solution(S3, C) === resolve3) ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/JeongShin.js ================================================ function solution(N) { var s = ""; while (N != 0) { let add = N % 2; s = add.toString().concat(s); N = Math.floor(N / 2); } var gap = 0; var max_gap = 0; for (let i = 0; i < s.length; i++) { if (s[i] == "1") { if (gap > max_gap) max_gap = gap; gap = 0; } else gap++; } return max_gap; } console.log(solution(32) === 0) console.log(solution(1041) === 5) console.log(solution(9) === 2) console.log(solution(529) === 4) console.log(solution(20) === 1) console.log(solution(15) === 0) ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/JunilHwang.java ================================================ package lessons.lesson01.Iterations.BinaryGap; public class JunilHwang { public static int solution(int n) { String b = Integer.toBinaryString(n); int i = 0, max = 0, len = b.length(), idx; // idx는 일단 정의만 while (i < len) { // 반복 횟수를 최대한 줄이기 idx = b.indexOf("1", i + 1); if (idx == -1) break; max = Math.max(max, idx - i - 1); i = idx; } return max; } public static void main(String[] args) { System.out.println(solution(32) == 0); System.out.println(solution(1041) == 5); System.out.println(solution(9) == 2); System.out.println(solution(529) == 4); System.out.println(solution(20) == 1); System.out.println(solution(15) == 0); } } ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/README.md ================================================ # Iterations.BinaryGap ## 출처 https://app.codility.com/programmers/lessons/1-iterations/binary_gap/ ## 문제 해결 방법 ### 0. Binary 관련 Method를 이용한다. #### javascript ``` ts const N: number = 32 const b: string = N.toString(2) ``` #### java ``` java String b = Integer.toBinaryString(n); ``` ### 1. indexOf를 이용한다. #### javascript ``` js const b = '1000100100010000000001' b.indexOf('1', 1) // output 4 b.indexOf('1', 5) // output 7 b.indexOf('1', 8) // output 11 b.indexOf('1', 12) // output 21 ``` #### java ``` java String b = "1000100100010000000001"; b.indexOf("1", 1); // output 4 b.indexOf("1", 5); // output 7 b.indexOf("1", 8); // output 11 b.indexOf("1", 12); // output 21 ``` ### 2. Math.max를 이용한다. #### javascript ``` js const max = Math.max(7 - 4, 11 - 7, 21 - 11) return max ``` #### java ``` java // 4 7 11 21 에 대해서 int max = 7 - 4; // output 3 max = Math.max(max, 11 - 7) // output 4 max = Math.max(max, 21 - 11) // output 10 return max ``` ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/eyabc.js ================================================ function solution(N) { const bin = N.toString(2); let max = 0; let prev = 1; for (let i = 1; i < bin.length; i++ ) { if (bin[i] === '1') { const value = i - prev; if (value > 1 && value > max ) { max = i - prev; } prev = i; } } return max; } function solution2(N) { const bin = N.toString(2); let max = 0; let prev = 0; for (let i = 1; i < bin.length; i++ ) { if (bin[i] === '1') { const value = i - prev; if (value > max ) { max = i - prev - 1; } prev = i; } } return max; } console.log(solution2(328) === 2) ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/junilhwang.js ================================================ function solution (N) { const b = N.toString(2), len = b.length let i = 0, max = 0; while (i < len) { const idx = b.indexOf('1', i+1) // i 이후의 1을 가져옴 if (idx === -1) break // 없을 경우 종료 max = Math.max(idx - i - 1, max) // 현재 거리와 최대 거리를 비교 i = idx // 다음 1의 위치로 이동 } return max } function solution2 (N) { return [ ...N.toString(2) ].reduce(([ max, count ], v) => { if (v === '0') { count += 1 } else { max = Math.max(max, count) count = 0 } return [ max, count ] }, [0, 0])[0] } const assert = require('assert').strict require('./test.json').forEach(({ input, output }) => { assert.deepEqual(solution(...input), output); assert.deepEqual(solution2(...input), output); }) ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/khw970421.js ================================================ //방법 1 (방법 2에 비해 if문대신 Math.amx,삼항연산자로 코드를 간결화 for문 대신 while문으로 대체 result라는 불필요 변수 제거) function solution(N) { const a = N.toString(2); //배열생성 N이 32일경우 a는 100000 let i = 0, len = a.length, max_result = 0; while (i < len) { idx = a.indexOf('1', i + 1); // 문자열을 탐색 a.indexOf('1',i)부터 안해도 첫번째는 1이고 그외에는 N이 0인값이다. if (idx === -1) break; max_result = Math.max(idx - i, max_result); //첫번째 이후 처음 찾은 1에서 첫번째의 1을 뺀값을 비교하며 그후는 반복하며 가장큰 값찾는다. i = idx; //불필요한 i의 반복을 막기위해 찾은 idx를 i로 하여 반복문을 다시 돌린다. } return max_result === 0 ? 0 : max_result - 1; //max_result가 0일경우는 a가 1111일경우 혹은 0일경우다. 그외에는 값이 존재 // 1과1 사이에 있는 갯수이기에 max_result - 1 로 처리 } //방법 2 function solution1(N) { let a,b=[];//배열생성 let p=0; let max_result=0,result=0; a=N.toString(2); const a_length=a.length; for(let i=0;i=1) return max_result-1; else return 0; //성공 } //방법3(2020.05.15) function solution2(N) { let k=N.toString(2); //문자열 2진수로 설정 let count=0,max=0; //0을세는 count, 0이연속인 최대크기 max let h = [...k]; //문자열을 배열로 변경 let reducer = function(accumulator,value) // h.reduce함수에 initialvalue가 없으므로 accumulator에 배열의 첫번째값, value에 배열의 두번째값 입력 { if(value==0) //배열값이 0이라면 count 증가 count++; else { max = Math.max(max, count); //배열값이 1이되면 그때 최대치인 max와 비교하기 (1000이면 count를 세어도 max와 비교하지않는다.) count = 0; //count를 0으로 초기화 } } h.reduce(reducer); //reduce함수 사용 return max; } //방법4(2020.05.17 =>준일선배 도움 reduce 및 구조분해 할당 사용) function solution(N) { return [ ...N.toString(2) ].reduce(([max, count], value) => { if(value==0) //배열값이 0이라면 count 증가 count++; else { max = Math.max(max, count); //배열값이 1이되면 그때 최대치인 max와 비교하기 (1000이면 count를 세어도 max와 비교하지않는다.) count = 0; //count를 0으로 초기화 } return [ max, count ]; }, [0, 0])[0] // max 반환 } //ex) N이 1041(10000010001)일경우 //화살표 함수 뒤의 [0,0]으로 인해 initialValue가 존재하므로 첫번째 accumulator인 [max,count]는 [0,0]이고 value는 첫번째 배열값인 1이고 //아무일도 없고 value가 2번째부터 6번째까지 0이므로 count++ 하다가 7번째에서 else문을 통해 max가 5가된다 // 그후에 뒤에 000으로 인해 다시 count가 증가하지만 else문제어 max(5)>count(3)이므로 마지막에 [5,0]이 return되고 그중[0]인 5가 return된다. //방법4.1 화살표함수를 안쓸경우 function solution(N) { return [ ...N.toString(2) ].reduce(function ([max, count], value){ if(value==0) //배열값이 0이라면 count 증가 count++; else { max = Math.max(max, count); //배열값이 1이되면 그때 최대치인 max와 비교하기 (1000이면 count를 세어도 max와 비교하지않는다.) count = 0; //count를 0으로 초기화 } return [ max, count ]; }, [0, 0])[0] // max 반환 } console.log(solution(1041)===5); console.log(solution(15)===0); console.log(solution(32)===0); console.log(solution1(32) === 0) console.log(solution1(1041) === 5) console.log(solution1(9) === 2) console.log(solution2(529) === 4) console.log(solution2(20) === 1) console.log(solution2(15) === 0) ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/pul8219.java ================================================ package lessons.lesson01.Iterations.BinaryGap; class Solution{ public int solution(int N){ int one_cnt = 0; // 변환된 이진수에서 1 count int zero_cnt = 0; // binary gap 판단을 위해 0 count하기 위한 변수 int long_gap = 0; // 가장 긴 binary gap 값을 저장하기 위한 변수 String strN = Integer.toBinaryString(N); // 매개변수 N을 이진수로 변환 System.out.println("N(정수): " + N); System.out.println("N(이진수): " + strN); // 이진수에 1값이 얼마나 있는지 알아보기 위한 반복문 for(int i = 0, len = strN.length() ; i < len; i++){ if(strN.charAt(i) == '1') one_cnt++; } // 이진수에서 1값이 처음으로 등장하는 index를 구함 int index = strN.indexOf("1"); // 이진수에서 1값이 없거나 1이 1개만 있는 경우 프로그램 종료(binary gap이 없는 경우) if(index == -1 || one_cnt == 1){ return 0; } one_cnt--; //최초로 1이 나온 것 다음 index부터 검사 for(int i = index + 1, len = strN.length(); i < len; i++){ if(strN.charAt(i) == '0'){ // 현재 index의 값이 0이라면 zero_cnt++; // 0의 개수 누적시킴 } else if(strN.charAt(i) == '1'){ // 현재 index의 값이 1이라면 if(long_gap <= zero_cnt){ // long_gap 변수값보다 지금 누적한 binary gap값이 크다면 long_gap = zero_cnt; // longest binary gap value 갱신 zero_cnt = 0; // 다시 세기 위해 zero_cnt값 초기화 } one_cnt--; if(one_cnt == 0){ // 이진수에 1이 더이상 없으면 반복문 종료 break; } } } // end of for loop return long_gap; } // end of solution() } // end of class Solution class pul8219 { public static void main(String[] args){ Solution s = new Solution(); int long_gap = 0; long_gap = s.solution(529); System.out.println("Longest binary gap: " + long_gap); } // end of main() } // end of class pul8219 ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/sAp00n.py ================================================ from random import randint import time def logging_time(original_fn): def wrapper_fn(*args, **kwargs): start_time = time.time() result = original_fn(*args, **kwargs) end_time = time.time() print(f"WorkingTime[{original_fn.__name__}]: {end_time - start_time} sec") return result return wrapper_fn @logging_time def solution(N): # write your code in Python 3.6 bin_n = str(bin(N)[2:]) print(f'bin_N = {bin_n}') ans = 0 current = 0 last = 0 while True: current = bin_n.find('1', last + 1) # print(f'temp = {temp}') if current == -1: return -1 if last == 0 else ans if current - (last + 1) > ans: ans = current - (last + 1) last = current N = randint(1, 2147483647) print(f'input decaN= {N}') print(solution(N)) ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/sangmandu.py ================================================ from random import randint def solution(n): binary = [] while(n // 2 != 0): binary.append(1 if n % 2 == 1 else 0) n = n // 2 binary.append(1) index = [] for x, y in enumerate(binary): if(y == 1): index.append(x) max = 0 for i in range(len(index)-1): max = max(index[i+1] - index[i] - 1, max) return max print( solution(32) == 0, solution(1041) == 5, solution(9) == 2, ) ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/sjjyy.java ================================================ package lessons.lesson01.Iterations.BinaryGap; public class sjjyy { public static int solution(int n) { int gap = 0; int temp = 0; if (n == 1) return 0; // 1 = 0 char binary[] = Integer.toBinaryString(n).toCharArray(); // binary로 변환 후 char[] 배열 생성 int len = binary.length; for (int x = 0; x < len; x++) { if(binary[x] == '0') { temp++; // count 0 } else if(binary[x] == '1') // end { if(temp > gap) gap = temp; temp = 0; } } return gap; } public static int solution2(int n) // indexOf 방법 { int gap = 0; String binary = Integer.toBinaryString(n); int len = binary.length(); for(int x=0; x < len;) { int i = binary.indexOf("1", x+1); // search 1 if(i == -1) break; // 닫는 1이 없음 gap = Math.max(gap, i-x-1); // maxGap x=i; } return gap; } public static void main(String[] args) { System.out.println(solution(32) == 0); System.out.println(solution(1041) == 5); System.out.println(solution(9) == 2); System.out.println(solution(529) == 4); System.out.println(solution(20) == 1); System.out.println(solution(15) == 0); } } ================================================ FILE: codility_training/lessons.lesson01.Iterations.BinaryGap/test.json ================================================ [ { "input": [ 32 ], "output": 0 }, { "input": [ 1041 ], "output": 5 }, { "input": [ 9 ], "output": 2 }, { "input": [ 529 ], "output": 4 }, { "input": [ 20 ], "output": 1 }, { "input": [ 15 ], "output": 0 } ] ================================================ FILE: codility_training/lessons.lesson02.Arrays.CyclicRotation/JeongShin.js ================================================ function solution(A) { A.sort(); const len = A.length; for (let i = 0; i < len; i += 2) { if (A[i] != A[i + 1]) return A[i]; } } ================================================ FILE: codility_training/lessons.lesson02.Arrays.CyclicRotation/JunilHwang.java ================================================ package lessons.lesson02.Arrays.CyclicRotation; import java.util.Arrays; public class JunilHwang { public static int[] solution(int[] A, int K) { int len = A.length; int[] newA = new int[A.length]; for (int i = 0; i < len; i++) { newA[i] = A[(len - K + i) % len]; } return newA; } public static void main(String[] args) { System.out.println(Arrays.equals(solution(new int[]{3, 8,9,7,6},3), new int[]{9,7,6,3,8})); System.out.println(Arrays.equals(solution(new int[]{},0), new int[]{})); System.out.println(Arrays.equals(solution(new int[]{5, -1000},1), new int[]{-1000, 5})); System.out.println(Arrays.equals(solution(new int[]{3,8,9,7,6},5), new int[]{3,8,9,7,6})); System.out.println(Arrays.equals(solution(new int[]{3,8,9,7,6},0), new int[]{3,8,9,7,6})); } } ================================================ FILE: codility_training/lessons.lesson02.Arrays.CyclicRotation/README.md ================================================ # 출처 https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/ ================================================ FILE: codility_training/lessons.lesson02.Arrays.CyclicRotation/eyabc.js ================================================ function solution(arr, K) { if (arr && arr.length > 1) { for(let i = 0 ; i ( set[set.has(v) ? 'delete' : 'add'](v), set ), new Set) ][0] } console.log( solution([9, 3, 9, 3, 9, 7, 9]) === 7 ) ================================================ FILE: codility_training/lessons.lesson02.Arrays.OddOccurrencesInArray/khw970421.js ================================================ function solution(A) { const size = A.length; //A의 크기 const로 저장 var mySet = new Set(); //Set 객체 챗엇 for(let i=0;i set = new HashSet<>(); for(int i : A) { if (set.contains(i)) { //set에 i가 있다면 set.remove(i); //set에서 삭제 } else { //없다면 set.add(i); //set에 추가 } }//end of for loop return set.iterator().next(); }//end of solution2() } // end of class Solution public class pul8219 { public static void main(String[] args){ int A[] = {9,3,9,7,9,7,9}; Solution s = new Solution(); System.out.println(s.solution2(A)); } } // end of class pul8219 /* int len = A.length; int unpair = 0; for(int i = 0; i < len; i++){ if(A[i] == A[i + 2]) continue; else{ if(i + 2 < len) continue; unpair = A[i]; else break; } } // end of for loop */ ================================================ FILE: codility_training/lessons.lesson02.Arrays.OddOccurrencesInArray/sangmandu.py ================================================ def solution(A): sA = sorted(A) size = len(sA) if size == 0: return sA[2*i] for i in range(size // 2): if sA[2 * i] != sA[2 * i + 1]: return sA[2 * i] ================================================ FILE: codility_training/lessons.lesson02.Arrays.OddOccurrencesInArray/sjjyy.java ================================================ package lessons.lesson02.Arrays.OddOccurrencesInArray; public class sjjyy { public static int solution(int[] A) { int a = 0; int len = A.length; for (int i=0; i a + b); } ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.PermMissingElem/NowonLee.js ================================================ function solution(A) { // write your code in JavaScript (Node.js 8.9.4) var r = 0 const l = A.length; A.sort((a,b) => a-b) if(A[0] !== 1) return 1; else if(A[l-1] !== l+1) return l+1; for(var i=0;i a - b); for(; i < len; i++) { if(A[i] > (i+1)) return A[i]-1; if(A[i] < (i+1)) return A[i]+1; } return i; } /* from JeongShin */ function solution2(A) { if (!A) return; const len = A.length + 1; //원래 예상 합 const x = (1 + len) / 2 * len; //현재 배열 합 const y = A.reduce((sum, curr) => sum + curr); //missing num = 예상 합 - 현재 합 return x - y; } console.log( solution2([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]) === 11, solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]) === 11 ); ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.PermMissingElem/junilhwang.js ================================================ function solution(A) { let sum1 = 0, sum2 = 0 const last = A.length + 1; for (let i = 1; i < last; i++) { sum1 += i sum2 += A[i - 1] } return sum1 - sum2 + last } function solution2(A) { const idx = A.sort((a, b) => a - b).findIndex((v, k) => v !== k + 1) return (idx === -1 ? A.length : idx) + 1 } console.log( solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]) === 11, solution2([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]) === 11, solution([]) === 1, solution2([]) === 1, solution2([3]) === 1, ); ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.PermMissingElem/khw970421.js ================================================ function solution(A) { let sum1=0,sum2=0,size=A.length; let i; sum1=size*(size+1)/2; //1부터 N까지 더한다. sum2=A.reduce((a,b)=>a+b); //배열 범위에 존재하는 값들을 전부 더한다. sum1+=(size+1); //N+1도 존재하는것도 더해 전체 1~N+1까지의 총합을 구한다. return sum1-sum2; //전체 1~N+1중에서 빠진 하나의 값을 제외한 총합을 빼서 빠진 값을 구한다. } ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.PermMissingElem/pul8219.java ================================================ package lessons.lesson03.TimeComplexity.PermMissingElem; // 배열 A -> N개의 서로 다른 숫자 // 1 ~ N+1 의 정수를 포함, 한 가지 요소가 빠져있음 // 배열에서 빠진 요소를 리턴하는 함수 작성하기 import java.util.Arrays; class Solution{ public int solution(int[] A){ Arrays.sort(A); // 배열 A를 오름차순으로 정렬 for(int i = 0, len = A.length; i < len; i++){ // 배열 크기 만큼 반복 if(i+1 != A[i]) // 배열 A는 오름차순으로 정렬되어있으므로 i를 증가시켜가며 값이 달라지는 때 return i+1; // missing된 값을 리턴 } // 가장 큰 값이 missing 됐을 경우는 위의 for문에서 파악할 수 없으므로 따로 고려해줘야함 return A.length + 1; } } public class pul8219 { public static void main(String[] args){ int[] A = {3,2,1,4,5}; Solution s = new Solution(); System.out.println(s.solution(A)); } } ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.PermMissingElem/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass sum = sum(A) n = len(A) return (n + 2) * ((n + 1) // 2) + (0 if n % 2 == 1 else (n + 2) // 2) - sum print( solution([2,3,1,5]) == 4, # solution(A) == result, ) ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.PermMissingElem/sjjyy.java ================================================ package lessons.lesson03.TimeComplexity.permMissingElem; class sjjyy { public static int solution(int[] A) { int len = A.length; int a = 0, b = 0; for(int i = 1 ; i <= len + 1 ; i++) a += i; for(int j = 0 ; j < len ; j++) b += A[j]; return a - b; } public static void main(String[] args) { int[] A = new int[] {2, 1, 3, 5}; System.out.println(solution(A)); } } ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.TapeEquilibrium/JeongShin.js ================================================ function solution(A) { if (!A) return; const len = A.length; let P = 1; const arr = []; //reduce 가 반복문 안으로 들어가면 시간 복잡도가 n^2이 되기 때문에 빼준다. var diff = A[0] - A.slice(P).reduce((prev, curr) => prev + curr); //앞, 뒤 배열 차이를 현재 인덱스 (P) 기준으로 덧셈 뺄셈으로 계산 후 arr에 push while (P < len) { arr.push(diff); diff += A[P++] * 2; } return arr.reduce ((min, a)=> Math.min(Math.abs(a), min), Infinity); } var ans = solution([-1000, 1000]); console.log(ans); ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.TapeEquilibrium/README.md ================================================ https://app.codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/ ``` A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 P = 1, difference = |3 − 10| = 7 P = 2, difference = |4 − 9| = 5 P = 3, difference = |6 − 7| = 1 P = 4, difference = |10 − 3| = 7 ``` 최소 차이를 리턴하는 문제 ``` A non-empty array A consisting of N integers is given. Array A represents numbers on a tape. Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1]. The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])| In other words, it is the absolute difference between the sum of the first part and the sum of the second part. For example, consider array A such that: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 We can split this tape in four places: P = 1, difference = |3 − 10| = 7 P = 2, difference = |4 − 9| = 5 P = 3, difference = |6 − 7| = 1 P = 4, difference = |10 − 3| = 7 Write a function: class Solution { public int solution(int[] A); } that, given a non-empty array A of N integers, returns the minimal difference that can be achieved. For example, given: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 the function should return 1, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [2..100,000]; each element of array A is an integer within the range [−1,000..1,000]. ``` Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unau ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.TapeEquilibrium/eyabc.js ================================================ function solution(A) { let frontSum = 0; let backSum = A.reduce((sum, value) => sum + value); const len = A.length - 1; return A.reduce((min, v, k) => { if (k === len) return min; frontSum += v; backSum -= v; return Math.min(Math.abs(frontSum - backSum), min); }, Infinity); } console.log(solution([3, 1, 2, 4, 3]) === 1); console.log(solution([-1000, 1000]) === 2000); ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.TapeEquilibrium/junilhwang.js ================================================ function solution(A) { return A.slice(0, -1).reduce(([min, front, back], a) => [ Math.min(Math.abs(front - back + a * 2), min), front + a, back - a ], [ Infinity, 0, A.reduce((a, b) => a + b) ])[0] } console.log( solution([3, 1, 2, 4, 3]) === 1, solution([-1000, 1000]) === 2000, solution([1, 2]) === 1 ); ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.TapeEquilibrium/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass sum = leftA = sum(A) min = abs(sum - 2 * A[0]) for n in range(len(A)-1): leftA += A[n] min = min([abs(sum - 2 * leftA), min]) return min print( solution([3,1,2,4,3]) == 1, # solution(A) == result, ) ================================================ FILE: codility_training/lessons.lesson03.TimeComplexity.TapeEquilibrium/sjjyy.java ================================================ package lessons.lesson03.TimeComplexity.TapeEquilibrium; class Solution { public static int solution(int[] A) { int left = 0, right = 0, sum = 0; int result = Integer.MAX_VALUE; // 비교군으로 MAX값을 넣어야 min에서 최소값 도출 가능 int len = A.length; for(int i = 0; i < len ; i++) // 수정 sum += A[i]; for (int j = 1 ; j < len ; j++) { left += A[j-1]; right = sum - left; result = Math.min(result, Math.abs(left-right)); } return result; } public static void main(String[] args) { int[] A = new int[] {2, 1, 3, 5, 4, 6}; System.out.println(solution(A)); } } ================================================ FILE: codility_training/lessons.lesson04.CountingElements.FrogRiverOne/JeongShin.js ================================================ function solution(X, A) { if (X === 0 || !A) return; const set = Array.from(new Set(A)); const len = set.length; if (len!==X) return -1; else{ return A.indexOf(set[len-1]); } } console.log(solution(5, [1, 3, 1, 4, 2, 3, 5, 4])); ================================================ FILE: codility_training/lessons.lesson04.CountingElements.FrogRiverOne/README.md ================================================ # 출처 https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/ ================================================ FILE: codility_training/lessons.lesson04.CountingElements.FrogRiverOne/eyabc.js ================================================ function solution (X, A) { const set = new Set(); const len = A.length(); for (let i = 0; i < len; i++) { set.add(A[i]); if(set.size === X) return i; } return -1; } console.log( solution(5, [1, 3, 1, 4, 2, 3, 5, 4]) === 6, solution(5, [1, 1, 1, 1, 2, 3, 4, 5]) === 7, ); // timeout function solution2 (X, A) { let time = -1; let count = 0; const locateArr = []; const f = () => { if (locateArr.includes(count + 1)) { count++; f(); } return; }; while (count < X) { time++; locateArr.push(A.shift()); f(); } return time; } // spent : Array.prototype.includes > indexOf function solution2 (X, A) { let time = -1; let location = 0; if (A.length < X) return -1; while (location < X) { const newLocation = A.indexOf(++location); if (newLocation === -1) return -1; else if (newLocation > time) { time = newLocation; } } return time; } ================================================ FILE: codility_training/lessons.lesson04.CountingElements.FrogRiverOne/junilhwang.js ================================================ function solution(X, A) { const set = new Set() const len = A.length for (let i = 0; i < len; i++) { // O(n) set.add(A[i]) if (set.size === X) return i } return -1 } console.log(solution(1, [1]) === 0) console.log(solution(5, [1, 3, 1, 4, 2, 3, 5, 4]) === 6) console.log(solution(5, [1, 2, 3, 4, 4]) === -1) console.log(solution(4, [1, 2, 3, 4, 4]) === 3) console.log(solution(4, [1, 2, 3, 4, 5, 6, 7, 8]) === 3) console.log(solution(3, [1, 3, 1, 3, 2, 1, 3]) === 4) ================================================ FILE: codility_training/lessons.lesson04.CountingElements.FrogRiverOne/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(X, A): # write your code in Python 3.6 pass sA = set([]) for idx in range(len(A)): sA.add(A[idx]) if(len(sA) == X): return idx return -1 print( solution(5,[1,3,1,4,2,3,5,4]) == 6, # solution(X,A) == result, ) ================================================ FILE: codility_training/lessons.lesson04.CountingElements.FrogRiverOne/sjjyy.java ================================================ package lessons.lesson04.CountingElements.FrogRiverOne; class Solution { public static int solution(int X, int[] A) { int[] set = new int[X]; int leaf = 0, len = A.length; for (int i = 0 ; i < len ; i++) { int a = A[i]; if (a <= X) { if(set[a-1] == 0) { set[a-1] = 1; leaf++; } if(leaf == X) return i; } } if (leaf != X) return -1; return 0; } public static void main(String[] args) { int[] A = new int[] {1, 3, 1, 4, 2, 3, 5, 4}; System.out.println(solution(4, A)); } } ================================================ FILE: codility_training/lessons.lesson04.CountingElements.MaxCounters/JeongShin.js ================================================ /*스스로 작성한코드*/ function solution(N, A) { if (!A || N === 0) return; const arr = new Array(N+1).fill(0); // arr[0]에는 max 값을 넣는데 사용하였습니다. for (const val of A){ if (val===N+1){ //fill 함수가 arr 를 iterate하기 때문에 이 부분에서 performance가 저하 된다. arr.fill(arr[0]); } else { if (arr[0]<++arr[val]) arr[0]=arr[val]; } } return arr.slice(1); } solution(5, [3,4,4,6,1,4,4]); /*@JunilHwang 형의 코드를 참고하여 작성한 코드*/ function solution(N, A) { if (!A || N === 0) return; const counters = new Array(N).fill(0); let prev_max = 0, curr_max = 0; for (const val of A) { if (1 <= val && val <= N) { let idx = val - 1; counters[idx] = Math.max(counters[idx], prev_max) counters[idx]++; curr_max = Math.max(curr_max, counters[idx]); } else if (val === N + 1) { prev_max = curr_max; } } return counters.map(el => el < prev_max ? prev_max : el); } let counters = solution(5, [3, 4, 4, 6, 1, 4, 4, 6, 4, 5]); console.log(counters); ================================================ FILE: codility_training/lessons.lesson04.CountingElements.MaxCounters/README.md ================================================ https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/ ================================================ FILE: codility_training/lessons.lesson04.CountingElements.MaxCounters/eyabc.js ================================================ function solution(N, A) { let max = 0, maxSave = 0; const arr = new Array(N).fill(0); for(const v of A) { if (v > N) maxSave = max; else { arr[v-1] = Math.max(arr[v-1], maxSave) + 1; max = Math.max(arr[v-1], max); } } return arr.map(v => Math.max(v, maxSave)); } console.log( solution(5, [3, 4, 4, 6, 1, 4, 4]).toString() ===[3, 2, 2, 4, 2].toString() ); /* timeout O(N^2)*/ function solution2(N, A) { const aLen = A.length; const arr = new Array(N).fill(0); // O(n) for (let i = 0; i < aLen; i++) { // O(n) const value = A[i]; if (value > N) arr.fill(Math.max(...arr)); // O(n) else arr[value-1]++; } return arr; } ================================================ FILE: codility_training/lessons.lesson04.CountingElements.MaxCounters/junilhwang.js ================================================ function solution(N, A) { let start = 0, max = 0 const arr = new Array(N).fill(0) for (const v of A) { if (N < v) { start = max continue } arr[v-1] = Math.max(arr[v-1], start) + 1 max = Math.max(arr[v-1], max) } return arr.map(v => Math.max(v, start)) } console.log( solution(5, [3,4,4,6,1,4,4]).toString() === [3,2,2,4,2].toString() ) ================================================ FILE: codility_training/lessons.lesson04.CountingElements.MaxCounters/khw970421.js ================================================ //large size time out function solution(N, A) { const arrNumber = new Array().fill(0); //배열선언 let max=0; for(let i=0;iN){ arrNumber.fill(max); } else{ arrNumber[value-1]++; max=Math.max(arrNumber[value-1],max); } },0); return arrNumber; } //준일형 소스코드 이해 function solution1(N, A) { let max = 0, Save = 0; const arr = new Array(N).fill(0); for(const v of A) { //A의 배열값을 v에 저장해 실행 if (v > N) Save = max; //배열값이 N 한계치보다 크다면 실행 else { arr[v-1] = Math.max(arr[v-1], Save) + 1; //Save랑 arr[v-1]의 값을 비교해 큰값에 1을 더한것을 저장 max = Math.max(arr[v-1], max); //변한값과 max 비교해 큰값을 max에 저장 } } return arr.map(v => Math.max(v, Save)); //arr의 배열값중에 Save보다 작은값은 Save로 채우기 } console.log(solution(5, [3, 4, 4, 6, 1, 4, 4]).toString()=== [3, 2, 2, 4, 2].toString()); ================================================ FILE: codility_training/lessons.lesson04.CountingElements.MaxCounters/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(N, A): # write your code in Python 3.6 pass arr = [0] * N tog = 0 mx = 0 for i in A: if(i == N+1): if(tog == 0): tog = 1 arr = [mx] * N continue arr[i-1] += 1 mx = max(arr[i-1], mx) tog = 0 return arr print( solution(1,[1,1,1,2]) == [3] # solution(X,A) == result, ) ''' print( solution(5,[3,4,4,6,1,4,4]) == [3,2,2,4,2] # solution(X,A) == result, ) ''' ================================================ FILE: codility_training/lessons.lesson04.CountingElements.MaxCounters/sjjyy.java ================================================ package lessons.lesson04.CountingElements.MaxCounters; import java.util.*; class sjjyy { public static int[] solution(int N, int[] A) // 솔루션 참고 { int tmp = 0; int fin = 0; int[] B = new int[N]; int a = A.length, b = B.length; for (int k = 0; k < a; k++) { int n = A[k] - 1; if (1 <= A[k] && A[k] <= N) { B[n] = Math.max(B[n], fin); B[n] += 1; tmp = Math.max(tmp, B[n]); } else if (A[k] == N + 1) fin = tmp; } for(int i = 0 ; i < b; i++) B[i] = Math.max(B[i], fin); return B; } public static int[] solution2(int N, int[] A) // 솔루션 { int n = A.length; int curr = 0; int done = 0; int[] counters = new int[N]; for(int i = 0; i < n ; i++) { if(A[i] > N) done = curr; else { if (counters[(A[i] - 1)] < done) counters[(A[i] - 1)] = done; counters[(A[i] - 1)]++; if (counters[(A[i] - 1)] > curr) curr = counters[(A[i] - 1)]; } } for(int i = 0; i < N ; i++) { if(counters[i] < done) counters[i] = done; } return counters; } public static void main(String[] args) { int[] A = new int[] {3, 4, 4, 6, 1, 4, 4}; System.out.println(Arrays.toString(solution(5, A))); } } ================================================ FILE: codility_training/lessons.lesson04.CountingElements.MissingInteger/JeongShin.js ================================================ function solution(A) { const set = Array.from(new Set(A)).sort((a,b)=> a-b); /*const set = Array.from(new Set(A).sort() -> 로 하면 제대로 오름차순 정렬이 안되더라고요. * 제가 알기론 int값을 포함한 array는 자동으로 오름차순 sort 하는거로 알고 있는데 혹시 시는분 코드 리뷰 부탁드려요*/ const len = set.length; if (len === 0) return 1; let missing = 1; for (const val of set) { //missing보다 작은 val는 무시 if (val >= missing) { if (val - missing !== 0) return missing; else missing++; } } return missing; } let sol1 = solution([0,1,2,4,3,5, 100]); console.log(sol1); ================================================ FILE: codility_training/lessons.lesson04.CountingElements.MissingInteger/NowonLee.js ================================================ function solution(A) { const o = {} const mx = Math.max(...A) if(m<1) return 1 A.forEach((a) => { if(a>0) o[a] = true; }) var m = mx for(var j=1;j a-b).find((val , idx)=> val - 1 !== idx))*1; } ================================================ FILE: codility_training/lessons.lesson04.CountingElements.PermCheck/README.md ================================================ https://app.codility.com/programmers/lessons/4-counting_elements/perm_check/ ``` A non-empty array A consisting of N integers is given. A permutation is a sequence containing each element from 1 to N once, and only once. For example, array A such that: A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2 is a permutation, but array A such that: A[0] = 4 A[1] = 1 A[2] = 3 is not a permutation, because value 2 is missing. The goal is to check whether array A is a permutation. Write a function: class Solution { public int solution(int[] A); } that, given an array A, returns 1 if array A is a permutation and 0 if it is not. For example, given array A such that: A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2 the function should return 1. Given array A such that: A[0] = 4 A[1] = 1 A[2] = 3 the function should return 0. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [1..1,000,000,000]. Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized ``` permutation 한지 묻는 문제입니다. true 이면 1 false 이면 0 을 반환하면됩니다. 만약 배열의 길이가 4일때, 요소가 1 ~ 4 를 가지고 있다면 1을 반환하고 배열길이가 3일 때는 1~3 을가지고 있어야 한다. 그 외 요소를 가지고 있거나 가지고 있지 않다면 0을 반환합니다 ================================================ FILE: codility_training/lessons.lesson04.CountingElements.PermCheck/eyabc.js ================================================ function solution(A) { const aLen = A.length; A.sort((a,b) => a-b); for(let i = 0; i < aLen ;) { if (A[i] !== ++i) return 0; } return 1; } console.log( solution( [4, 1, 3, 2]) === 1, solution([4, 1, 3]) === 0 ); ================================================ FILE: codility_training/lessons.lesson04.CountingElements.PermCheck/junilhwang.js ================================================ function solution(A) { return !(A.sort((a, b) => a - b).find((v, k) => v - 1 !== k)) * 1 } function solution2(A) { return (A.sort((a,b)=>a-b).reduce(([acc, count], val) => { if(val - acc !== 1) return [-1, 0]; count++; return [val,count]; }, [ 0, 0 ])[1] === A.length) * 1 } console.log( solution2( [4, 1, 3, 2]) === 1, solution2([4, 1, 3]) === 0, ) ================================================ FILE: codility_training/lessons.lesson04.CountingElements.PermCheck/khw970421.js ================================================ //직접만든코드 function solution(A) { let count=0; A.sort((a,b)=>a-b); //순서대로 분류 A.reduce(function(accumulator,currentvalue){ //accumulator 0으로 설정 currentvalue A[0]으로 시작 if(currentvalue-accumulator!=1) // 둘의 차이가 1이 아니면 함수종료 return -1; //둘의 차이가 1이면 count증가와 currentvalue값을 accumulator값으로 return count++; return currentvalue; },0) return (count==A.length)?1:0; //배열을 reduce에서 전부 순회하여 count와 A.length가 같으면 1 return 아니면 0 return } //피드백 받은코드1 function solution2(A) { return (A.sort((a,b)=>a-b).reduce(([acc, count], val) => { //accumulator 0으로 설정 currentvalue A[0]으로 시작 if(val - acc !== 1) // 둘의 차이가 1이 아니면 함수종료 console.log([1]-[1]==0); 결과 true return [-1,0]; //둘의 차이가 1이면 count증가와 currentvalue값을 accumulator값으로 return count++; return [val,count]; }, [ 0, 0 ])[1] === A.length); //배열을 reduce에서 전부 순회하여 count와 A.length가 같으면 1 return 아니면 0 return } //피드백 받은코드2 function solution3(A){ return !(A.sort((a, b) => a - b).find(function(v, k){ return (v - 1 !== k);} //1부터 나열했을때 값 - 1 이 index값이랑 같지않은값(순열이 아닐때)이 있으면 return에 false를 만든다 )); } //true false를 1,0으로 변환하려면 *1을한다. true * 1 = 1 , false * 1 = 0 console.log(solution3([4, 1, 3, 2])==1); console.log(solution([4, 1, 3])==0); console.log(solution2([4, 1, 3])==0); console.log(solution3([4, 1, 3])==0); ================================================ FILE: codility_training/lessons.lesson04.CountingElements.PermCheck/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass A.sort() for i in range(len(A)): if i+1 != A[i]: return 0 return 1 print( solution([4, 1, 3, 2]) == 1, solution([4, 1, 3]) == 0 ) ================================================ FILE: codility_training/lessons.lesson04.CountingElements.PermCheck/sjjyy.java ================================================ package lessons.lesson04.CountingElements.PermCheck; import java.util.*; class sjjyy { public static int solution(int[] A) { Arrays.sort(A); int len = A.length; for(int i = 0 ; i < len ; i++) { if(A[i] != i + 1) return 0; } return 1; } public static void main(String[] args) { int[] A = new int[] {1, 3, 1, 4, 2, 3, 5, 4}; int[] B = new int[] {1, 4, 2, 3}; System.out.println(solution(A)); System.out.println(solution(B)); } } // ================================================ FILE: codility_training/lessons.lesson05.PrefixSum.GenomicRangeQuery/JeongShin.js ================================================ // Performance 측면에서 0 점 받았습니다 ㅜㅜ, 여러가지 방법으로 다 시도해봤지만 계속 0점이라 // @eyabc.js 님이 올리신 코드 보고 공부했습니다. function solution(S, P, Q) { return Q.map((q, k) => { const val = S.slice(P[k], q+1); if(val.indexOf('A') !== -1) return 1; else if (val.indexOf('C') !== -1) return 2; else if (val.indexOf('G') !== -1) return 3; else if (val.indexOf('T') !== -1) return 4; }); } /*제가 한 풀이 */ function solution2(S, P, Q) { const len = P.length; const arr = []; const map = char => { switch (char) { case 'A': return 1; case 'C': return 2; case 'G': return 3; case 'T': return 4; } }; for (let i = 0; i < len; i++) { const s = Array.from(new Set(S.substring(P[i], Q[i] + 1))); s.sort((a, b) => a.charCodeAt(0)-b.charCodeAt(0)); arr.push(map(s[0])); } return arr; } ================================================ FILE: codility_training/lessons.lesson05.PrefixSum.GenomicRangeQuery/README.md ================================================ https://app.codility.com/programmers/lessons/5-prefix_sums/genomic_range_query/ ```javascript function solution(S, P, Q) { // write your code in JavaScript (Node.js 8.9.4) return [] } solution('CAGCCTA', [2, 5, 0], [4, 5, 6]).toString() === [2, 4, 1].toString() ``` P[0] = 2 Q[0] = 4 P[1] = 5 Q[1] = 5 P[2] = 0 Q[2] = 6 A, C, G and T의 각 영향력은 1,2 ,3, 4 이다. P[0] 의 값 2 와 Q[0] 의 값 4 인덱스 사이의 문자열 값은 gcc 의 영향력은, 3,2,2 이다. 이중 최소 는 2 이고. RETURN할 배열의 0번째 요소값이 된다. ... 이런식으로 반복하여 [ 2, 3, 1] 을 얻을 수 있다. A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence. Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively. You are going to answer several queries of the form: What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence? The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 ≤ K < M) requires you to find the minimal impact factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K] (inclusive). For example, consider string S = CAGCCTA and arrays P, Q such that: P[0] = 2 Q[0] = 4 P[1] = 5 Q[1] = 5 P[2] = 0 Q[2] = 6 The answers to these M = 3 queries are as follows: The part of the DNA between positions 2 and 4 contains nucleotides G and C (twice), whose impact factors are 3 and 2 respectively, so the answer is 2. The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4. The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1. Write a function: class Solution { public int[] solution(String S, int[] P, int[] Q); } that, given a non-empty string S consisting of N characters and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M integers specifying the consecutive answers to all queries. Result array should be returned as an array of integers. For example, given the string S = CAGCCTA and arrays P, Q such that: P[0] = 2 Q[0] = 4 P[1] = 5 Q[1] = 5 P[2] = 0 Q[2] = 6 the function should return the values [2, 4, 1], as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; M is an integer within the range [1..50,000]; each element of arrays P, Q is an integer within the range [0..N − 1]; P[K] ≤ Q[K], where 0 ≤ K < M; string S consists only of upper-case English letters A, C, G, T. ``` ================================================ FILE: codility_training/lessons.lesson05.PrefixSum.GenomicRangeQuery/eyabc.js ================================================ /* https://github.com/yaseenshaik/codility-solutions-javascript/blob/master/GenomicRangeQuery.md * 어려워서 구글링을 하였다. */ function solution(S, P, Q) { return Q.map((q, k) => { const val = S.slice(P[k], q+1); if(val.indexOf('A') !== -1) return 1; else if (val.indexOf('C') !== -1) return 2; else if (val.indexOf('G') !== -1) return 3; else if (val.indexOf('T') !== -1) return 4; }); } console.log( // solution('TC', [0, 0, 1], [0, 1, 1]), solution('TC', [0, 0, 1], [0, 1, 1]).toString() ===[4, 2, 2].toString(), solution('CAGCCTA', [2, 5, 0], [4, 5, 6]).toString() === [2, 4, 1].toString(), solution('AC', [0, 0, 1], [0, 1, 1]).toString() === [1, 1, 2].toString() ); /* time out */ function solution2(S, P, Q) { const len = P.length; const arr = []; const sString = S.split('').map(v => { switch (v) { case 'A' : return 1; case 'C' : return 2; case 'G' : return 3; case 'T' : return 4; } }); for(let i = 0; i < len; i++) { arr.push(Math.min(...sString.slice(P[i], Q[i]+1))); } return arr } ================================================ FILE: codility_training/lessons.lesson05.PrefixSum.GenomicRangeQuery/junilhwang.js ================================================ function solution(S, P, Q) { return P.map((start, k) => { const end = Q[k] const A = S.indexOf('A', start) if ( A !== -1 && A <= end) return 1 const C = S.indexOf('C', start) if ( C !== -1 && C <= end) return 2 const G = S.indexOf('G', start) if ( G !== -1 && G <= end) return 3 const T = S.indexOf('T', start) if ( T !== -1 && T <= end) return 4 }) } function solution2(S, P, Q) { return P.map((start, k) => { const str = S.substring(start, Q[k] + 1) if ( str.indexOf('A') !== -1 ) return 1; if ( str.indexOf('C') !== -1 ) return 2; if ( str.indexOf('G') !== -1 ) return 3; if ( str.indexOf('T') !== -1 ) return 4; }) } require("./test.json") .forEach(({ input, output }) => console.log(solution2(...input).toString() === output.toString()) ) ================================================ FILE: codility_training/lessons.lesson05.PrefixSum.GenomicRangeQuery/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(S, P, Q): # write your code in Python 3.6 pass ret = [] for i in range(len(P)): temp = S[P[i]:Q[i] + 1] if temp.find("A") != -1: ret.append(1) elif temp.find("C") != -1: ret.append(2) elif temp.find("G") != -1: ret.append(3) else: ret.append(4) return ret print( solution('A', [0], [0]) == [1] ) print( solution('CAGCCTA', [2, 5, 0], [4, 5, 6]) == [2, 4, 1] ) ================================================ FILE: codility_training/lessons.lesson05.PrefixSum.GenomicRangeQuery/test.json ================================================ [ { "input": ["TC", [0, 0, 1], [0, 1, 1]], "output": [4, 2, 2] }, { "input": ["CAGCCTA", [2, 5, 0], [4, 5, 6]], "output": [2, 4, 1] }, { "input": ["AC", [0, 0, 1], [0, 1, 1]], "output": [1, 1, 2] } ] ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.CountDiv/JeongShin.js ================================================ /*처음 작성한 코드*/ function solution(A, B, K) { // A랑 가장 가까운 범위 내 숫자 const start = A % K ? A + K - A % K : A; // B랑 가장 가까운 범위 내 숫자 const end = B - B % K; if (end >= start) return (end - start) / K + 1; else return 0; } /*@eyabc 님 코드보고 훨씬 가독성도 좋고 효율적인거 같아서 다시 작성해보았습니다.*/ // function solution2(A, B, K) { // B까지 총 K 배수의 개수 const rear = Math.floor(B / K); const front = Math.floor(A / K) - (A % K ? 0 : 1); return (Math.floor(B / K) - Math.floor(A / K) - (A % K ? 0 : 1)); // 이렇게 하면 왜 아예 다른 결과가 나오는지 잘 모르겠네요 ㅠ // return rear - front; } function solution3(A, B, K) { if (A === B) return B % K === 0 ? 1 : 0; return ~~(B / K) - ~~(A / K) - (A % K ? 0 : 1); } console.log(solution3(3, 10, 4)); ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.CountDiv/README.md ================================================ https://app.codility.com/programmers/lessons/5-prefix_sums/count_div/ * good lecture https://www.youtube.com/watch?v=scD312I7kkE ``` Write a function: class Solution { public int solution(int A, int B, int K); } that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.: { i : A ≤ i ≤ B, i mod K = 0 } For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10. Write an efficient algorithm for the following assumptions: A and B are integers within the range [0..2,000,000,000]; K is an integer within the range [1..2,000,000,000]; A ≤ B. ``` 정수 인수 , A, B ,K 가 주어지고, A <= B 입니다. 이 범위 사이의 수 중 (A<= i <= B) 가 K로 나누었을 때 나머지가 0이 되는 수의 갯수를 return 하는 문제입니다. ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.CountDiv/eyabc.js ================================================ function solution(A, B, K) { if (A === B) return B % K === 0 ? 1 : 0; const f = ~~(B / K); const s = ~~(A / K) - (A % K ? 0 : 1) return f- s; } console.log( solution(11, 13, 2) === 1, solution(10, 10, 7) === 0, solution(0, 0, 11) === 1 ) ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.CountDiv/junilhwang.js ================================================ /** * 정수 인수 A, B ,K 가 주어지고, A <= B 입니다. * 이 범위 사이의 수 중 (A <= i <= B) 가 K로 나누었을 때 나머지가 0이 되는 수의 갯수를 return 하는 문제입니다. */ function solution (A, B, K) { return ~~(B / K) - ~~(A / K) + !!(A % K === 0) } const testCase = require("./test.json") testCase.forEach(({ input, output }) => console.log(solution(...input), output)) ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.CountDiv/khw970421.js ================================================ //처음 시도한 성공결과 => 성능에서 50점 function solution(A, B, K) { const k=[]; let p=0; for(let i=A;i<=B;i++){ k[p]=i; p++; } let count; count=k.filter(element=>element%K==0); return count.length; } //성능을 높이기 위해 한 최종코드 function solution1(A, B, K) { return Math.floor(B/K)-Math.ceil(A/K)+1; //A랑B가 나눠떨어지면 나눈 크기들의 차+1로 갯수를 구하고 //A가 안나눠지면 A가 갯수에 포함이 안되게 ceil로 올려주고 //B가 안나눠지면 B가 갯수에 포함이 안되게 floor해준다. } console.log(solution1(6,10,2)==3); console.log(solution1(7,10,2)==2); console.log(solution1(5,10,3)==2); ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.CountDiv/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A, B, K): # write your code in Python 3.6 pass return B // K - A // K + (1 if A % K == 0 else 0) print( solution(6, 12, 2) == 4 ) ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.CountDiv/sjjyy.java ================================================ package lessons.lesson05.PrefixSums.CountDiv; class sjjyy { public static int solution(int A, int B, int K) // 수학적으로 접근 { return (B / K) - (A / K) + (A % K == 0 ? 1 : 0); } public static int solution0(int A, int B, int K) // 문제 그대로만 풀었을 때 { int c = 0; for (int i = A ; i <= B ; i++) { if (i % K == 0) c++; } return c; } public static void main(String[] args) { System.out.println(solution(1, 5, 3)); System.out.println(solution(6, 11, 2)); } } ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.CountDiv/test.json ================================================ [ { "input": [11, 13, 2], "output": 1 }, { "input": [10, 10, 7], "output": 0 }, { "input": [0, 0, 11], "output": 1 }, { "input": [3, 10, 4], "output": 2 }, { "input": [2, 3, 1], "output": 2 }, { "input": [2, 4, 2], "output": 2 } ] ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.GenomicRangeQuery/README.md ================================================ https://app.codility.com/programmers/lessons/5-prefix_sums/genomic_range_query/ ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.GenomicRangeQuery/eyabc.js ================================================ /* https://github.com/yaseenshaik/codility-solutions-javascript/blob/master/GenomicRangeQuery.md * 어려워서 구글링을 하였다. */ function solution(S, P, Q) { return Q.map((q, k) => { const val = S.slice(P[k], q+1); if(val.indexOf('A') !== -1) return 1; else if (val.indexOf('C') !== -1) return 2; else if (val.indexOf('G') !== -1) return 3; else if (val.indexOf('T') !== -1) return 4; }); } console.log( // solution('TC', [0, 0, 1], [0, 1, 1]), solution('TC', [0, 0, 1], [0, 1, 1]).toString() ===[4, 2, 2].toString(), solution('CAGCCTA', [2, 5, 0], [4, 5, 6]).toString() === [2, 4, 1].toString(), solution('AC', [0, 0, 1], [0, 1, 1]).toString() === [1, 1, 2].toString() ); /* time out */ function solution2(S, P, Q) { const len = P.length; const arr = []; const sString = S.split('').map(v => { switch (v) { case 'A' : return 1; case 'C' : return 2; case 'G' : return 3; case 'T' : return 4; } }); for(let i = 0; i < len; i++) { arr.push(Math.min(...sString.slice(P[i], Q[i]+1))); } return arr } ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.GenomicRangeQuery/khw970421.js ================================================ //정확성은 만족하나 효율성에서 문제 function solution(S, P, Q) { let k=[]; const o=[]; for(let i=0;i= 0) sub = arr[x - 1][a]; if (arr[y][a] - sub > 0) { result[i] = a + 1; break; } } } return result; } public static void main(String[] args) { String S = "CAGCCTA"; int[] P = { 2, 5, 0 }; int[] Q = { 4, 5, 6 }; int[] solution1 = solution(S, P, Q); for (int i : solution1) System.out.print(i + " "); } } ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.MinAvgTwoSlice/JeongShin.js ================================================ function solution(A) { const len = A.length; let i = 0; const min = []; let glob_min = Infinity; while (i < len - 1) { let sum = A[i]; let min_avg = Infinity; for (let j = i + 1; j < i + 3; j++) { sum += A[j]; min_avg = Math.min(min_avg, sum / (j - i + 1)) } glob_min = Matn.min(glob_min, min_avg) min[i] = min_avg; i++; } return min.indexOf(glob_min); } solution([4, 2, 2, 5, 1, 5, 8]); ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.MinAvgTwoSlice/README.md ================================================ [링크](https://app.codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice/) ## 문제설명 * 입출력 함수 ``` function solution(A) { return 0 } console.log(solution([4, 2, 2, 5, 1, 5, 8]) === 1); ``` * 아이디어 ``` (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1). ``` * 예시 주어진 배열입니다. ``` A[0] = 4 A[1] = 2 A[2] = 2 A[3] = 5 A[4] = 1 A[5] = 5 A[6] = 8 ``` slice 메서드를 실행했을 때. 배열 내에서 임의의 인덱스의 시작과 끝을 정합니다. 그리고 slice된 배열의 요소의 평균값을 구합니다. 단, 0 ≤ 시작인덱스 < 끝인덱스 입니다. ``` slice (1, 2), whose average is (2 + 2) / 2 = 2; slice (3, 4), whose average is (5 + 1) / 2 = 3; slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5 ``` 이중 평균이 가장 작을 때의 시작 값을 반환하면 됩니다. ## 원문 ``` A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1). For example, array A such that: A[0] = 4 A[1] = 2 A[2] = 2 A[3] = 5 A[4] = 1 A[5] = 5 A[6] = 8 contains the following example slices: slice (1, 2), whose average is (2 + 2) / 2 = 2; slice (3, 4), whose average is (5 + 1) / 2 = 3; slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5. The goal is to find the starting position of a slice whose average is minimal. Write a function: class Solution { public int solution(int[] A); } that, given a non-empty array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice. For example, given array A such that: A[0] = 4 A[1] = 2 A[2] = 2 A[3] = 5 A[4] = 1 A[5] = 5 A[6] = 8 the function should return 1, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [2..100,000]; each element of array A is an integer within the range [−10,000..10,000]. ``` ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.MinAvgTwoSlice/eyabc.js ================================================ let min = [Infinity, Infinity]; let num = 1; function solution(A) { if (A.length === 2) return 0; num++; min = A.reduce(([min, minIdx], v, k) => { if(!A[k+num-1]) return [min, minIdx]; const newValue = v + A[k+1] + (num === 3 ? A[k+2] : 0); const lastValue = Math.min(min, newValue / num); return [lastValue, lastValue !== min ? k : minIdx]; }, min); if (num === 2) solution(A); return min[1]; } function solution2(A) { if (A.length === 2) return 0; let min = A.reduce(([ min, minIdx ], v, k) => { if(!A[k+1]) return [ min, minIdx ]; const newValue = v + A[k+1]; const lastValue = Math.min(min, newValue / 2); return [lastValue, lastValue !== min ? k : minIdx]; }, [Infinity, Infinity]); min = A.reduce((oldValue, v, k) => { if(!A[k+2]) return oldValue; const newValue = v + A[k+1] + A[k+2]; const lastValue = Math.min(oldValue[0], newValue / 3); return [lastValue, lastValue !== oldValue[0] ? k : oldValue[1]]; }, min); return min[1]; } console.log( solution([4, 2, 2, 5, 1, 5, 8]) === 1, solution([-10000, -10000]) === 0, solution([-3, -5, -8, -4, -10]) === 2, ); ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.MinAvgTwoSlice/junilhwang.js ================================================ /** * 평균이 최소인 Slice의 시작 위치 * @param A */ function solution(A) { const len = A.length const sum = (a, b) => a + b let min = Infinity, i = 0, resolve = -1 do { const arr1 = A.slice(i, i + 2), avg1 = arr1.reduce(sum) / arr1.length const arr2 = A.slice(i, i + 3), avg2 = arr2.reduce(sum) / arr2.length let tmp = Math.min(avg1, avg2, min) if (tmp !== min) ([ resolve, min ] = [ i, tmp ]) i += 1 } while (i < len - 1) return resolve } const testCase = require("./test.json") testCase.forEach(({ input, output }) => console.log(input.toString(), '\n', solution(...input), output)) ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.MinAvgTwoSlice/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass mn2 = sum(A[0:2]) / 2 idx2 = idx3 = 0 for i in range(1, len(A)-1): if mn2 > sum(A[i:i+2]) / 2: mn2 = sum(A[i:i+2]) / 2 idx2 = i if(len(A) >= 3): mn3 = sum(A[0:3]) / 3 for i in range(1, len(A)-2): if mn3 > sum(A[i:i+3]) / 3: mn3 = sum(A[i:i+3]) / 3 idx3 = i return idx2 if sum(A[idx2:idx2+2])/2 <= sum(A[idx3:idx3+3])/3 else idx3 return idx2 print( solution([-1,-1,0,-1,1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,0,0,0]) ) ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.MinAvgTwoSlice/sjjyy.java ================================================ package lessons.lesson05.PrefixSums.MinAvgTwoSlice; public class sjjyy { public static int solution(int[] A) { int len = A.length; double min = (A[0] + A[1]) / 2.0; int index = 0; // 평균은 a+...+b/n로 계산하며, a+b/2에서 a<=b이면 평균은 a보다 크거나 같다. // 따라서 a+b+c+d/4인 경우 (a+b)+(c+d)의 평균은 (a+b)<=(c+d)일 때 (a+b) 이상이 된다. // 문제에서 최소 원소 개수가 2개 이상이므로 2개와 3개인 그룹만 비교하면 된다. for(int i = 2 ; i < len ; i++) { if((A[i-1] + A[i]) / 2.0 < min) { min = (A[i-1] + A[i]) / 2.0; index = i-1; } if((A[i-2] + A[i-1] + A[i]) / 3.0 < min) { min = (A[i-2] + A[i-1] + A[i]) / 3.0; index = i-2; } } return index; } public static void main(String[] args) { int [] A ={4, 2, 2, 5, 1, 5, 8}; System.out.println(solution(A)); } } ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.MinAvgTwoSlice/test.json ================================================ [ { "input": [[4,2,2,5,1,5,8]], "output": 1 }, { "input": [[-10000, -10000]], "output": 0 }, { "input": [[-3, -5, -8, -4, -10]], "output": 2 } ] ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.PassingCars/JeongShin.js ================================================ function solution(A) { let othercar = A.reduce((acc, curr) => acc + (curr !== A[0])); let cars = 0; A.forEach(el => !el ? othercar-- : cars += othercar); return cars < 1000000001 ? cars : -1; } ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.PassingCars/README.md ================================================ [문제출처](https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars/) ## 입출력 ```javascript function solution(A) { // write your code in JavaScript (Node.js 8.9.4) return 1 } console.log( solution([0, 1, 0, 1, 1]) === 5 ); ``` ## 문제 설명 (값인 0인 요소의 인덱스, 값이 1인 요의 인덱스) 쌍의 경우의 수 구하기 0 <= 값인 0인 요소의 인덱스 < 값이 1인 요의 인덱스 쌍의 수가 1,000,000,000을 초과하면이 함수는 -1을 반환 ```text A [0] = 0 A [1] = 1 A [2] = 0 A [3] = 1 A [4] = 1 (0, 1), (0, 3), (0, 4), (2, 3), (2, 4) ``` ## 번역 ```text N 개의 정수로 구성된 비어 있지 않은 배열 A가 제공됩니다. 배열 A의 연속 요소는 도로의 연속 자동차를 나타냅니다. 배열 A에는 0 및 / 또는 1 만 포함됩니다. 0은 동쪽으로 여행하는 자동차를 나타냅니다. 1은 서쪽으로 여행하는 자동차를 나타냅니다. 목표는 지나가는 자동차를 세는 것입니다. P가 동쪽으로 여행하고 Q가 서쪽으로 여행 할 때 0 ≤ P -1; i--) { if (A[i] === 0) res += count; if (A[i] === 1) count++; } return res < 1000000001 ? res : -1; } console.log( solution([0, 1, 0, 1, 1]) === 5 ); ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.PassingCars/junilhwang.js ================================================ function solution (A) { let sum = 0, inc = 0 for (const v of A) { [() => inc += 1, () => sum += inc][v](); if (sum > 1000000000) return -1 } return sum } const assert = require('assert') require('./test.json').forEach(([ input ,output ]) => { assert.deepEqual(solution(...input), output) }) ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.PassingCars/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass zero_cnt = A.count(0) one_cnt = len(A)- zero_cnt cnt = 0 for i in A: if i == 0: cnt += one_cnt zero_cnt -= 1 continue one_cnt -= 1 return cnt if cnt <= 1000000000 else -1 print( solution([0,1,0,1,1]) == 5 ) ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.PassingCars/sjjyy.java ================================================ package lessons.lesson05.PrefixSums.PassingCars; class sjjyy { public static int solution(int[] A) { int result = 0; int count = 0; int len = A.length; for (int i = 0; i < len ; i++) { if (A[i] == 0) count++; else result += count; } if (result > 1000000000) return -1; return result; } public static void main(String[] args) { int[] A = new int[] {0, 1, 0, 1, 1}; System.out.println(solution(A)); } } ================================================ FILE: codility_training/lessons.lesson05.PrefixSums.PassingCars/test.json ================================================ [ [ [[0, 1, 0, 1, 1]], 5 ] ] ================================================ FILE: codility_training/lessons.lesson06.Sorting.Distinct/JeongShin.js ================================================ function solution(A) { return new Set(A).size } solution([2,1,1,2,3,1]); ================================================ FILE: codility_training/lessons.lesson06.Sorting.Distinct/README.md ================================================ ## [Sorting](https://codility.com/media/train/4-Sorting.pdf) [문제출처](https://app.codility.com/programmers/lessons/6-sorting/distinct/) ## 번역 ```text N 개의 정수로 구성된 배열 A가 주어지면 배열 A의 고유 값 수를 반환합니다. 예를 들어, 배열 A는 다음과 같은 6 가지 요소로 구성됩니다. A [0] = 2 A [1] = 1 A [2] = 1 A [3] = 2 A [4] = 3 A [5] = 1 이 함수는 배열 A에 3, 즉 1, 2 및 3으로 구분되는 3 개의 고유 한 값이 있기 때문에 3을 반환해야합니다. 다음 가정을위한 효율적인 알고리즘을 작성하십시오 . N은 [ 0 .. 100,000 ] 범위 내의 정수 이며; 배열 A의 각 요소는 [ -1,000,000 .. 1,000,000 ] 범위의 정수 입니다. ``` ## 원문 ```text Write a function class Solution { public int solution(int[] A); } that, given an array A consisting of N integers, returns the number of distinct values in array A. For example, given array A consisting of six elements such that: A[0] = 2 A[1] = 1 A[2] = 1 A[3] = 2 A[4] = 3 A[5] = 1 the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000]. ``` ================================================ FILE: codility_training/lessons.lesson06.Sorting.Distinct/eyabc.js ================================================ function solution(A) { return new Set(A).size; } console.log(solution([2, 1, 1, 2, 3, 1]) === 3); ================================================ FILE: codility_training/lessons.lesson06.Sorting.Distinct/junilhwang.js ================================================ function solution (A) { return Object.keys(A.reduce((obj, v) => (obj[v] = true, obj), {})).length } function solution2 (A) { return new Set(A).size } const assert = require('assert') require('./test.json').forEach(([ input ,output ]) => { assert.deepEqual(solution(...input), output) assert.deepEqual(solution2(...input), output) }) ================================================ FILE: codility_training/lessons.lesson06.Sorting.Distinct/khw970421.js ================================================ //정확성은 되나 효율성이 안좋다 function solution(A) { let p =A.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]); return p.length; } //set을 쓰면 strong set에의해 쉽게 distinct 가능 //정확성,효율성 문제x function solution2 (A) { return new Set(A).size } ================================================ FILE: codility_training/lessons.lesson06.Sorting.Distinct/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass return len(list(set(A))) print( solution([1,2,3,4,1,2,3,4,5,6]) == 6 ) ================================================ FILE: codility_training/lessons.lesson06.Sorting.Distinct/sjjyy.java ================================================ package lessons.lesson06.Sorting.Distinct; import java.util.Set; import java.util.HashSet; class sjjyy { public static int solution(int[] A) { Set hs = new HashSet<>(); int len = A.length; for (int i = 0; i < len ; i++) hs.add(A[i]); return hs.size(); } public static void main(String[] args) { int[] A = new int[] {2, 1, 1, 2, 3, 1}; System.out.println(solution(A)); } } ================================================ FILE: codility_training/lessons.lesson06.Sorting.Distinct/test.json ================================================ [ [ [ [2, 1, 1, 2, 3, 1] ], 3 ] ] ================================================ FILE: codility_training/lessons.lesson06.Sorting.MaxProductOfThree/JeongShin.js ================================================ /* * @eyabc 님 풀이 참고했습니다. 이렇게 짧게 구현이 가능하네요 ㅠ * */ function solution(A) { const len = A.length; if (len < 4) return A.reduce((acc, curr) => curr * acc, 1); A.sort((a, b) => a - b); return Math.max(A[0] * A[1] * A[len - 1], A[len - 1] * A[len - 2] * A[len - 3]); } // 원래 시도하려 했던 방법 // for (const val of A) // val >= 0 ? pos.push(val) : neg.push(val); // pos.sort((a, b) => b - a); // neg.sort((a, b) => a - b); // const neg_len = neg.length; // return pos.length === 0 ? neg[neg_len - 1] * neg[neg_len - 2] * neg[neg_len - 3] : // Math.max(number(pos[0]) * number(pos[1]) * number(pos[2]), number(pos[0]) * number(neg[0]) * number(neg[1]), // ); ================================================ FILE: codility_training/lessons.lesson06.Sorting.MaxProductOfThree/README.md ================================================ [문제출처](https://app.codility.com/programmers/lessons/6-sorting/max_product_of_three/) ## 입출력 ```javascript function solution(A) { // write your code in JavaScript (Node.js 8.9.4) return 1 } console.log(solution([-3, 1, 2, -2, 5, 6]) === 60); ``` ## 번역 ```text N 개의 정수로 구성된 비어 있지 않은 배열 A가 제공됩니다. 삼중 항 (P, Q, R) 의 곱은 A [P] * A [Q] * A [R] (0 ≤ P a - b); return Math.max(A[0] * A[1] * A[aLen - 1], A[aLen - 1] * A[aLen - 2] * A[aLen - 3]); } /** * https://stackoverflow.com/questions/23487381/solve-maximum-product-of-three-array-elements-without-sorting * When we sort an array there are two possible options for the largest product * 1) The largest (the last) three elements * 2) Combination of two smallest and the largest elements * Logic of (1): Obvious * Logic of (2): A pair of negatives multiplied returns a positive, which in combination with * the largest positive element of the array can give the max outcome. * Therefore we return the max of options (1) and (2) */ console.log( solution([-3, 2, 2, -2, 5, 6]) === 60, solution([-5, 5, -5, 4]) === 125, solution([-4, -6, -3, 4, 5]) === 120, solution([4, 6, 3, 4, 5]) === 120, ); ================================================ FILE: codility_training/lessons.lesson06.Sorting.MaxProductOfThree/junilhwang.js ================================================ function solution (A) { const last = A.length - 1 A.sort((a, b) => b - a) return Math.max(A[0] * A[1] * A[2], A[last] * A[last - 1] * Math.max(A[0], A[last - 2])) } const assert = require('assert') require('./test.json').forEach(([ input ,output ]) => { assert.deepEqual(solution(...input), output) }) ================================================ FILE: codility_training/lessons.lesson06.Sorting.MaxProductOfThree/khw970421.js ================================================ function solution(A) { A.sort((a,b)=>b-a); const len=A.length; return Math.max(A[0]*A[1]*A[2],A[len-1]*A[len-2]*A[0]); } /* 나열했을때 경우의수는 결국 2가지 순서로 나열했을때 제일큰수부터 3가지의 곱이 제일클때 순서로 나열했을때 제일절대값이 큰음수 2개와 제일큰 양수의 곱 (0이 포함되는 경우는 결국 둘다 0이 포함되면 최대도 0이고 둘중 하나가 0이 포함되도 나머지 다른 값이 max로 출력 */ ================================================ FILE: codility_training/lessons.lesson06.Sorting.MaxProductOfThree/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass sA = sorted(A) size = len(sA) mx1 = sA[size-1] * sA[size-2] * sA[size-3] mx2 = sA[size-1] * sA[0] * sA[1] return max(mx1, max2) ''' + + + 큰 수들로 곱 + + - 작은수들로 곱 // not applied + - - 큰 수들로 곱 - - - 작은수들로 곱 // not applied ''' print( solution([-3, 1, 2, -2, 5, 6]) == 60 ) ================================================ FILE: codility_training/lessons.lesson06.Sorting.MaxProductOfThree/sjjyy.java ================================================ package lessons.lesson06.Sorting.MaxProductOfThree; import java.util.*; class sjjyy { public static int solution(int[] A) { int n = A.length - 1; Arrays.sort(A); int ans1 = A[n] * A[n - 1] * A[n - 2]; int ans2 = A[0] * A[1] * A[n]; return ans1 > ans2 ? ans1 : ans2; } public static void main(String[] args) { int[] A = new int[] {2, 1, 1, 2, 3, 1}; System.out.println(solution(A)); } } ================================================ FILE: codility_training/lessons.lesson06.Sorting.MaxProductOfThree/test.json ================================================ [ [ [ [-3, 2, 2, -2, 5, 6] ], 60], [ [ [-5, 5, -5, 4] ], 125], [ [ [-4, -6, -3, 4, 5] ], 120], [ [ [4, 6, 3, 4, 5] ], 12] ] ================================================ FILE: codility_training/lessons.lesson06.Sorting.NumberOfDiscIntersections/JeongShin.js ================================================ /*제가 작성한 코드 * */ function solution(A) { const len = A.length; let count = 0; A.forEach((el, idx) => { for (let j = idx + 1; j < len; j++) { if (count > 10000000) return -1; count = (idx - A[idx] >= j + A[j] || idx + A[idx] >= j - A[j]) ? count + 1 : count; } }); return count; } /* https://jobjava00.github.io/algorithm/codility/lesson6/NumberOfDiscIntersections/ 에서 참고하여 작성한 코드 * */ function solution2(A) { const len = A.length; const [lower, upper] = A.reduce(([l, u], i, v) => (l.push(v - i), u.push(v + i), [l, u]), [[], []]); lower.sort((a, b) => a - b); upper.sort((a, b) => a - b); // console.log(lower, upper); let intersections = 0; let j = 0; for (let i = 0; i < len; i++) { while (j < len && upper[i] >= lower[j]) { // console.log(intersections, i,j); intersections += j; intersections -= i; j++; } } return intersections > 10000000 ? -1 : intersections; } console.log(solution2([1, 5, 2, 1, 4, 0])); ================================================ FILE: codility_training/lessons.lesson06.Sorting.NumberOfDiscIntersections/README.md ================================================ ## Number Of Disc Intersections ## 번역 ``` 평면에 N 개의 디스크를 그립니다. 디스크는 0에서 N-1까지 번호가 매겨집니다. 디스크의 반경을 지정하는 N 개의 음이 아닌 정수의 배열 A가 제공됩니다. J 번째 디스크는 중심이 (J, 0) 및 반경 A [J]로 그려집니다. J ≠ K 및 J 번째 및 K 번째 디스크에 하나 이상의 공통점이있는 경우 J 번째 디스크와 K 번째 디스크가 교차한다고합니다 (디스크에 테두리가 있다고 가정). 아래 그림은 N = 6 및 A에 대한 디스크를 다음과 같이 보여줍니다.   A[0] = 1   A[1] = 5   A[2] = 2   A[3] = 1   A[4] = 4   A[5] = 0 교차하는 11 개의 (정렬되지 않은) 디스크 쌍이 있습니다. 디스크 1과 4가 서로 교차하고 둘 다 다른 모든 디스크와 교차합니다. 디스크 2는 디스크 0 및 3 과도 교차합니다. 함수를 작성하십시오. 기능 솔루션 (A); 상술 한 바와 같이 N 개의 디스크를 기술하는 배열 A가 주어지면, 교차 디스크의 (정렬되지 않은) 쌍의 수를 리턴한다. 교차 쌍의 수가 10,000,000을 초과하면 함수는 -1을 반환해야합니다. 위에 표시된 배열 A에서 함수는 위에서 설명한대로 11을 반환해야합니다. 다음 가정을위한 효율적인 알고리즘을 작성하십시오. N은 [0..100,000] 범위 내의 정수이며; 배열 A의 각 요소는 [0..2,147,483,647] 범위의 정수입니다. ``` ## 출처 https://app.codility.com/programmers/lessons/6-sorting/number_of_disc_intersections/ ================================================ FILE: codility_training/lessons.lesson06.Sorting.NumberOfDiscIntersections/eyabc.js ================================================ const sortAsc = (a, b) => a - b; /* https://jobjava00.github.io/algorithm/codility/lesson6/NumberOfDiscIntersections/ */ function solution(A) { let counter = 0; const lower = []; const upper = []; const aLen = A.length; for(let i = 0; i < aLen ; i++) { lower[i] = i - A[i]; upper[i] = i + A[i]; } lower.sort(sortAsc); upper.sort(sortAsc); for(let i = 0, j = 0 ; i < aLen ; i++) { while(j < aLen && upper[i] >= lower[j]){ counter += j - i; j++; } if(counter > 10000000) return -1; } return counter; } /* timeout */ function solution2 (A) { const len = A.length; let res = 0; A.forEach((centerV, k) => { const lowV = k - centerV, highV = k + centerV; for(let i = k + 1; i < len ; i++) { const _this = A[i], lowThis = i - _this; if (lowV >= lowThis || highV >= lowThis) res++; if (res > 10000000) return -1; } }); return res; } /* 0 -> 1, 2, 4 1 -> 0, 2, 3 ,4 , 5 2 -> 0, 1, 3, 4, 3 -> 4, 2, 1 4 -> 1, 0, 2, 3, 5 5 -> 1, 4 */ console.log(solution([1, 5, 2, 1, 4, 0]) === 11); ================================================ FILE: codility_training/lessons.lesson06.Sorting.NumberOfDiscIntersections/junilhwang.js ================================================ function solution (A) { const [ upper, lower ] = A.reduce( ( [ u, l ], v ,i ) => (u.push(i + v), l.push(i - v), [ u, l ]), [ [], [] ]) upper.sort((a, b) => a - b) lower.sort((a, b) => a - b) let sum = 0 for (let i = 0, j = 0, len = A.length; i < len; i++) { while(upper[i] >= lower[j]){ sum += j++ - i; if (lower[j] === undefined) return sum; if (sum > 10000000) return -1; } } return sum } const testCase = require("./test.json") const assert = require('assert').strict testCase.forEach(({ input, output }) => assert.deepEqual(solution(...input), output) ) ================================================ FILE: codility_training/lessons.lesson06.Sorting.NumberOfDiscIntersections/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") # 굉장히 어려워서 오래걸렸다. 획기적인 발상으로 한번에 풀린 문제 def solution(A): # write your code in Python 3.6 pass B = sorted([ i - v for i, v in enumerate(A) ]) C = sorted([ i + v for i, v in enumerate(A) ]) num = len(A) case = num * (num - 1) // 2 cnt = 0 j = 0 for i in range(len(A)): while (C[j] < B[i]): cnt += num - i j += 1 return case - cnt if case - cnt <= 10000000 else -1 ================================================ FILE: codility_training/lessons.lesson06.Sorting.NumberOfDiscIntersections/sjjyy.java ================================================ package lessons.lesson06.Sorting.NumberOfDiscIntersections; import java.util.*; public class sjjyy { public static int solution(int [] A) // 어려워서 Mickey0521님 참고했습니다. { int len = A.length; long [] left = new long[len]; long [] right = new long[len]; int intersection = 0; for(int i = 0 ; i < len ; i++) { right[i] = i - (long) A[i]; left[i] = i + (long) A[i]; } Arrays.sort(left); Arrays.sort(right); int low = 0; for(int i = 0 ; i < len ; i++) { while (low < len && left[i] >= right[low]) { intersection = intersection + low - i; low++; if(intersection > 10000000) return -1; } } return intersection; } public static void main(String[] args) { int [] A = {1, 5, 2, 1, 4, 0}; System.out.println(solution(A)); // 11 } } ================================================ FILE: codility_training/lessons.lesson06.Sorting.NumberOfDiscIntersections/test.json ================================================ [ { "input": [ [1, 5, 2, 1, 4, 0] ], "output": 11 } ] ================================================ FILE: codility_training/lessons.lesson06.Sorting.Triangle/JeongShin.js ================================================ function solution(A) { const len = A.length; if (len < 3) return 0; const sorted = A.sort((a, b) => b - a); const isTraingle = (a, b, c) => a < b + c && b < a + c && c < a + b; for (let i = 0; i < len - 2; i++) { if (isTraingle(sorted[i], sorted[i + 1], sorted[i + 2])) return 1; } return 0; } console.log(solution([10, 2, 5, 1, 8, 20])); ================================================ FILE: codility_training/lessons.lesson06.Sorting.Triangle/README.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/6-sorting/triangle/ ## 번역 ```text N 개의 정수로 구성된 배열 A가 제공됩니다. 삼중 항 (P, Q, R)은 0 ≤ P A [R], A [Q] + A [R]> A [P], A [R] + A [P]> A [Q]. 예를 들어 다음과 같은 배열 A를 고려하십시오. A [0] = 10 A [1] = 2 A [2] = 5 A [3] = 1 A [4] = 8 A [5] = 20 삼중 항 (0, 2, 4)은 삼각형입니다. 함수를 작성하십시오. 기능 솔루션 (A); 즉, N 정수로 구성된 배열 A가 주어지면이 배열에 삼각 삼중 항이 있으면 1을 반환하고 그렇지 않으면 0을 반환합니다. 예를 들어, 다음과 같은 배열 A가 제공됩니다. A [0] = 10 A [1] = 2 A [2] = 5 A [3] = 1 A [4] = 8 A [5] = 20 위에서 설명한대로 함수는 1을 반환해야합니다. 주어진 배열 A는 다음과 같습니다. A [0] = 10 A [1] = 50 A [2] = 5 A [3] = 1 함수는 0을 반환해야합니다. 다음 가정을위한 효율적인 알고리즘을 작성하십시오 . N은 [ 0 .. 100,000 ] 범위 내의 정수 이며; 배열 A의 각 요소는 [ -2,147,483,648 .. 2,147,483,647 ] 범위 내의 정수 이다. ``` ## 원문 ```text An array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and: A[P] + A[Q] > A[R], A[Q] + A[R] > A[P], A[R] + A[P] > A[Q]. For example, consider array A such that: A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A[5] = 20 Triplet (0, 2, 4) is triangular. Write a function: function solution(A); that, given an array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise. For example, given array A such that: A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A[5] = 20 the function should return 1, as explained above. Given array A such that: A[0] = 10 A[1] = 50 A[2] = 5 A[3] = 1 the function should return 0. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. ``` ======= ================================================ FILE: codility_training/lessons.lesson06.Sorting.Triangle/eyabc.js ================================================ function solution(A) { A.sort((a, b) => a - b); const aLen = A.length - 2; for (let i = 0 ; i < aLen; i++) { const a = A[i], b = A[i + 1], c = A[i+2]; if (b > c - a) return 1; } return 0; } /* from sjjyy * http://blog.daum.net/_blog/BlogTypeView.do?blogid=03OsN&articleno=13080078 * 삼각형의 세 변의 길이를 a,b,c라고 하면 c가 가장 긴 변일 때 a + b > c (나머지 두 변의 길이의 합이 가장 긴 변의 길이보다 길다) 그렇다면 a > c-b, b > c-a 가 성립한다. 또 c>0 , c > b-a (c는 b보다 길기 때문에 당연히 b-a보다 길다)이므로 b-a < c < a + b c-b < a, 또는 c-a < b 가 성립한다 * */ console.log(solution([10, 2, 5, 1, 8, 20]) === 1); console.log(solution([10, 50, 5, 1]) === 0); ================================================ FILE: codility_training/lessons.lesson06.Sorting.Triangle/junilhwang.js ================================================ function solution(A) { A.sort((a, b) => a - b) for (let i = 0, len = A.length - 2; i < len; i++) { if (A[i + 1] > A[i + 2] - A[i]) return 1; } return 0 } const assert = require('assert').strict require("./test.json").forEach(({ input, output }) => assert.deepEqual(solution(...input), output) ) ================================================ FILE: codility_training/lessons.lesson06.Sorting.Triangle/khw970421.js ================================================ //sort후에 가장가까운3개의 값을 길이계산했을 때 가능하면 1리턴 아니면 0리턴 //정확성 효율성 문제x function solution(A) { // write your code in JavaScript (Node.js 8.9.4) A.sort((a,b)=>a-b); for(let i=0;iA[i+2]) return 1; } return 0; } ================================================ FILE: codility_training/lessons.lesson06.Sorting.Triangle/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass A.sort() A.reverse() for i in range(len(A)-2): if(A[i] < A[i+1] + A[i+2]): return 1 return 0 ================================================ FILE: codility_training/lessons.lesson06.Sorting.Triangle/sjjyy.java ================================================ package lessons.lesson06.Sorting.Triangle; import java.util.*; class sjjyy { public static int solution(int[] A) { int n = A.length; Arrays.sort(A); for (int i = 0 ; i < n - 2 ; i++) { if (A[i + 1] > A[i + 2] - A[i]) return 1; } return 0; } public static int solution2(int[] A) // overflow { int n = A.length; Arrays.sort(A); for (int i = 0 ; i < n - 2 ; i++) { if (A[i] + A[i + 1] > A[i + 2]) return 1; } return 0; } public static void main(String[] args) { int[] A = new int[] {2, 1, 1, 2, 3, 1}; System.out.println(solution(A)); System.out.println(solution2(A)); } } ================================================ FILE: codility_training/lessons.lesson06.Sorting.Triangle/test.json ================================================ [ { "input": [ [10, 2, 5, 1, 8, 20] ], "output": 1 }, { "input": [ [10, 50, 5, 1] ], "output": 0 } ] ================================================ FILE: codility_training/lessons.lesson07.StackandQueues.StoneWall/JeongShin.js ================================================ function solution(H) { return H.reduce(([stack, count, top], curr) => { while (top > 0 && stack[top - 1] > curr) { top--; } if (top === 0 || stack[top - 1] < curr) { stack[top++] = curr; count++; } return [stack, count, top]; }, [[], 0, 0])[1]; } solution([8, 8, 5, 7, 9, 8, 7, 4, 8]); ================================================ FILE: codility_training/lessons.lesson07.StackandQueues.StoneWall/README.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/ ## 입출력 ```javascript function solution(H) { // write your code in JavaScript (Node.js 8.9.4) return 0; } console.log( solution([8, 8, 5, 7, 9, 8, 7, 4, 8]) === 7 ); ``` ![stoneWall](./StoneWall.png) ## 번역 ```text 돌담을 지을 것입니다. 벽은 똑 바르고 N 미터 길이 여야하며 두께는 일정해야합니다. 그러나 장소마다 높이가 달라야합니다. 벽의 높이는 N 양의 정수로 구성된 배열 H로 지정됩니다. H [I]는 I에서 I + 1 미터 (왼쪽 끝)까지의 벽 높이입니다. 특히 H [0]은 벽의 왼쪽 끝의 높이이고 H [N-1]은 벽의 오른쪽 끝의 높이입니다. 벽은 직육면체 석재 블록으로 만들어야합니다 (즉, 그러한 블록의 모든면은 직사각형입니다). 당신의 임무는 벽을 구축하는 데 필요한 최소 블록 수를 계산하는 것입니다. 함수를 작성하십시오. 클래스 솔루션 {public int solution (int [] H); } 즉, 벽의 높이를 지정하는 N 개의 양의 정수로 구성된 배열 H가 있으면 벽을 만드는 데 필요한 최소 블록 수를 반환합니다. 예를 들어 N = 9 개의 정수를 포함하는 배열 H는 다음과 같습니다. H [0] = 8 H [1] = 8 H [2] = 5 H [3] = 7 H [4] = 9 H [5] = 8 H [6] = 7 H [7] = 4 H [8] = 8 이 함수는 7을 반환해야합니다. 그림은 7 개의 블록으로 구성된 가능한 배열을 보여줍니다. 다음 가정을위한 효율적인 알고리즘을 작성하십시오 . N은 [ 1 .. 100,000 ] 범위의 정수 이며; H 어레이의 각 요소는 범위 [내 정수 1 .. 1000000000 ]. ``` ## 원문 ```text You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end. The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall. Write a function: class Solution { public int solution(int[] H); } that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it. For example, given array H containing N = 9 integers: H[0] = 8 H[1] = 8 H[2] = 5 H[3] = 7 H[4] = 9 H[5] = 8 H[6] = 7 H[7] = 4 H[8] = 8 the function should return 7. The figure shows one possible arrangement of seven blocks. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array H is an integer within the range [1..1,000,000,000]. ``` ================================================ FILE: codility_training/lessons.lesson07.StackandQueues.StoneWall/eyabc.js ================================================ function solution(H) { const stack = [H[0]]; stack.getLast = () => stack[stack.length - 1] let res = 1; for (const v of H) { while(stack.getLast() > v) stack.pop(); res += v > stack.getLast() || !stack.length; stack.push(v) } return res; } console.log( solution([8, 8, 5, 7, 9, 8, 7, 4, 8]) === 7 ); ================================================ FILE: codility_training/lessons.lesson07.StackandQueues.StoneWall/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g.. # print("this is a debug message") # 좀 어렵다 문제가.. 전혀 not painless... painful.. def solution(H): # write your code in Python 3.6 pass S = [] cnt = 0 for x in H: while len(S) > 0 and S[len(S)-1] > x: S.pop() if len(S) == 0 or S[len(S)-1] < x: S.append(x) cnt += 1 return cnt pritn( solution([8,8,5,7,9,8,7,4,8]) == 7 ) ================================================ FILE: codility_training/lessons.lesson07.StackandQueues.StoneWall/sjjyy.java ================================================ package lessons.lesson07.StackandQueues.StoneWall; import java.util.*; class sjjyy { public static int solution(int[] H) { Stack stack = new Stack<>(); int len = H.length; int ans = 0; for (int i = 0 ; i < len ; i++) { if (stack.isEmpty() || stack.peek() < H[i]) { stack.push(H[i]); ans++; } else if (H[i] < stack.peek()) { stack.pop(); i--; } } return ans; } public static void main(String[] args) { int H[] = {8, 8, 5, 7, 9, 8, 7, 4, 8}; System.out.println(solution(H)); // 7 } } ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Brackets/JeongShin.js ================================================ function solution(S) { const brackets = {"(": ")", "{": "}", "[": "]"}; const bracketsKeys = Object.keys(brackets); const bracketsValues = Object.values(brackets); const open = []; let o_top = 0, c_top = 0; [...S].forEach(el => { bracketsKeys.indexOf(el) === -1 ? bracketsValues[bracketsKeys(brackets).indexOf(open[o_top - 1])] === el ? o_top-- : c_top++ : open[o_top++] = el; }); return o_top === 0 && c_top === 0 ? 1 : 0; } ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Brackets/README.md ================================================ ## 문제 https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/ ## 입출력 ```javascript function solution(S) { // write your code in JavaScript (Node.js 8.9.4) return 0; } console.log( solution('{[()()]}') === 1, solution('([)()]') === 0 ) ``` ## 번역 ```text 다음 조건 중 하나라도 해당되는 경우 N 문자로 구성된 문자열 S는 올바르게 중첩 된 것으로 간주됩니다 . S는 비어 있습니다. S의 형식은 " (U) "또는 " [U] "또는 " {U} "입니다. 여기서 U는 올바르게 중첩 된 문자열입니다. S의 형식은 " VW "이며 여기서 V와 W는 올바르게 중첩 된 문자열입니다. 예를 들어, 문자열 " {[() ()]} "은 (는) 올바르게 중첩되었지만 " ([) ()] "는 그렇지 않습니다. 함수를 작성하십시오. 기능 솔루션 (S); N 문자로 구성된 문자열 S가 주어지면 S가 올바르게 중첩되면 1을, 그렇지 않으면 0을 반환합니다. 예를 들어, S = " {[() ()]} "인 경우 함수는 1을 리턴하고 S = " ([) ()] "인 경우 함수는 위에서 설명한대로 0을 리턴해야합니다. 다음 가정을위한 효율적인 알고리즘을 작성하십시오 . N은 [ 0 .. 200,000 ] 범위 내의 정수 이며; 문자열 S는 " ( ", " { ", " [ ", " ] ", " } "및 / 또는 " ) " 문자로만 구성됩니다 . ``` ## 원문 ```text A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: S is empty; S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; S has the form "VW" where V and W are properly nested strings. For example, the string "{[()()]}" is properly nested but "([)()]" is not. Write a function: function solution(S); that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise. For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..200,000]; string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")". ``` ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Brackets/eyabc.js ================================================ /* JeongShin 님꺼 참고해서 수정 */ function solution(S) { const brackets = { '(': ')', '{': '}', '[': ']' }; const stack = []; const start = /\[|\(|{/; for (const v of S) { if(start.test(v)) stack.push(v); else if (v !== brackets[stack.pop()]) return 0; } return !stack.length * 1; } console.log( solution('{[()()]}') === 1, solution('([)()]') === 0 ); ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Brackets/junilhwang.js ================================================ function solution(A) { const obj = { ']': '[', ')': '(', '}': '{' } const stack = [] return (![ ...A ].some(v => { if ('[({'.indexOf(v) !== -1) stack.push(v) else if(stack.pop() !== obj[v]) return true }) && !stack.length) * 1 } const assert = require('assert').strict require("./test.json").forEach(({ input, output }) => assert.deepEqual(solution(...input), output) ) ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Brackets/sAp00n.py ================================================ def solution(S): # write your code in Python 3.6 braket_stack =[] parentheses = "(" curly = "{" square ="[" for i in S: if i == '(': braket_stack.append(parentheses) if i == ')': if len(braket_stack) == 0: return 0 elif braket_stack[-1] == parentheses: braket_stack.pop() else: return 0 if i == '{': braket_stack.append(curly) if i == '}': if len(braket_stack) == 0: return 0 elif braket_stack[-1] == curly: braket_stack.pop() else: return 0 if i == '[': braket_stack.append(square) if i == ']': if len(braket_stack) == 0: return 0 elif braket_stack[-1] == square: braket_stack.pop() else: return 0 if len(braket_stack) == 0: return 1 else: return 0 ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Brackets/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g.. # print("this is a debug message") def solution(S): # write your code in Python 3.6 pass st = [] for i in S: if(len(st) == 0): if(i == ")" or i == "]" or i == "}"): return 0 st.append(i) continue; if i == ")" and st.pop() != "(" : return 0 if i == "}" and st.pop() != "{": return 0 if i == "]" and st.pop() != "[" : return 0 st.append(i) return 1 if len(st) == 0 else 0 ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Brackets/sjjyy.java ================================================ package lessons.lesson07.StacksandQueues.Brackets; import java.util.*; class sjjyy { public static int solution(String S) { Stack stack = new Stack<>(); int len = S.length(); for (int i = 0 ; i < len ; i++) { char c = S.charAt(i); if (stack.isEmpty()) return 0; if (c == '(' || c == '{' || c == '[') stack.push(c); else { char last = stack.pop(); if (c == ')' && last != '(') return 0; if (c == '}' && last != '{') return 0; if (c == ']' && last != '[') return 0; } } if (!stack.isEmpty()) return 0; return 1; } public static void main(String[] args) { String S = "{[[()(]]}"; System.out.println(solution(S)); } } ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Brackets/test.json ================================================ [ { "input": [ "{[()()]}" ], "output": 1 }, { "input": [ "([)()]" ], "output": 0 }, { "input": [ "(((" ], "output": 0 } ] ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Fish/JeongShin.js ================================================ function solution(A, B) { const stack = []; let top = 0; A.forEach((fish, index) => { const direction = B[index] ? 1 : -1; if (top === 0 || direction === (top > 0 ? Math.sign(stack[top - 1]) : 0) || direction === 1) stack[top++] = fish * direction; else { while (top > 0 && Math.sign(stack[top - 1]) === 1) { top--; if (fish > stack[top]) stack[top] = fish * direction; else break; } top++; } }); // console.log(stack, top); return top; } solution([4, 3, 8, 1, 5], [0, 1, 1, 1, 0]); ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Fish/README.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/ ## 입출력 ```javascript function solution(A, B) { // write your code in JavaScript (Node.js 8.9.4) return 0; } console.log( solution([4, 3, 2, 1, 5], [0, 1, 0, 0, 0]) === 2 ) ``` ## 문제설명 solution([4, 3, 2, 1, 5], [0, 1, 0, 0, 0]) === 2 배열이 주어지면 첫번째 배열은 물고기의 크기 입니다. 두번째 배열은 물고기가 가는 방향이며 0 은 상류, 1은 하류 로 향합니다 서로 반대방향에서 마주치는 물고기중 큰 물고기가 살아남는다. 리턴할 값은 살아남은 물고기의 수이다. ## 번역 ```text N 개의 정수로 구성된 비어 있지 않은 두 개의 배열 A와 B가 제공됩니다. 배열 A와 B는 강의 흐름을 따라 하류로 정렬 된 강에서 N 개의 끔찍한 물고기를 나타냅니다. 물고기는 0에서 N-1까지 번호가 매겨집니다. P와 Q가 두 물고기이고 P A [Q] 인 경우 P는 Q를 먹고 P는 여전히 하류로 흐릅니다. A [Q]> A [P]이면 Q는 P를 먹고 Q는 여전히 상류로 흐릅니다. 우리는 모든 물고기가 같은 속도로 흐르고 있다고 가정합니다. 즉, 같은 방향으로 움직이는 물고기는 절대 만나지 않습니다. 목표는 살아남을 물고기 수를 계산하는 것입니다. 예를 들어, 배열 A와 B를 다음과 같이 고려하십시오. A [0] = 4 B [0] = 0 A [1] = 3 B [1] = 1 A [2] = 2 B [2] = 0 A [3] = 1 B [3] = 0 A [4] = 5 B [4] = 0 처음에는 모든 물고기가 살아 있고 물고기 번호 1을 제외한 모든 물고기가 상류로 이동합니다. 물고기 번호 1은 물고기 번호 2를 만나서 먹은 다음 물고기 번호 3을 만나서 먹습니다. 마지막으로 물고기 4 번을 만나서 먹습니다. 숫자 0과 4의 나머지 두 물고기는 절대 만나지 않으므로 살아남습니다. 함수를 작성하십시오. 기능 솔루션 (A, B); 즉, N 개의 정수로 구성된 비어 있지 않은 두 개의 배열 A와 B가 제공되면 살아남을 물고기 수를 반환합니다. 예를 들어 위에 표시된 배열이 주어지면 함수는 위에서 설명한 것처럼 2를 반환해야합니다. 다음 가정을위한 효율적인 알고리즘을 작성하십시오 . N은 [ 1 .. 100,000 ] 범위의 정수 이며; 어레이 A의 각 요소는 범위 [내 정수 0 .. 1000000000 ]; 배열 B의 각 요소는 다음 값 중 하나를 가질 수있는 정수입니다. 0, 1; A의 요소는 모두 다릅니다. ``` ## 원문 ```text You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river. The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q. Initially, each fish has a unique position. Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where: 0 represents a fish flowing upstream, 1 represents a fish flowing downstream. If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them. After they meet: If A[P] > A[Q] then P eats Q, and P will still be flowing downstream, If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream. We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive. For example, consider arrays A and B such that: A[0] = 4 B[0] = 0 A[1] = 3 B[1] = 1 A[2] = 2 B[2] = 0 A[3] = 1 B[3] = 0 A[4] = 5 B[4] = 0 Initially all the fish are alive and all except fish number 1 are moving upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, number 0 and 4, never meet and therefore stay alive. Write a function: function solution(A, B); that, given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive. For example, given the arrays shown above, the function should return 2, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [0..1,000,000,000]; each element of array B is an integer that can have one of the following values: 0, 1; the elements of A are all distinct. ``` ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Fish/eyabc.js ================================================ function solution (A, B) { const down = []; const len = A.length; let lastSize; let aliveCount = 0; for (let i = 0; i < len; i++) { if (B[i] === 1) down.push(A[i]); else { while (down.length > 0) { lastSize = down[down.length - 1]; if (lastSize > A[i]) break; else down.pop(); } if (down.length === 0) aliveCount++; } } return aliveCount + down.length; } console.log( solution([4, 3, 2, 1, 5], [0, 1, 0, 0, 0]), // === 2 // solution([4, 3, 2, 1, 5], [0, 1, 1, 0, 0]) solution([4], [0]) // === 2, ); ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Fish/sAp00n.py ================================================ def solution(A, B): # write your code in Python 3.6 print(f'A: {A} B:{B}') fish_stack = [] n = len(B) for i in range(n): if len(fish_stack) == 0: fish_stack.append((B[i], A[i])) else: if fish_stack[-1][0] == 0: fish_stack.append((B[i], A[i])) else: if B[i] == 1: fish_stack.append((B[i], A[i])) elif A[i] > fish_stack[-1][-1]: fish_eat_func(fish_stack,B[i], A[i]) print(fish_stack) return len(fish_stack) def fish_eat_func(fish_stack, Bi, Ai): if len(fish_stack) == 0: fish_stack.append((Bi, Ai)) return b, a = fish_stack[-1] while b != Bi and Ai > a: b, a = fish_stack.pop() if len(fish_stack) == 0: fish_stack.append((Bi, Ai)) return if fish_stack[-1][0] == Bi: fish_stack.append((Bi, Ai)) return else: return ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Fish/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g.. # print("this is a debug message") def solution(A, B): # write your code in Python 3.6 pass S = [] cnt = 0 for i, v in enumerate(A): if B[i] == 1: S.append(v) continue; while len(S) != 0: fish = S.pop() if fish > v: S.append(fish) break if (len(S) == 0): cnt += 1 return cnt + len(S) pritn( solution([4, 3, 2, 1, 5], [0, 1, 0, 0, 0]) == 2 ) ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Fish/sjjyy.java ================================================ package lessons.lesson07.StacksandQueues.Fish; import java.util.*; class sjjyy { public static int solution(int [] A, int [] B) { Stack stack = new Stack<>(); int size, cnt = 0; int len = A.length; for(int i = 0 ; i < len ; i++) { if(B[i] == 1) stack.push(A[i]); else { while (!stack.isEmpty()) { size = stack.peek(); if (size > A[i]) break; else stack.pop(); } if (stack.isEmpty()) cnt++; } } return cnt + stack.size(); } public static void main(String[] args) { int A[] = {4, 3, 2, 1, 5}; int B[] = {0, 1, 0, 0, 0}; System.out.println(solution(A, B)); } } ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Nesting/JeongShin.js ================================================ function solution(S) { let top = 0; // forEach 문은 도중에 break로 loop 탈출이 불가능 하다 하여 일반 포문을 사용 하였습니다. for (const v of S) { if (top < 0) break; top += v === '(' ? 1 : (v === ')') * -1 } return !top*1; } solution(")("); ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Nesting/README.md ================================================ ## 문제 https://app.codility.com/programmers/lessons/7-stacks_and_queues/nesting/ ## 입출력 ```javascript function solution(S) { // write your code in JavaScript (Node.js 8.9.4) return 0; } console.log( solution('(()(())())') === 1, solution('())') === 0 ) ``` ## 번역 ```text 다음과 같은 경우 N 문자로 구성된 문자열 S를 올바르게 중첩 이라고 합니다. S는 비어 있습니다. S의 형식은 " (U) "입니다. 여기서 U는 올바르게 중첩 된 문자열입니다. S의 형식은 " VW "이며 여기서 V와 W는 올바르게 중첩 된 문자열입니다. 예를 들어, 문자열 " (() (()) ()) "은 올바르게 중첩되지만 문자열 " ()) "는 그렇지 않습니다. 함수를 작성하십시오. 클래스 솔루션 {public int solution (String S); } N 문자로 구성된 문자열 S가 주어지면 문자열 S가 올바르게 중첩되면 1을 반환하고 그렇지 않으면 0을 반환합니다. 예를 들어, S = " (() (()) ()) "인 경우 함수는 1을 반환하고 S = " ()) "인 경우 함수는 위에서 설명한대로 0을 반환해야합니다. 다음 가정을위한 효율적인 알고리즘을 작성하십시오 . N은 [ 0 .. 1,000,000 ] 범위 내의 정수 이며; 문자열 S는 문자 " ( "및 / 또는 " ) " 로만 구성됩니다 . ``` ## 원문 ```text A string S consisting of N characters is called properly nested if: S is empty; S has the form "(U)" where U is a properly nested string; S has the form "VW" where V and W are properly nested strings. For example, string "(()(())())" is properly nested but string "())" isn't. Write a function: class Solution { public int solution(String S); } that, given a string S consisting of N characters, returns 1 if string S is properly nested and 0 otherwise. For example, given S = "(()(())())", the function should return 1 and given S = "())", the function should return 0, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..1,000,000]; string S consists only of the characters "(" and/or ")". ``` ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Nesting/eyabc.js ================================================ function solution(S) { const stack = []; for (const v of S) { if (v === '(') stack.push(v); else { if(stack.length === 0) return 0; stack.pop() } } return !stack.length * 1 } console.log( solution('(()(())())') === 1, solution('())') === 0, solution('((())') === 0, solution('((()))))') === 0, ); ================================================ FILE: codility_training/lessons.lesson07.StacksandQueues.Nesting/khw970421.js ================================================ //방법1 : 정확성은 맞으나 효율성 부족 function solution(S) { const A=S.length; S=[...S]; //문자열을 배열로 선언 for(let i=0;i stack = new Stack<>(); int len = S.length(); int ans = 0; for (int i = 0 ; i < len ; i++) { char c = S.charAt(i); if (c =='(') stack.push('('); else if (stack.size() == 0 || stack.pop() != '(') return 0; } return stack.size() == 0 ? 1 : 0; } public static void main(String[] args) { String S = "((()))("; System.out.println(solution(S)); } } ================================================ FILE: codility_training/lessons.lesson08.Leader.Dominator/JeongShin.js ================================================ function solution(A) { const d = {}; const goal = A.length / 2; for (const [idx, el] of A.entries()){ d[el] = (d[el] || 0) + 1 if (d[el]>goal) return idx; } return -1; } ================================================ FILE: codility_training/lessons.lesson08.Leader.Dominator/JunilHwang.java ================================================ package codility_training.lessons.lesson08.Leader.Dominator; import java.util.Stack; import java.util.stream.Stream; public class JunilHwang { public static int solution(int [] A) { Stack stack = new Stack<>(); int len = A.length; for (int a : A) { if (stack.isEmpty() || stack.peek() == a) stack.push(a); else stack.pop(); } if (stack.size() == 0) return -1; int peek = stack.peek(); for (int j = 0, max_cnt = 0; j < len; j++) { if (peek == A[j]) max_cnt++; if (max_cnt > len / 2) return j; } return -1; } public static void main(String[] args) { Stream.of( solution(new int[]{3, 4, 3, 2, 3, -1, 3, 3}), solution(new int[]{2, 1, 1, 3, 4}), solution(new int[]{1, 2, 1}), solution(new int[]{3, 2, 1}), solution(new int[]{3, 2, 1, 4}), solution(new int[]{2147483647}) ).forEach(System.out::println); } } ================================================ FILE: codility_training/lessons.lesson08.Leader.Dominator/README.md ================================================ # Leader - Dominator ## About Leader http://blog.naver.com/PostView.nhn?blogId=1net1&logNo=221237882968 ## 출처 https://app.codility.com/programmers/lessons/8-leader/dominator/ ## 원문 ``` An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A. For example, consider array A such that A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8. Write a function class Solution { public int solution(int[] A); } that, given an array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return −1 if array A does not have a dominator. For example, given array A such that A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 the function may return 0, 2, 4, 6 or 7, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. ``` ## 번역 ``` N 개의 정수로 구성된 배열 A가 제공됩니다. 배열 A의 지배자는 A 요소의 절반 이상에서 발생하는 값입니다. 예를 들어 배열 A를 고려하여  A [0] = 3 A [1] = 4 A [2] = 3  A [3] = 2 A [4] = 3 A [5] = -1  A [6] = 3 A [7] = 3 A의 지배자는 A의 8 개 요소 중 5 개 (즉, 인덱스 0, 2, 4, 6 및 7을 가진 요소 중 5 개)에서 발생하고 5는 8의 절반 이상이기 때문에 3입니다. 함수 작성 클래스 솔루션 {public int solution (int [] A); } 즉, N 개의 정수로 구성된 배열 A가 주어지면 A의 지배자가 발생하는 배열 A의 모든 요소의 인덱스를 반환합니다. 배열 A에 지배자가 없으면 함수는 -1을 반환해야합니다. 예를 들어, 주어진 배열 A는  A [0] = 3 A [1] = 4 A [2] = 3  A [3] = 2 A [4] = 3 A [5] = -1  A [6] = 3 A [7] = 3 함수는 위에서 설명한대로 0, 2, 4, 6 또는 7을 반환 할 수 있습니다. 다음 가정을위한 효율적인 알고리즘을 작성하십시오. N은 [0..100,000] 범위 내의 정수이며; 배열 A의 각 요소는 [-2,147,483,648..2,147,483,647] 범위의 정수입니다. ``` ================================================ FILE: codility_training/lessons.lesson08.Leader.Dominator/eyabc.js ================================================ function solution(A) { const arr = [], len = A.length; for (let i = 0; i < len; i++) { arr[A[i]] = ( arr[A[i]] || 0 ) + 1; if (arr[A[i]] > len / 2) return i; } return -1; } console.log( solution([3, 4, 3, 2, 3, -1, 3, 3]), solution([2, 1, 1, 3, 4] ), solution([1, 2, 1]), solution([3, 2, 1]), solution([2147483647] ) ); ================================================ FILE: codility_training/lessons.lesson08.Leader.Dominator/junilhwang.js ================================================ function solution(A) { const obj = {} const half = A.length / 2 let max = 0; for (const i in A) { const v = A[i] obj[v] = (obj[v] || 0) + 1 if (obj[v] > half) return i*1; } return -1 } const assert = require('assert').strict require("./test.json").forEach(({ input, output }) => { const expected = solution(...input) assert.notEqual(output.indexOf(expected), -1) }) ================================================ FILE: codility_training/lessons.lesson08.Leader.Dominator/sAp00n.py ================================================ # N 개의 정수로 구성된 배열 A가 제공됩니다. 배열 A 의 지배자 는 A 요소의 절반 이상에서 발생하는 값입니다. # N은 [ 0 .. 100,000 ] 범위 내의 정수 이며 # 배열 A의 각 요소는 [ -2,147,483,648 .. 2,147,483,647 ] 범위 내의 정수 이다. def solution(A): # write your code in Python 3.6 len_a = len(A) condition = len_a // 2 dic = {} for i in A: dic[i] = dic.get(i, 0)+1 if dic[i] > condition: return i return -1 ================================================ FILE: codility_training/lessons.lesson08.Leader.Dominator/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass B = {} C = set(A) for i in C: B[i] = 0 for i in A: B[i] += 1 for k, v in B.items(): if (v > len(A) // 2): return A.index(k) return -1 print( solution(3,4,3,2,3,-1,3,3 == 0) ) ================================================ FILE: codility_training/lessons.lesson08.Leader.Dominator/sjjyy.java ================================================ package lessons.lesson08.Leader.Dominator; import java.util.*; class sjjyy { public static int solution(int [] A) { Stack stack = new Stack<>(); int len = A.length; for (int i = 0 ; i < len ; i++) { if (stack.isEmpty() || stack.peek() == A[i]) stack.push(A[i]); else stack.pop(); } int res = stack.size() > 0 ? stack.peek() : -1; int max_cnt = 0; for(int j = 0 ; j < len ; j++) { if (res == A[j]) max_cnt++; if (max_cnt > len/2) return j; } return -1; } public static void main(String[] args) { int A[] = {3, 4, 3, 2, 3, -1, 3, 3}; System.out.println(solution(A)); } } ================================================ FILE: codility_training/lessons.lesson08.Leader.Dominator/test.json ================================================ [ { "input": [ [3, 4, 3, 2, 3, -1, 3, 3] ], "output": [0, 2, 4, 6, 7] } ] ================================================ FILE: codility_training/lessons.lesson08.Leader.EquiLeader/JeongShin.js ================================================ function solution(A) { const getLeader = (obj, len) => { for (const [key, val] of Object.entries(obj)) { if (val > len / 2) return key; } return -1; }; const left = {}, right = {}; A.forEach(el => right[el] = (right[el] || 0) + 1); //오른쪽 오브젝트에 A 모든 요소 삽입 let [llen, rlen] = [0, A.length]; // .length 메소드 사용을 줄이기 위한 변수 if (Object.keys(right).length > rlen / 2) // 숫자가 A 배열 절반 이상으로 다양하면 leader는 존재할 수 없다. ex) [1,2,2,2,3,5,2,2,7,6] return 0; return A.reduce((count, el) => { --right[el]; left[el] = (left[el] || 0) + 1; const [l, r] = [getLeader(left, ++llen), getLeader(right, --rlen)]; return count + (l === r && l !== -1) }, 0); } ================================================ FILE: codility_training/lessons.lesson08.Leader.EquiLeader/README.md ================================================ # Leader - EquilLeader ## 출처 https://app.codility.com/programmers/lessons/8-leader/ ## 원문 ``` A non-empty array A consisting of N integers is given. The leader of this array is the value that occurs in more than half of the elements of A. An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value. For example, given array A such that: A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 we can find two equi leaders: 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4. 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4. The goal is to count the number of equi leaders. Write a function: class Solution { public int solution(int[] A); } that, given a non-empty array A consisting of N integers, returns the number of equi leaders. For example, given: A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 the function should return 2, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000,000..1,000,000,000]. ``` ## 번역 ``` N 개의 정수로 구성된 비어 있지 않은 배열 A가 제공됩니다. 이 배열의 리더는 A 요소의 절반 이상에서 발생하는 값입니다. 등가 리더는 0 ≤ S (A.length / 2)) return 0; for (const v of A) rObj[v] = (rObj[v] || 0) + 1; for (let i = 0 ; i < len ; i++) { lObj[A[i]] = (lObj[A[i]] || 0) + 1; rObj[A[i]]--; const lMax = Math.max(...Object.values(lObj)); const rMax = Math.max(...Object.values(rObj)); /// l r 둘다 과반수가 존재하는지 if (lMax / (i + 1) > 0.5 && rMax / (len - i) > 0.5) { const maxLKey = Object.entries(lObj).find(([, value]) => value === lMax); const maxRKey = Object.entries(rObj).find(([, value]) => value === rMax); if (maxRKey[0] === maxLKey[0]) res++; } } return res; } console.log( solution([4, 3, 4, 4, 4, 2]), solution([4, 4, 2, 5, 3, 4, 4, 4]), solution([-1000000000, -1000000000]), solution([1, 2, 3, 4, 5, 6, 7, 8, 9]), ); ================================================ FILE: codility_training/lessons.lesson08.Leader.EquiLeader/junilhwang.js ================================================ function solution(A) { if (A.length < 2) return 0 const FO = { [A[0]]: 1 }, BO = {} let FLMax = 1, BLMax = 0, FC = 1, BC = A.length - 1, FL = A[0], BL for (let i = 1; A[i] !== undefined; i++) { const v = A[i] BO[v] = (BO[v] || 0) + 1 BLMax = Math.max(BLMax, BO[v]) if (BO[v] > BC / 2) BL = v } let cnt = (~~FL === ~~BL) * 1 for (let i = 1; A[i] !== undefined; i++) { const v = A[i] FO[v] = (FO[v] || 0) + 1; BO[v] -= 1 FC += 1 BC -= 1 BLMax = BO[BL] if (FO[v] > FLMax) ([FL, FLMax] = [v, FO[v]]); cnt += (FLMax > FC / 2 && BLMax > BC / 2 && ~~FL === ~~BL) } return cnt } const assert = require('assert').strict require("./test.json").forEach(({ input, output }) => { assert.deepEqual(solution(...input), output) }) ================================================ FILE: codility_training/lessons.lesson08.Leader.EquiLeader/sAp00n.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") # [1, 2, 1, 1, 2, 1] def solution(A): # write your code in Python 3.6 leader = search_leader(A) #print(f'leader = {leader}') if leader == -1: return 0 else: eq_leadernum = 0 n = len(A) logical_list = [0 for i in range(n)] temp = 0 for value in range(n): if A[value] == leader: temp += 1 logical_list[value] = temp #print(logical_list) left_ele_num = 1 right_ele_num = len(A)-1 for i in range(len(A) - 1): left_condition = logical_list[i] / left_ele_num if left_condition > 1 / 2: right_condition = (logical_list[-1] - logical_list[i]) / right_ele_num if right_condition > 1 / 2: eq_leadernum += 1 left_ele_num += 1 right_ele_num -= 1 return eq_leadernum def search_leader(A): # write your code in Python 3.6 len_a = len(A) condition = len_a // 2 dic = {} for i in A: dic[i] = dic.get(i, 0)+1 if dic[i] > condition: return i return -1 ================================================ FILE: codility_training/lessons.lesson08.Leader.EquiLeader/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass B = {} D = set(A) for i in D: B[i] = 0 for i in A: B[i] += 1 equi = 0 for k, v in B.items(): if (v > len(A) // 2): equi = k cnt = ret = 0 num = B.get(equi) size = len(A) for i, v in enumerate(A): if v == equi: cnt += 1 if (i + 1) / 2 < cnt and (size - i - 1) / 2 < num - cnt: ret += 1 return ret print( solution(4, 3, 4, 4, 4, 2 == 2) ) ================================================ FILE: codility_training/lessons.lesson08.Leader.EquiLeader/sjjyy.java ================================================ package lessons.lesson08.Leader.EquiLeader; import java.util.*; class sjjyy { public static int solution(int [] A) { Stack stack = new Stack<>(); int len = A.length; for (int i = 0 ; i < len ; i++) { if (stack.isEmpty() || stack.peek() == A[i]) stack.push(A[i]); else stack.pop(); } int res = stack.size() > 0 ? stack.peek() : -1; int cnt = 0; for(int j = 0 ; j < len ; j++) { if (A[j] == res) cnt++; } if (cnt <= len/2) return 0; int leader = res; int leftCount = 0; int rightCount = 0; for (int i = 0 ; i < len ; i++) { if (A[i] == leader) rightCount++; if (rightCount > (i+1)/2 && (cnt-rightCount) > (len-i-1)/2) leftCount++; } return leftCount; } public static void main(String[] args) { int A[] = {4, 3, 4, 4, 4, 2}; System.out.println(solution(A)); } } ================================================ FILE: codility_training/lessons.lesson08.Leader.EquiLeader/test.json ================================================ [ { "input": [ [4,3,4,4,4,2] ], "output": 2 }, { "input": [ [4, 4, 2, 5, 3, 4, 4, 4] ], "output": 3 }, { "input": [ [0,0] ], "output": 1 }, { "input": [ [0] ], "output": 0 } ] ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxDoubleSliceSum/JeongShin.js ================================================ /* * 이틀정도 해매다가 84%에서 어디가 틀렸는지 모르겠어서 인터넷 검색해서 풀이 공부했습니다 ㅜ ㅜ. * 일단 merge 해둔뒤 나중에 수정하겠습니다 . * */ function solution(A) { const N = A.length; if (N === 3) return 0; let headSum = A.map(i => 0); let tailSum = A.map(i => 0); for (let i = 1; i < N - 1; i++) { headSum[i] = Math.max(0, headSum[i - 1] + A[i]); } for (let i = N - 2; i >= 1; i--) { tailSum[i] = Math.max(0, tailSum[i + 1] + A[i]); } let maxSum = 0; for (let i = 1; i < N - 1; i++) { maxSum = Math.max(maxSum, headSum[i - 1] + tailSum[i + 1]); } return maxSum; } //출처 : https://sustainable-dev.tistory.com/25 solution([1, 1, 0, 10, -100, 10, 0]); // function solution(A) { // const len = A.length; // if (len < 4) // return 0; // A[0] = 0; // A[len - 1] = 0; // let max = -Infinity; // const result = A.reduce(([acc, min, flag], curr, index) => { // const prev = index > 1 ? A[index - 1] : 0; // if (index !== 0 && index !== len - 1) { // 처음과 마지막은 최소값으로 포함될 수 없음. // min = Math.min(min, curr); // } // if (prev > 0 && curr < 0) { // max = Math.max(flag === 1 ? acc - min : acc, max); // } // if (prev < 0 && curr >= 0) // if (acc - min < 0) // return [curr, curr, 0]; // else // return [acc + curr, min, 1]; // return [curr + acc, min, flag] // }, [0, Infinity, 0]); // max = Math.max(max, result[0] - result[1]); // return max < 0 ? 0 : max; // } ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxDoubleSliceSum/README.md ================================================ # Maximum slice problem https://codility.com/media/train/7-MaxSlice.pdf ## 문제 https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_double_slice_sum/ ## 문제 설명 https://hwan-shell.tistory.com/124 ## 번역 ```text N 개의 정수로 구성된 비어 있지 않은 배열 A가 제공됩니다. 0≤X = 1; i--) rArr[i] = Math.max(0, (rArr[i+1] || 0) + A[i]); let maxSum = 0; for(let i = 1; i < len-1; i++) maxSum = Math.max(maxSum, (lArr[i-1] || 0) + (rArr[i+1] || 0)); return maxSum; } console.log(solution([5, -7, 3, 5, -2, 4, -1])) console.log(solution([3, 2, 6, -1, 4, 5, -1, 2])) ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxDoubleSliceSum/sAp00n.py ================================================ # test case [5, 17, 0, 3], [0, 10, -5, -2, 0], [5, 5, 5] and all negative def solution(A): mid = 1 total = 0 max_slice = 0 for idx, end in enumerate(A[2:-1], start=2): if total < 0: mid = idx total = 0 elif total == 0 and A[idx - 1] > A[mid]: mid = idx - 1 total = end else: if A[mid] > end: total += A[mid] mid = idx else: total += end max_slice = max(max_slice, total) return max_slice ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxDoubleSliceSum/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") # https://github.com/DKU-STUDY/Algorithm/blob/master/codility_training/lessons.lesson09.MaximumSliceProblem.MaxDoubleSliceSum/sjjyy.java 참고 def solution(A): # write your code in Python 3.6 pass size = len(A) L = [0] * size R = [0] * size mx = 0 for i in range(1, size): L[i] = max(0, L[i-1]+A[i]) for i in range(size-2, -1, -1): R[i] = max(0, R[i+1] + A[i]) for i in range(1, size-1): mx = max(mx, L[i-1] + R[i+1]) return mx ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxDoubleSliceSum/sjjyy.java ================================================ package lessons.lesson09.MaximumSliceProblem.MaxDoubleSliceSum; public class sjjyy { public static int solution(int [] A) { int len = A.length; int[] L = new int[len]; int[] R = new int[len]; int max = 0; for(int i = 1 ; i < len ; i++) L[i] = Math.max(0, L[i-1]+A[i]); // A[X+1] + A[X+2] + ... + A[Y-1] for(int i = len - 2 ; i >= 0 ; i--) R[i] = Math.max(0, R[i+1] + A[i]); // A[Y+1] + A[Y+2] + ... + A[Z-1] for(int i = 1 ; i < len-1 ; i++) max = Math.max(max, L[i-1] + R[i+1]); return max; } public static void main(String[] args) { int [] A = {3, 2, 6, -1, 4, 5, -1, 2}; System.out.println(solution(A)); // 17 } } ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxProfit/JeongShin.js ================================================ function solution(A) { let [maxidx, minidx] = [0, 0]; return A.reduceRight(([profit, max, min], curr, curridx) => { [max, maxidx] = curr > max ? [curr, curridx] : [max, maxidx]; [min, minidx] = curr < min ? [curr, curridx] : [min, minidx]; [min, minidx] = minidx > maxidx ? [curr, curridx] : [min, minidx]; profit = maxidx > minidx ? Math.max(profit, max - min) : profit; return [profit, max, min]; }, [0, 0, Infinity])[0]; } let ans = solution([8, 9, 3, 6, 1, 2]); console.log(ans); ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxProfit/README.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/ ## 원문 ``` An array A consisting of N integers is given. It contains daily prices of a stock share for a period of N consecutive days. If a single share was bought on day P and sold on day Q, where 0 ≤ P ≤ Q < N, then the profit of such transaction is equal to A[Q] − A[P], provided that A[Q] ≥ A[P]. Otherwise, the transaction brings loss of A[P] − A[Q]. For example, consider the following array A consisting of six elements such that: A[0] = 23171 A[1] = 21011 A[2] = 21123 A[3] = 21366 A[4] = 21013 A[5] = 21367 If a share was bought on day 0 and sold on day 2, a loss of 2048 would occur because A[2] − A[0] = 21123 − 23171 = −2048. If a share was bought on day 4 and sold on day 5, a profit of 354 would occur because A[5] − A[4] = 21367 − 21013 = 354. Maximum possible profit was 356. It would occur if a share was bought on day 1 and sold on day 5. Write a function, class Solution { public int solution(int[] A); } that, given an array A consisting of N integers containing daily prices of a stock share for a period of N consecutive days, returns the maximum possible profit from one transaction during this period. The function should return 0 if it was impossible to gain any profit. For example, given array A consisting of six elements such that: A[0] = 23171 A[1] = 21011 A[2] = 21123 A[3] = 21366 A[4] = 21013 A[5] = 21367 the function should return 356, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..400,000]; each element of array A is an integer within the range [0..200,000]. ``` ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxProfit/eyabc.js ================================================ function solution(A) { if(!A.length) return 0; const arr = [...A].reverse(); let max, maxmap; const len = A.length; const maxArr = arr.map(v => { maxmap = maxmap ? (maxmap < v ? v : maxmap) : v; return maxmap }); maxArr.reverse(); for(let i = 0 ; i < len - 1 ; i++) max = A[i] < maxArr[i] ? Math.max(maxArr[i] - A[i], (max || maxArr[i] - A[i])) : max; return max || 0; } /* time out */ function solution2(A) { if(!A.length) return 0; let max; const len = A.length; for(let i = 0 ; i < len ; i++) { const buy = A[i]; for (let j = i ; j < len ; j++) { const sell = A[j]; max = Math.max(sell - buy, (max || sell - buy)); } } return max; } function solution3(A) { if(!A.length) return 0; let max; const len = A.length, maxArr= []; for(let i = 0 ; i < len - 1 ; i++) { maxArr[i] = Math.max(...A.slice(i+1, len)) } for(let i = 0; i < maxArr.length; i++) { max = A[i] < maxArr[i] ? Math.max(maxArr[i] - A[i], (max || maxArr[i] - A[i])) : max } return max || 0; } function solution4(A) { if(!A.length) return 0; const arr = [...A]; let max; const len = A.length, maxArr = []; for(let i = 0 ; i < len - 1 ; i++) { arr.shift() maxArr[i] = Math.max(...arr) max = A[i] < maxArr[i] ? Math.max(maxArr[i] - A[i], (max || maxArr[i] - A[i])) : max } return max || 0; } console.log( solution([23171, 21011, 21123, 21366, 21013, 21367]), solution([5, 4, 3, 2, 1] ), solution([]) // =;== 356 ) ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxProfit/khw970421.js ================================================ //정확도 100 효율성 75 function solution(A) { let max=0; const A_size=A.length; for(let i=0;i { min = Math.min(v, min); max = Math.max(max, v - min); return [min ,max]; },[min,max])[1]; } ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxProfit/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass B = [] if len(A) == 0: return 0 mn = A[0] for i in A[1:]: mn = min(mn, i) B.append(i - mn) return sorted(B)[-1] print( solutiion(23171, 21011, 21123, 21366, 21013, 21367) == 356 ) ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxProfit/sjjyy.java ================================================ package lessons.lesson09.MaximumSliceProblem.MaxProfit; class sjjyy { public static int solution(int [] A) { int len = A.length; int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; if (len == 0 || len == 1) return 0; for (int i = 0 ; i < len ; i++) { min = Math.min(A[i], min); max = Math.max(max, A[i]-min); } return max; } public static void main(String[] args) { int A[] = {23171, 21011, 21123, 21366, 21013, 21367}; System.out.println(solution(A)); // 356 } } ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxSliceSum/JeongShin.js ================================================ function solution(A) { return A.reduce(([max, acc], curr) => { max = Math.max(acc + curr, max, curr); return [max, curr + !(acc < 0) * acc] }, [-Infinity, 0])[0]; } ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxSliceSum/NowonLee.js ================================================ function solution(A) { if(A.length===1) return A[0] return A.reduce(([loc, glob], el, idx) => { if(idx > 0){ loc = Math.max(el, loc + el); glob = Math.max(loc, glob); } return [loc, glob]; },[A[0],A[0]])[1] } console.log(solution([3,2,-6,4,0]) === 5) ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxSliceSum/eyabc.js ================================================ function solution(A) { return A.reduce(([ max, max_ending ], v) => { max_ending = Math.max(v, max_ending + v); return [ Math.max(max, max_ending), max_ending ]; }, [-Infinity, -Infinity])[0] } console.log( solution([3, 2, -6, 4, 0])===5, solution([-10]) === -10, solution([-2, 1]) === 1 ); ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxSliceSum/sAp00n.py ================================================ def solution(A): start_ind, end_ind = find_max_slice(A) max_slice = A[start_ind:end_ind] max_slice.remove(min(max_slice)) return sum(max_slice) def find_max_slice(A): A = A[1:-2] maximum = A[0] temp = 0 start_ind = 0 end_ind = 0 for i in A: if i > temp + i: start_ind = A.index(i) temp = max(temp + i, i) if temp > maximum: end_ind = A.index(i) maximum = max(temp, maximum) # print(f'temp = {temp} max = {maximum}\n A[{start_ind}:{end_ind}]') return start_ind, end_ind ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxSliceSum/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pass size = len(A) L = [0] * size mx = 0 if sorted(A)[-1] < 0: return sorted(A)[-1] for i in A: mx = max(0, mx + i) L.append(mx) return sorted(L)[-1] print( solutiion(3, 2, -6, 4, 0) == 5 ) ================================================ FILE: codility_training/lessons.lesson09.MaximumSliceProblem.MaxSliceSum/sjjyy.java ================================================ package lessons.lesson09.MaximumSliceProblem.MaxSliceSum; class sjjyy { public static int solution(int [] A) { int len = A.length; if(len == 1) return A[0]; int max = 0; // int maxSlice = 0; int maxSlice = Integer.MIN_VALUE; for (int i = 0 ; i < len ; i++) { max = Math.max(A[i], A[i] + max); maxSlice = Math.max(max, maxSlice); } return maxSlice; } public static void main(String[] args) { int A[] = {3, 2, -6, 4, 0}; System.out.println(solution(A)); // 5 } } ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/JeongShin.js ================================================ function solution(N) { if (N === 1) return 1 const n = ~~Math.sqrt(N) let count = 0 for (let i = 1; i <= n; i++) count += (N % i === 0) * 1 return count * 2 - (N / n === n) * 1 } console.log(solution(4)) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/NowonLee.js ================================================ function solution(N) { if(N===1) return 1 let result = 0; /* for(let i = 1; i*i<=N;i++){ if(N%i===0){ if(i*i === N) result += 1; else { result += 2; } } } */ let i = 1; while(i ** 2 < 0){ result += !(N % i++) * 2 } return result + !(N%i) } console.log(solution(24)===8) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/PrimeAndCompositeNumber-practice.js ================================================ /* Counting the Number of Divisors O(√n) */ function divisors(n) { let i = 1; let result = 0; while (i * i < n) { if (n % i == 0) result += 2; i += 1; } return result + (i ** 2 == n); } // console.log(divisors(36)); /* 10.2 Primality test — O(√n) */ function primality(n) { let i = 2; while (i * i <= n) { if (n % i == 0) return false; i += 1; } return true; } // console.log(primality(5)); /* 10.3: Reversing coins — O(n log n) */ function coins(n) { let result = 0; let coin = new Array(n + 1).fill(0); for (let i = 1; i < n + 1; i++) { let k = i; while (k <= n) { coin[k] = (coin[k] + 1) % 2; k += i } result += coin[i] } return result; } console.log(coins(10)); ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/README.md ================================================ ## Prime and composite numbers javascript 코드는 PrimeAndCompositeNumber-practice.js 에 있습니다. intro. Prime Number (소수) 에 대한 설명 10.1 Counting divisors 나눌수 있는 수 (divisors)가 몇개인가? 예시 k^2 를 나눌수 있는 수들은 k 와 같거나 작다. k가 36일때 1 * 36, 2*18, 3 * 12, 3 * 9 ...모두 18 이하이다. 10.2 Primality test 소수판별법 10.3. Exercises 문제 : n 개의 동전이 일렬로 정렬되어 있다고 가정합니다. 각 동전은 처음에 머리를 보이고 있습니다. 그런 다음 n 명이 다음과 같이 해당 동전을 넘깁니다. 사람 i는 i의 배수 인 숫자로 동전을 뒤집습니다. 즉, 사람 i는 동전 i, 2 · i, 3 · i,을 뒤집습니다. . . 더 이상 적절한 동전이 남아 있지 않을 때까지. 목표는 꼬리를 보여주는 동전의 수를 세는 것입니다. 위의 예에서 최종 구성은 다음과 같습니다. ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/eyabc.js ================================================ function solution(N) { let i = 1, result = 0; while (i * i < N) { if (N % i === 0) result += 2; i++; } return result + (i*i === N); } console.log(solution(24) === 8); ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/khw970421.js ================================================ //정확성 효율성 100 function solution(N) { let cnt = 0; for(let i = 1; ; i++) { if(i>=Math.sqrt(N)){ //제곱근 전까지만 반복(만약 많이 커져도 갈수록 제곱근은 크게 늘어나는것이 아니기때문에 반복이 그나마 적다 break; } if (N % i == 0) { //제곱근 전까지의 약수의 갯수 구하기 cnt++; // 약수 개수 // i 약수 } } cnt*=2; // 제곱근 전과 후에 곱해야 원래 값이나오므로 2배하기 let q=Math.sqrt(N); //제곱근값 대입 if(Number.isInteger(q)) //제곱근 값이 만약 정수라면 그갯수도 포함해 더한다( 자신을 제곱하면 원래값이 되므로 ex) 5*5==25 , 4.321*4.321 != 24이므로) cnt++; return cnt; //합친값을 return } //피드백 후 코드 function solution1(N) { let cnt = 0; const q = Math.sqrt(N); for(let i = 1; i < q ;i++) cnt += N % i == 0; //제곱근까지 돌리면서 약수의 갯수를 구하기 N%i==0이면 결국 1이니 cnt=cnt+1이 되므로 약수희 갯수 증가 return cnt*2 + Number.isInteger(q); //제곱근 전까지의 값을 2배하고 제곱근이 정수인 값이라면 그 값도 더해야 하기때문에 1을 더한다. // (Number.isInteger는 T/F 받으므로 T이면 더했을때 1로 처리되서 더하기 때문에 가능 } ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/sAp00n.py ================================================ import time start = time.time() def solution(N): number_of_factors = 0 i = 1 while i*i < N: if N % i == 0: number_of_factors += 2 i += 1 if i * i == N: number_of_factors += 1 return number_of_factors print(solution(1)) print(f'time = {time.time()-start}') ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(N): # write your code in Python 3.6 pass i = 1 while i * i <= N: i += 1 i -= 1 cnt = 0 for j in range(1, i + 1): cnt += 1 if N % j == 0 else 0 j += 1 return (cnt * 2 if i * i != N else cnt * 2 - 1) print( solutiion(24) == 8 ) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.CountFactors/sjjyy.java ================================================ package lessons.lesson10.PrimeAndCompositeNumbers.CountFactors; class sjjyy { public static int solution(int N) { int result = 0; double sqrt = Math.sqrt(N); for (int i = 1 ; i <= sqrt ; i++) { if (N % i == 0) result++; } result = result * 2; // pair if (sqrt * sqrt == N) result--; return result; } public static void main(String[] args) { int N = 24; System.out.println(solution(N)); // 8 } } ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Flags/Flag.md ================================================ # Flag ## Description `O(N)` preprocessing (done inplace): ```js A[i] := next peak or end position after or at position i (i for a peak itself, len(A) after last peak) ``` If we can plant `k` flags then we can certainly plant `k' < k` flags as well. If we can not plant `k` flags then we certainly can not plant `k' > k` flags either. We can always set 0 flags. Let us assume we can not set `X` flags. Now we can use binary search to find out exactly how many flags can be planted. ```js Steps: 1. X/2 2. X/2 +- X/4 3. X/2 +- X/4 +- X/8 ... log2(X) steps in total ``` With the preprocessing done before, each step testing whether `k` flags can be planted can be performed in `O(k)` operations: - flag(0) = next(0) - flag(1) = next(flag(1) + k) ... - flag(k-1) = next(flag(k-2) + k) total cost - worst case - when `X - 1` flags can be planted: > == X * (1/2 + 3/4 + ... + (2^k - 1)/(2^k)) > == X * (log2(X) - 1 + (<1)) > <= X * log(X) Using `X == N` would work, and would most likely also be sublinear, but is not good enough to use in a proof that the total upper bound for this algorithm is under `O(N)`. Now everything depends on finding a good `X`, and it since `k` flags take about `k^2` positions to fit, it seems like a good upper limit on the number of flags should be found somewhere around `sqrt(N)`. If `X == sqrt(N)` or something close to it works, then we get an upper bound of `O(sqrt(N) * log(sqrt(N)))` which is definitely sublinear and since `log(sqrt(N)) == 1/2 * log(N)` that upper bound is equivalent to `O(sqrt(N) * log(N))`. Let's look for a more exact upper bound on the number of required flags around `sqrt(N)`: - we know `k` flags requires `Nk := k^2 - k + 3` flags - by solving the equation `k^2 - k + 3 - N = 0` over `k` we find that if `k >= 3`, then any number of flags <= the resulting `k` can fit in some sequence of length N and a larger one can not; solution to that equation is `1/2 * (1 + sqrt(4N - 11))` - for `N >= 9` we know we can fit 3 flags ==> for `N >= 9`, `k = floor(1/2 * (1 + sqrt(4N - 11))) + 1` is a strict upper bound on the number of flags we can fit in `N` - for `N < 9` we know 3 is a strict upper bound but those cases do not concern us for finding the big-O algorithm complexity > floor(1/2 * (1 + sqrt(4N - 11))) + 1 > == floor(1/2 + sqrt(N - 11/4)) + 1 > <= floor(sqrt(N - 11/4)) + 2 > <= floor(sqrt(N)) + 2 ==> `floor(sqrt(N)) + 2` is also a good strict upper bound for a number of flags that can fit in `N` elements + this one holds even for `N < 9` so it can be used as a generic strict upper bound in our implementation as well If we choose `X = floor(sqrt(N)) + 2` we get the following total algorithm upper bound: ```js O((floor(sqrt(N)) + 2) * log(floor(sqrt(N)) + 2)) {floor(...) <= ...} O((sqrt(N) + 2) * log(sqrt(N) + 2)) {for large enough N >= 4: sqrt(N) + 2 <= 2 * sqrt(N)} O(2 * sqrt(N) * log(2 * sqrt(N))) {lose the leading constant} O(sqrt(N) * (log(2) + loq(sqrt(N))) O(sqrt(N) * log(2) + sqrt(N) * log(sqrt(N))) {lose the lower order bound} O(sqrt(N) * log(sqrt(N))) {as noted before, log(sqrt(N)) == 1/2 * log(N)} O(sqrt(N) * log(N)) QED ``` ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Flags/JeongShin.js ================================================ /* 이 문제는 다음에 다시 시도해보겠습니다 어렵네요 ㅠ ㅠ 시간 복잡도 측면에서 해결이 안되네요. */ function solution(A) { const [peeks, last] = A.reduce(([peek, last_peek], curr, idx) => { const [p, n] = [A[idx - 1], A[idx + 1]] || curr if (curr > p && curr > n) { last_peek !== undefined ? peek.push(idx - last_peek) : null return [peek, idx]; } return [peek, last_peek]; }, [[], undefined]); if (last === undefined) return 0 if (peeks.length === 0) return 1 let flags = new Array(peeks.length).fill(1) let acc = new Array(peeks.length).fill(0) for (const val of peeks) acc = acc.map((curr, idx) => (val + curr) / (idx + 1) > 1 ? (flags[idx]++, 0) : (val + curr)) flags = flags.map((curr, idx) => Math.min(idx + 2, curr)) return Math.max(...flags); } ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Flags/eyabc.js ================================================ const createPeaks = (A) => { const len = A.length; const peaks = new Array(len).fill(false); for (let i = 1; i < len - 1; i++) { if (A[i] > Math.max(A[i - 1], A[i + 1])) { peaks[i] = true; } } return peaks; }; /* Check whether x flags can be set * If we know that x flags can be set, * then we also know that x−1, x−2, . . . , 1 flags can be set. * Otherwise, if x flags cannot be set, then x+1, x+2, . . . , √ N flags cannot be set either. * */ const check = (x, A) => { const N = A.length; const peaks = createPeaks(A); let flags = x; let pos = 0; while (pos < N && flags > 0) { if (peaks[pos]) { flags -= 1; pos += x; } else pos += 1; } return flags === 0; }; /* Next peak * * */ const next_peak = A => { const N = A.length; const peaks = createPeaks(A); console.log({peaks}); const next = new Array(N).fill(0); next[N - 1] = -1; for (let i = N - 2; i > -1; i--) { if (peaks[i]) next[i] = i; else next[i] = next[i + 1] } return next }; function solution(A) { const N = A.length; const next = next_peak(A); let i = 1, result = 0; while((i - 1) * i <= N) { let pos = 0, num = 0; while (pos < N && num < i) { pos = next[pos]; if (pos == -1) break; num += 1; pos += i; } result = Math.max(result, num); i += 1 } return result } console.log( solution([1, 3, 1, 4, 1]) === 2, solution([0, 1000000000, 0]) === 1, solution([1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2]) === 3, solution( [0, 0, 0, 0, 0, 1, 0, 1, 0, 1]) === 2, ); ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Flags/sAp00n.py ================================================ # [3, 2, 1] #[0, 0, 0, 0, 0, 1, 0, 1, 0, 1] #[1,5,3,4,3,4,1,2,3,4,6,2] from math import sqrt def transform(A): peak_pos = len(A) last_height = A[-1] for p in range(len(A) - 1, 0, -1): if (A[p - 1] < A[p] > last_height): peak_pos = p last_height = A[p] A[p] = peak_pos A[0] = peak_pos def can_fit_flags(A, k): flag = 1 - k for i in range(k): # plant the next flag at A[flag + k] if flag + k > len(A) - 1: return False flag = A[flag + k] return flag < len(A) # last flag planted successfully def solution(A): transform(A) lower = 0 upper = int(sqrt(len(A))) + 2 assert not can_fit_flags(A, k=upper) while lower < upper - 1: next = (lower + upper) // 2 if can_fit_flags(A, k=next): lower = next else: upper = next return lower A = [1,5,3,4,3,4,1,2,3,4,6,2] print(solution(A)) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Flags/sangmandu.py ================================================ def solution(A): # write your code in Python 3.6 pass B = [ i for i in range(1, len(A) - 1) if max(A[i - 1], A[i + 1]) < A[i] ] size = len(B) if size == 0: return 0 C = [ B[i] - B[i - 1] for i in range(1, size) ] maxFlags = 1 for i in range(2, size + 1): flags = 1 dist = 0 for j in C: dist += j if flags == i: break if dist < i: continue flags += 1 dist = 0 maxFlags = max(maxFlags, flags) if flags != i and maxFlags != flags: break return maxFlags print( solution([1,5,3,4,3,4,1,2,3,4,6,2] == 3) ) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle/JeongShin.js ================================================ function solution(N) { const n = Math.sqrt(N); let min = Infinity for (let x = 1; x <= n; x++) { const [y, r] = [N / x, N % x] min = r === 0 ? Math.min(2 * (x + y), min) : min } return min; } solution(1) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle/NowonLee.js ================================================ function solution(N) { let l = [] for(let i = 1;i*i<=N;i++){ if(N%i == 0) l.push(i) } /* const nums = l.map(el => { return 2*(el + (N/el)) }) return Math.min(...nums) */ return l.reduce((min, el) => { return Math.min(min, 2 * (el + N/el)) }, Infinity) } console.log(solution(36)===24) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle/README.md ================================================ # 출처 https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/min_perimeter_rectangle/ # 번역 ```text 일부 사각형의 영역을 나타내는 정수 N이 제공됩니다. 변의 길이가 A이고 B 인 직사각형 의 넓이 는 A * B이고 둘레 는 2 * (A + B)입니다. 목표는 면적이 N 인 직사각형의 최소 둘레를 찾는 것입니다.이 직사각형의 변은 정수만되어야합니다. 예를 들어, 정수 N = 30 인 경우 영역 30의 사각형은 다음과 같습니다. (1, 30), 둘레 62의 (2, 15), 둘레가 34, 둘레가 26 인 (3, 10) (5, 6), 둘레는 22입니다. 함수를 작성하십시오. 기능 솔루션 (N); 정수 N이 주어지면 면적이 정확히 N 인 사각형의 최소 둘레를 반환합니다. 예를 들어, 정수 N = 30 인 경우 함수는 위에서 설명한대로 22를 반환해야합니다. 다음 가정을위한 효율적인 알고리즘을 작성하십시오 . N은 [ 1 .. 1,000,000,000 ] 범위 내의 정수 이다. ``` # 원문 ``` An integer N is given, representing the area of some rectangle. The area of a rectangle whose sides are of length A and B is A * B, and the perimeter is 2 * (A + B). The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers. For example, given integer N = 30, rectangles of area 30 are: (1, 30), with a perimeter of 62, (2, 15), with a perimeter of 34, (3, 10), with a perimeter of 26, (5, 6), with a perimeter of 22. Write a function: class Solution { public int solution(int N); } that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N. For example, given an integer N = 30, the function should return 22, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..1,000,000,000]. ``` ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle/eyabc.js ================================================ // 최소 공약수의 쌍중 갭이 가장 작은 것의 둘레를 구한다 function solution (N) { for (let a = ~~Math.sqrt(N); a > 0; a--) { if (!(N % a)) { const b = N / a; return 2 * (a + b); } } } console.log(solution(982451653)) console.log(solution(10000000000)) console.log(solution(1)) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle/khw970421.js ================================================ //정확성 효율성 100 function solution(N) { let count=0; let num=[]; let q=Math.sqrt(N); if(Number.isInteger(q)) //약수가 홀수개일때 가장 작은 값은 루트한 값을 4배한것 return 4*q; for(let i=1; i<=Math.sqrt(N); i++) //약수가 짝수개일때 루트값 전까지 약수를 구한다 { if(N % i == 0) { count++; num.push(i); } } const l=num.length; let k = N/num[l-1]; //가장 마지막 값은 N의 약수의 중간값이기 때문에 그다음 값 k를구한다. ex) 8=40/5 return 2*(k+num[l-1]); //두개를 더하고 곱한값을 return } //수정본 function solution1(N) { const num=[]; const q=Math.sqrt(N); if(Number.isInteger(q)) //약수가 홀수개일때 가장 작은 값은 루트한 값을 4배한것 return 4*q; for(let i=1; i<=q; i++) //약수가 짝수개일때 루트값 전까지 약수를 구한다 if(N % i == 0) num.push(i); const l=num.pop(); const k = N/l; //가장 마지막 값은 N의 약수의 중간값이기 때문에 그다음 값 k를구한다. ex) 8=40/5 return 2*(k+l); //두개를 더하고 곱한값을 return } ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle/sAp00n.py ================================================ from random import randint def solution(N): couple_list = find_couple(N) return_val = find_min_perimeter(couple_list) return return_val def find_couple(A): i = 1 list_of_couple = [] while i * i <= A: if A % i == 0: val01 = i val02 = int(A / i) couple = (min(val01, val02), max(val01, val02)) if couple not in list_of_couple: list_of_couple.append(couple) i += 1 if A == i: list_of_couple.append((1, 1)) return list_of_couple def find_min_perimeter(list_of_couple): min_perimeter = 2 * (list_of_couple[0][0] + list_of_couple[0][1]) list_length = len(list_of_couple) if list_length == 2: min_perimeter = min(min_perimeter, 2 * (list_of_couple[1][0] + list_of_couple[1][1])) else: for idx in range(2, len(list_of_couple)): min_perimeter = min(min_perimeter, 2 * (list_of_couple[idx][0] + list_of_couple[idx][1])) return min_perimeter ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(N): # write your code in Python 3.6 M = N ** (1 / 2) M = int(M) for i in range(M, 0, -1): if N % i == 0: return int(N / i + i) * 2 print( solution(30) == 22 ) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle/sjjyy.java ================================================ package lessons.lesson10.PrimeAndCompositeNumbers.MinPerimeterRectangle; class sjjyy { public static int solution(int N) { int a = 0, b = 0; int min = 0; int len = (int)Math.sqrt(N); for(int i = 1 ; i <= len ; i++) { if(N % i == 0) a = i; } b = N/a; min = (a + b) * 2; return min; } public static void main(String[] args) { int N = 30; System.out.println(solution(N)); // 22 } } ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Peaks/JeongShin.js ================================================ function solution(A) { const len = A.length; const peeks = A.reduce((peeks, curr, idx) => { if (curr > A[idx - 1] && curr > A[idx + 1]) peeks.push(idx); return peeks; }, []); let k = peeks.length; while (k > 0) { if (len % k) { k-- continue } const size = len / k const result = peeks.reduce(([count, from, to], curr) => curr < from ? [count, from, to] : [count + (from <= curr && curr <= to), from + size, to + size] , [0, 0, size - 1])[0]; if (result === k) return k; k--; } return 0; } ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Peaks/README.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/peaks/ ## 원문 ``` A non-empty array A consisting of N integers is given. A peak is an array element which is larger than its neighbors. More precisely, it is an index P such that 0 < P < N − 1, A[P − 1] < A[P] and A[P] > A[P + 1]. For example, the following array A: A[0] = 1 A[1] = 2 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2 has exactly three peaks: 3, 5, 10. We want to divide this array into blocks containing the same number of elements. More precisely, we want to choose a number K that will yield the following blocks: A[0], A[1], ..., A[K − 1], A[K], A[K + 1], ..., A[2K − 1], ... A[N − K], A[N − K + 1], ..., A[N − 1]. What's more, every block should contain at least one peak. Notice that extreme elements of the blocks (for example A[K − 1] or A[K]) can also be peaks, but only if they have both neighbors (including one in an adjacent blocks). The goal is to find the maximum number of blocks into which the array A can be divided. Array A can be divided into blocks as follows: one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block contains three peaks. two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block has a peak. three blocks (1, 2, 3, 4), (3, 4, 1, 2), (3, 4, 6, 2). Every block has a peak. Notice in particular that the first block (1, 2, 3, 4) has a peak at A[3], because A[2] < A[3] > A[4], even though A[4] is in the adjacent block. However, array A cannot be divided into four blocks, (1, 2, 3), (4, 3, 4), (1, 2, 3) and (4, 6, 2), because the (1, 2, 3) blocks do not contain a peak. Notice in particular that the (4, 3, 4) block contains two peaks: A[3] and A[5]. The maximum number of blocks that array A can be divided into is three. Write a function: class Solution { public int solution(int[] A); } that, given a non-empty array A consisting of N integers, returns the maximum number of blocks into which A can be divided. If A cannot be divided into some number of blocks, the function should return 0. For example, given: A[0] = 1 A[1] = 2 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2 the function should return 3, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [0..1,000,000,000]. ``` ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Peaks/sAp00n.py ================================================ def find_peaks(A): peak_logical_list = [0 for i in range(len(A))] # Peak Node == 1 else == 0 past_element, current_element, next_element = A[0:3] peak_num = 0 if past_element < current_element > next_element: peak_logical_list[1] = 1 peak_num += 1 for idx in range(1, len(A) - 1): past_element = A[idx - 1] current_element = A[idx] next_element = A[idx + 1] if past_element < current_element > next_element: peak_logical_list[idx] = 1 peak_num += 1 #print(peak_logical_list) if peak_num == 0: return False return peak_logical_list def find_Max_subunit_number(logical_list): list_length = len(logical_list) forward_candidate = logical_list.index(1) + 1 logical_list.reverse() backward_candidate = logical_list.index(1) + 1 # print(f'for:{forward_candidate} back: {backward_candidate}') return_val = min(forward_candidate, backward_candidate) return int(list_length / return_val) def check_function(logical_list, number_of_subunit): if len(logical_list) % number_of_subunit != 0: return False subunit_len = int(len(logical_list) / number_of_subunit) start_slice = 0 end_slice = subunit_len if number_of_subunit == 1: for ele in logical_list: if ele == 1: return True for i in range(0, number_of_subunit): subunit = logical_list[start_slice:end_slice] #print(f'subunit = {subunit}') for ele in subunit: if ele == 1: return True #print(f'checker :{checker}') start_slice += subunit_len end_slice += subunit_len #print(f'check result: {checker}') return False def solution(A): if len(A) < 3: return 0 logical_list = find_peaks(A) if logical_list == False: return 0 Max_subunit_number = find_Max_subunit_number(logical_list) subunit_number = Max_subunit_number while subunit_number >= 1: #print(f'subunit_num = {subunit_number}') temp = check_function(logical_list, subunit_number) if temp == True: return subunit_number subunit_number -= 1 return 0 #A = [1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2] A= [1, 2, 3, 4, 5, 6, 5, 5, 5, 6, 5, 6] print(solution(A)) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Peaks/sangmandu.py ================================================ # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 B = [i for i in range(1, len(A) - 1) if max(A[i - 1], A[i + 1]) < A[i]] sizeB = len(B) if len(B) == 0: return 0 sizeA = len(A) sqrt = int(sizeA ** (1 / 2)) div = [sizeA // i for i in range(1, sqrt + 1) if sizeA % i == 0 and i <= sizeB] temp = [] for i in div[::-1]: if i > sizeB: break temp.append(sizeA // i) div += temp maxBlank = 0 for i in div: blank = [B[j] // i for j in range(sizeB)] if len(set(blank)) == sizeA // i: maxBlank = max(maxBlank, sizeA // i) return maxBlank print( solution([1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2]) == 3 ) ================================================ FILE: codility_training/lessons.lesson10.PrimeAndCompositeNumbers.Peaks/sjjyy.java ================================================ package lessons.lesson10.PrimeAndCompositeNumbers.Peaks; import java.util.ArrayList; public class sjjyy { public static int solution(int[] A) { int len = A.length; ArrayList peaks = new ArrayList<>(); for(int i = 1 ; i < len-1 ; i++) { if(A[i-1] < A[i] && A[i+1] < A[i]) peaks.add(i); } if(peaks.size() <= 1) return peaks.size(); for(int num = len ; num >= 1 ; num--) { // 1st method if (len % num == 0) { int size = len / num; int block = 0; for(int j : peaks) { if(j / size == block) block++; } if(block == num) return num; } /* 2nd method - time-out error if (len % num != 0) continue; int size = len / num; int block = peaks.stream() .reduce(0, (n, j) -> n + (j / size == n ? 1 : 0)); if(block == num) return num; */ } return 0; } public static void main(String[] args) { int [] A = {1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2}; int [] B = {1, 3, 2, 1}; int [] C = {0, 1, 0, 0, 0}; System.out.println(solution(A)); // 3 System.out.println(solution(B)); // 1 System.out.println(solution(C)); // 1 } } ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountNonDivisible/JeongShin.js ================================================ function solution(A) { const len = A.length const max = Math.max(...A) const count = {} let ones = 0 for (const val of A) { if (val === 1) { ones++ continue } for (let i = 1; (i * val) <= max; i++) count[i * val] = (count[i * val] || 0) + 1 } return A.map(el => len - (count[el] || 0) - ones) } // solution([3, 1, 2, 3, 6]) ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountNonDivisible/README.md ================================================ 번역 - N 정수로 구성된 배열 A가 주어진다. 각 숫자 A[i]에 대해 0 ≤ i < N에 대해, A[i]의 약수가 아닌 배열의 요소 수를 세고자 한다. 우리는 이 원소들이 약수가 아니라고 말한다. 예시의 다음 N = 5 인 배열 A를 고려하십시오. A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 3 A[4] = 6 다음 원소의 경우: A[0] = 3, non-divisors: 2, 6, A[1] = 1, non-divisors: 3, 2, 3, 6, A[2] = 2, non-divisors: 3, 3, 6, A[3] = 3, non-divisors: 2, 6, A[4] = 6, non-divisors: 없다. 함수를 작성하시오: def solution(A) N개의 정수로 구성된 배열 A가 주어진 경우, non-약수의 양을 나타내는 일련의 정수를 반환한다. 결과 배열을 정수의 배열로 반환해야 한다. 예를 들어, 다음과 같다. A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 3 A[4] = 6 함수는 위에서 설명한 대로 [2, 4, 3, 2, 0]을 반환해야 한다. 다음과 같은 가정에 대해 효율적인 알고리즘을 작성하십시오. N은 [1..50,000] 범위 내의 정수; 배열 A의 각 요소는 [1..] 범위 내의 정수다.2 * N] 원문 - You are given an array A consisting of N integers. For each number A[i] such that 0 ≤ i < N, we want to count the number of elements of the array that are not the divisors of A[i]. We say that these elements are non-divisors. For example, consider integer N = 5 and array A such that: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 3 A[4] = 6 For the following elements: A[0] = 3, the non-divisors are: 2, 6, A[1] = 1, the non-divisors are: 3, 2, 3, 6, A[2] = 2, the non-divisors are: 3, 3, 6, A[3] = 3, the non-divisors are: 2, 6, A[4] = 6, there aren't any non-divisors. Write a function: def solution(A) that, given an array A consisting of N integers, returns a sequence of integers representing the amount of non-divisors. Result array should be returned as an array of integers. For example, given: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 3 A[4] = 6 the function should return [2, 4, 3, 2, 0], as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..50,000]; each element of array A is an integer within the range [1..2 * N]. ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountNonDivisible/eyabc.js ================================================ function solution (A) { const len = A.length; const cnt = A.reduce((cnt, v) => (cnt[v] = (cnt[v] || 0) + 1, cnt), {}); return A.map(v => { let divisor = 0; for (let j = 1 ; j * j <= v ; j++) { if (v % j === 0) { divisor += cnt[j] || 0; if (v / j !== j) divisor += cnt[v / j] || 0; } } return len - divisor; }); } console.log( solution([3, 1, 2, 3, 6]), solution([2]), solution([ 6, 7, 2, 1, 4, 7, 4, 4, 1, 8, 10, 15 ]) ); ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountNonDivisible/sAp00n.py ================================================ def solution(A): element_dict = {} for element in A: element_dict[element] = 0 Max_element = max(A) for element in A: i = 1 temp = element * i while temp <= Max_element: if temp in element_dict: element_dict[temp] += 1 i += 1 temp = element * i A_len = len(A) for idx in range(A_len): A[idx] = A_len - element_dict[A[idx]] return A A = [3, 1, 1, 2, 2, 3, 6] print(solution(A)) ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountNonDivisible/sjjyy.java ================================================ package lessons.lesson11.SieveofEratosthenes.CountNonDivisible; // import java.util.ArrayList; import java.util.Arrays; import java.util.stream.IntStream; public class sjjyy { /* public static int[] solution(int[] A) // error { int len = A.length; ArrayList div = new ArrayList(); for(int i = 0 ; i < len ; i++) div.add(A[i]); int [] count = {}; for (int i = 0 ; i < len ; i++) { int division = 0; for (int j = 1; j * j <= A[i] ; j++) { if(A[i] % j == 0) { division += div.get(j); if (A[i] / j != j) division += div.get(A[i] / j); } } count[i] = len - division; } return count; } */ public static int[] solution(int[] A) { int len = A.length; // int max = A[0]; // for (int i = 1 ; i < len ; i++) // max = Math.max(max, A[i]); int max = IntStream.range(1, len).reduce(A[0], (m, i) -> Math.max(m, A[i])); int [] count = new int [max+1]; IntStream.range(0, len).forEach(i -> count[A[i]]++); int [] nonDiv = new int [max+1]; int len2 = nonDiv.length; for (int i = 1 ; i < len2 ; i++) { if (count[i] != 0) nonDiv[i] = len - count[i]; } //sieve for (int i = 1 ; i < len2 ; i++) { if (count[i] != 0) { int s = i*2; while (s < len2) { if (nonDiv[s] != 0) nonDiv[s] -= count[i]; s+=i; } } } // int [] result = new int [len]; // for (int i = 0 ; i < len ; i++) // { // result[i] = nonDiv[A[i]]; // } // return result; return IntStream.range(0, len).map(i -> nonDiv[A[i]]).toArray(); } public static void main(String[] args) { int [] A = {3, 1, 2, 3, 6}; System.out.println(Arrays.toString(solution(A))); // [2, 4, 3, 2, 0] } } ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountSemiprimes/JeongShin.js ================================================ function solution(N, P, Q) { const semi_primes = new Array(N + 1).fill(0) for (let i = 2; i <= N; i++) { if (semi_primes[i] === 0) { for (let j = i * i; j <= N; j += i) if (semi_primes[j] === 0) semi_primes[j] = i; } } semi_primes[0] = 1; // 1 is not prime num const semi_primes_count = semi_primes.reduce(([arr, acc], curr, idx) => { if (curr !== 0) acc += (semi_primes[idx / curr] === 0) * 1 arr.push(acc); return [arr, acc]; }, [[], 0])[0] return P.map((P, idx) => (semi_primes_count[Q[idx]] - (semi_primes_count[P - 1] || 0))) // P 자기자신 포함,직전 ~ Q 까지 차이 } ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountSemiprimes/READMD.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/11-sieve_of_eratosthenes/count_semiprimes/ ## 원문 A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13. A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26. You are given two non-empty arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges. Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N. For example, consider an integer N = 26 and arrays P, Q such that: P[0] = 1 Q[0] = 26 P[1] = 4 Q[1] = 10 P[2] = 16 Q[2] = 20 The number of semiprimes within each of these ranges is as follows: (1, 26) is 10, (4, 10) is 4, (16, 20) is 0. Write a function: class Solution { public int[] solution(int N, int[] P, int[] Q); } that, given an integer N and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M elements specifying the consecutive answers to all the queries. For example, given an integer N = 26 and arrays P, Q such that: P[0] = 1 Q[0] = 26 P[1] = 4 Q[1] = 10 P[2] = 16 Q[2] = 20 the function should return the values [10, 4, 0], as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..50,000]; M is an integer within the range [1..30,000]; each element of arrays P, Q is an integer within the range [1..N]; P[i] ≤ Q[i]. ## 설명 - 프라임 : 소수, 2, 3, 5, 7, 11 및 13 - 세미프라임 : 두개의 소수로 이뤄진 수, 4, 6, 9, 10, 14, 15, 21, 22, 25, 26 매개변수 N P Q가 주어질 때, 1 ≤ P [K] ≤ Q [K] ≤ N. 이다. 예를 들어 정수 N = 26 및 배열 P, Q 등을 고려하십시오. P[0] = 1 Q[0] = 26 P[1] = 4 Q[1] = 10 P[2] = 16 Q[2] = 20 이러한 각 범위 내에서 세미프라임 수는 다음과 같습니다. (1, 26)은 10, (4, 10)은 4, (16, 20)은 0입니다. [10, 4, 0]을 반환 ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountSemiprimes/eyabc.js ================================================ function solution (N, P, Q) { const semiCnt = new Array(N + 1).fill(0), maxNum = N + 1; // 참고함 const isSemi = (num) => { let cnt = 0; for (let i = 2 ; cnt < 2 && i * i <= num ; ++i) while (num % i === 0) num /= i, ++cnt; if (num > 1) ++cnt; return cnt === 2; }; for (let i = 1 ; i < maxNum ; i++) semiCnt[i] = semiCnt[i - 1] + (isSemi(i) ? 1 : 0); return P.map((start, k) => semiCnt[Q[k]] - semiCnt[start - 1]); } console.log( solution(26, [1, 4, 16], [26, 10, 20]).toString() === [10, 4, 0].toString(), solution(50, [1, 2, 3, 4, 10], [50, 49, 48, 40, 30]).toString() === [17, 17, 16, 15, 7].toString(), ); ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountSemiprimes/sAp00n.py ================================================ def solution(N, P, Q): from math import sqrt prime_table = [False]*2+[True]*(N-1) prime = [] prime_count = 0 for element in range(2, int(sqrt(N))+1): if prime_table[element] == True: prime.append(element) prime_count += 1 multiple = element * element while multiple <= N: prime_table[multiple] = False multiple += element for element in range(int(sqrt(N))+1, N+1): if prime_table[element] == True: prime.append(element) prime_count += 1 semiprime = [0] * (N+1) for index_former in range(prime_count-1): for index_latter in range(index_former, prime_count): if prime[index_former]*prime[index_latter] > N: break semiprime[prime[index_former]*prime[index_latter]] = 1 for index in range(1, N+1): semiprime[index] += semiprime[index-1] question_len = len(P) result = [0]*question_len for index in range(question_len): result[index] = semiprime[Q[index]] - semiprime[P[index]-1] return result print(solution(P=[1, 4, 16], Q=[26, 10, 20], N=26)) ================================================ FILE: codility_training/lessons.lesson11.SieveofEratosthenes.CountSemiprimes/sjjyy.java ================================================ package lessons.lesson11.SieveofEratosthenes.CountSemiprimes; import java.util.Arrays; public class sjjyy { public static int[] solution(int N, int[] P, int[] Q) { int len = P.length; int [] result = new int [len]; int [] presum = new int [N+1]; int [] flag = new int [N+1]; flag[0] = 1; flag[1] = 1; for(int i = 2 ; i*i <= N ; i++) { if (flag[i] == 1) continue; int j = i * i; while (j <= N) { flag[j] = 1; j += i; } } for(int i = 2 ; i*i <= N ; i++) { if(flag[i] == 1) continue; int j = i * i; while (j <= N) { if (flag[i] == 0 && flag[j / i] == 0) flag[j] = 2; j += i; } } int sem_prime_counter = 0; for(int i = 2 ; i <= N ; i++) { if(flag[i] == 2) sem_prime_counter++; presum[i] = sem_prime_counter; } for(int i = 0 ; i < len ; i++) result[i] = presum[Q[i]] - presum[P[i]-1]; return result; } private static int [] seive(int N) { int [] seive = new int[N + 1]; int i = 2; while (i * i <= N) { if(seive[i] == 0) { int j = i * i; while (j <= N) { if(seive[j] == 0) seive[j] = i; j += i; } } i++; } int len = seive.length; int [] flags = new int[len]; for(int k = 2 ; k < len ; k++) { if (seive[k] == 0) flags[k] = k; else flags[k] = seive[k]; } return flags; } public static int[] solution2(int N, int[] P, int[] Q) { int [] flag = new int [N+1]; int [] seive = seive(N); int len = flag.length; int Plen = P.length; for(int i = 4 ; i < len ; i++) { if (seive[i] * seive[i / seive[i]] == i) { flag[i] = 1; } } int[] preSum = new int[len]; for (int i = 1; i < len; i++) { preSum[i] = preSum[i - 1] + flag[i]; } int[] result = new int[Plen]; for (int i = 0; i < Plen; i++) { result[i] = preSum[Q[i]] - preSum[P[i] - 1]; } return result; } public static void main(String[] args) { int[] P = {1, 4, 16}; int[] Q = {26, 10, 20}; int N = 26; System.out.println(Arrays.toString(solution(N, P, Q))); // [10, 4, 0] System.out.println(Arrays.toString(solution2(N, P, Q))); // [10, 4, 0] } } ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.ChocolatesByNumbers/EuclideanAlgorithm.md ================================================ # 유클리드 알고리즘 두 양의 정수의 최대 공약수 (gcd)를 계산하는 문제를 해결합니다. 왜 이게 되는지 모르겠음.. 별로 알고싶지도 않아..!! ## 12.1 차를 이용한 유클리드 알고리즘 ```javascript function gcd (a, b) { if (a === b) return a; if (a > b) gcd(a - b, b); else gcd(a, b - a); } ``` ## 12.2 나누기를 이용한 유클리드 알고리즘 when, a > b ```javascript function gcd(a, b) { if (a % b === 0) return b; else return gcd(b, a % b); } ``` ### 12.3 이진 유클리드 알고리즘 - shifting and parity testing - divide and conquer technique 안됨 ```javascript function gcd(a, b, res) { if (a === b) return res * a; else if (a % 2 === 0 && b % 2 === 0) return gcd( ~~(a / 2), ~~(b / 2), 2 * res) else if (a % 2 === 0) return gcd(~~(a / 2), b, res) else if (b % 2 === 0) return gcd(a, ~~(b / 2), res) else if (a > b) return gcd(a - b, b, res) else return gcd(a, b - a, res) } ``` ## Least common multiple a*b / gcd(a, b) ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.ChocolatesByNumbers/JeongShin.js ================================================ function solution(N, M) { const gcd = (a, b) => { if (a % b === 0) return b; else return gcd(b, a % b) } return ((N * M / gcd(N, M)) / M) } solution(10, 4) ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.ChocolatesByNumbers/README.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/12-euclidean_algorithm/chocolates_by_numbers/ ## 원문 ``` Two positive integers N and M are given. Integer N represents the number of chocolates arranged in a circle, numbered from 0 to N − 1. You start to eat the chocolates. After eating a chocolate you leave only a wrapper. You begin with eating chocolate number 0. Then you omit the next M − 1 chocolates or wrappers on the circle, and eat the following one. More precisely, if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division). You stop eating when you encounter an empty wrapper. For example, given integers N = 10 and M = 4. You will eat the following chocolates: 0, 4, 8, 2, 6. The goal is to count the number of chocolates that you will eat, following the above rules. Write a function: class Solution { public int solution(int N, int M); } that, given two positive integers N and M, returns the number of chocolates that you will eat. For example, given integers N = 10 and M = 4. the function should return 5, as explained above. Write an efficient algorithm for the following assumptions: N and M are integers within the range [1..1,000,000,000]. ``` ## 해석 입력 ```javascript function solution(N, M) { // write your code in JavaScript (Node.js 8.9.4) return 0; } ``` - 입력: 양수 N, M - N : 0 ~ (N-1) 번호가 매겨진 원에 배치된 초콜릿의 수 - 원이기 때문에 로테이션 가능하다. - 초콜릿을 번호0부터 먹기 시작합니다. - 다음 먹는 초콜릿의 번호는 (현재번호 + M ) 입니다 - 다음 먹을 번호에 초콜릿이 없을 때 중단합니다. - 예시: N = 10 및 M = 4. 0, 4, 8, 2, 6 - 반환: 먹은 초콜릿의 수 ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.ChocolatesByNumbers/eyabc.js ================================================ // 초콜릿을 먹는 index만 보면 0부터 시작해서 N과 M의 최대 공약수의 배수(< N) 라고 합니다. function solution (N, M) { const gcd = (a, b) => a % b === 0 ? b : gcd(b, a % b); return ~~(N / gcd(N, M)); } console.log( solution(10, 4), solution(30, 120) ); ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.ChocolatesByNumbers/sAp00n.py ================================================ def solution(N, M): def gcd(N, M): if N % M == 0: return M else: return gcd(M, N % M) return N // gcd(N, M) print(solution(10, 4)) ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.ChocolatesByNumbers/sjjyy.java ================================================ package lessons.lesson12.EuclideanAlgorithm.ChocolatesByNumbers; public class sjjyy { public static int solution(int N, int M) { return N/(gcd(N,M)); } public static int gcd(int a, int b) // using Uclidean algorithm { // if(a % b == 0) // return b; // else // return gcd(b, a % b); return a % b == 0 ? b : gcd(b, a % b); } public static void main(String[] args) { int N = 10; int M = 4; System.out.println(solution(N, M)); // 5 } } ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.CommonPrimeDivisors/JeongShin.js ================================================ const gcd = (a, b) => a % b === 0 ? b : gcd(b, a % b); function solution(A, B) { let count = 0; const len = A.length; for (let i = 0; i < len; i++) { let [a, b] = [A[i], B[i]] const g = gcd(a, b); while (true) { const r = gcd(a, g) if (r === 1) break; a /= r; } while (true) { const r = gcd(b, g) if (r === 1) break; b /= r; } count += (b === 1 && a === 1) } return count } // console.log(solution([10], [30])) ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.CommonPrimeDivisors/README.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/12-euclidean_algorithm/common_prime_divisors/ ## 원문 A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13. A prime D is called a prime divisor of a positive integer P if there exists a positive integer K such that D * K = P. For example, 2 and 5 are prime divisors of 20. You are given two positive integers N and M. The goal is to check whether the sets of prime divisors of integers N and M are exactly the same. For example, given: N = 15 and M = 75, the prime divisors are the same: {3, 5}; N = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5}; N = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}. Write a function: class Solution { public int solution(int[] A, int[] B); } that, given two non-empty arrays A and B of Z integers, returns the number of positions K for which the prime divisors of A[K] and B[K] are exactly the same. For example, given: A[0] = 15 B[0] = 75 A[1] = 10 B[1] = 30 A[2] = 3 B[2] = 5 the function should return 1, because only one pair (15, 75) has the same set of prime divisors. Write an efficient algorithm for the following assumptions: Z is an integer within the range [1..6,000]; each element of arrays A, B is an integer within the range [1..2,147,483,647]. ## 해석 - 입력: 양수 배열 N, M - 각각, N의 k번째 정수 n과, M의 k번째 정수 m의 제수(prime 나누는 수) 집합이 같으면 count 증가 ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.CommonPrimeDivisors/eyabc.js ================================================ function solution (A, B) { const getGCD = (a, b) => a % b === 0 ? b : getGCD(b, a % b); return A.reduce((cnt, a, k) => { let b = B[k]; const gcd = getGCD(a, b); let gcdA = 0, gcdB = 0; while (gcdA !== 1) { gcdA = getGCD(a, gcd); a = a / gcdA; } while (gcdB !== 1) { gcdB = getGCD(b, gcd); b = b / gcdB; } return cnt + (a + b === 2); }, 0); } console.log( solution([15, 10, 9], [75, 30, 5]) === 1, solution([1], [1]) === 1, solution([3, 9, 20, 11], [9, 81, 5, 13]) === 2, ) ; ================================================ FILE: codility_training/lessons.lesson12.EuclideanAlgorithm.CommonPrimeDivisors/sjjyy.java ================================================ package lessons.lesson12.EuclideanAlgorithm.CommonPrimeDivisors; import java.util.stream.IntStream; public class sjjyy { public static int solution(int[] A, int[] B) { int len = A.length; int count = 0; for(int i = 0 ; i < len ; i++) { if(prime(A[i], B[i])) count++; } return count; /* // time-out error return IntStream .range(0, len) .reduce(0, (count, i) -> count + (prime(A[i], B[i]) ? 1 : 0)); */ } private static int gcd(int a, int b) // using Uclidean algorithm { return a % b == 0 ? b : gcd(b, a % b); } private static boolean prime(int a, int b) { int g = gcd(a, b); int gcd_A = 0, gcd_B = 0; while (gcd_A != 1) { gcd_A = gcd(a, g); a = a / gcd_A; } while (gcd_B != 1) { gcd_B = gcd(b, g); b = b / gcd_B; } return a == 1 && b == 1; } public static void main(String[] args) { int[] A = {15, 10, 3}; int[] B = {75, 30, 5}; System.out.println(solution(A, B)); // 1 } } ================================================ FILE: codility_training/lessons.lesson13.FibonacciNumbers.FibFrog/JeongShin.js ================================================ function solution(A) { const len = A.length; let fib = [1, 1]; let idx = 2; while (fib[idx - 1] <= len) { fib.push(fib[idx - 1] + fib[idx - 2]); idx++; } A[len] = 1; const stack = [new frog(-1, 0)] const count = []; while (stack[0] !== undefined) { const curr = stack.pop() for (const jump of fib) { const next = curr.pos + jump; if (A[next] === 1) { const next_count = count[next] || Infinity if (next_count > (curr.count + 1)) { stack.push(new frog(next, curr.count + 1)) count[next] = curr.count + 1; } } } } return (count[len] || -1) } class frog { constructor(pos, count) { this.pos = pos; this.count = count; } } console.log(solution([1])) ================================================ FILE: codility_training/lessons.lesson13.FibonacciNumbers.FibFrog/README.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/13-fibonacci_numbers/fib_frog/ ## 원문 The Fibonacci sequence is defined using the following recursive formula: F(0) = 0 F(1) = 1 F(M) = F(M - 1) + F(M - 2) if M >= 2 A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N. The leaves on the river are represented in an array A consisting of N integers. Consecutive elements of array A represent consecutive positions from 0 to N − 1 on the river. Array A contains only 0s and/or 1s: 0 represents a position without a leaf; 1 represents a position containing a leaf. The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position −1 to position N). The frog can jump between positions −1 and N (the banks of the river) and every position containing a leaf. For example, consider array A such that: A[0] = 0 A[1] = 0 A[2] = 0 A[3] = 1 A[4] = 1 A[5] = 0 A[6] = 1 A[7] = 0 A[8] = 0 A[9] = 0 A[10] = 0 The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5. Write a function: class Solution { public int solution(int[] A); } that, given an array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return −1. For example, given: A[0] = 0 A[1] = 0 A[2] = 0 A[3] = 1 A[4] = 1 A[5] = 0 A[6] = 1 A[7] = 0 A[8] = 0 A[9] = 0 A[10] = 0 the function should return 3, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer that can have one of the following values: 0, 1. ================================================ FILE: codility_training/lessons.lesson13.FibonacciNumbers.FibFrog/sAp00n.py ================================================ def solution(A): A.append(1) N = len(A) fib = [0] * 27 fib[1] = 1 for i in range(2, 27): fib[i] = fib[i - 1] + fib[i - 2] if fib[i] > N: fib = fib[2:i] break reachable = [-1] * N for jump in fib: if A[jump - 1] == 1: reachable[jump - 1] = 1 for i in range(N): if not (A[i] == 1 and reachable[i] < 0): continue min, minidx = N + 1, -1 for jump in fib: pre = i - jump if pre < 0 or reachable[pre] < 0: continue if min > reachable[pre]: min, minidx = reachable[pre], pre if minidx != -1: reachable[i] = min + 1 return reachable[-1] A = [0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0] print(solution(A)) """B = [0, 0, 0] print(solution(B)) C = [1,1,0,0,0] print(solution(C))""" ================================================ FILE: codility_training/lessons.lesson13.FibonacciNumbers.FibFrog/sjjyy.java ================================================ package lessons.lesson13.FibonacciNumbers.FibFrog; import java.util.*; public class sjjyy { public static int solution(int[] A) // 83% { int aLen = A.length; List jmp = new ArrayList<>(); jmp.add(1); jmp.add(1); int next = 0; while (next < aLen -1) { next = jmp.get(jmp.size()-1) + jmp.get(jmp.size()-2); jmp.add(next); } // fibonacci int[] min = new int[aLen + 2]; Arrays.fill(min, Integer.MAX_VALUE); min[0] = 0; int mLen = min.length; for(int i = 0 ; i < mLen ; i++) { if(!(i == 0 || i == mLen - 1 || A[i-1] == 1)) continue; for(int j : jmp) { if(j > i) break; min[i] = (int) Math.min(min[i], (long) min[i-j]+1); } } if(min[mLen-1] == Integer.MAX_VALUE) return -1; return min[mLen-1]; } public static int solution2(int[] A) // modify { int aLen = A.length; if(aLen == 0) return 1; List jmp = new ArrayList<>(); jmp.add(1); jmp.add(1); int next = 1; while (jmp.get(next) <= aLen) { jmp.add(jmp.get(next) + jmp.get(next-1)); next++; } // github mkki님 참고 Collections.reverse(jmp); Queue q = new LinkedList<>(); boolean[] check = new boolean[aLen+1]; q.add(new Pair(-1, 0)); while(!q.isEmpty()) { Pair current = q.poll(); for(int f : jmp) { int n = current.x + f; if(n == aLen) return current.y + 1; if(n < aLen && n >= 0 && A[n] == 1 && !check[n] ) { check[n] = true; q.add(new Pair(n, current.y + 1)); } } } return -1; } public static void main(String[] args) { int[] A = {0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0}; System.out.println(solution(A)); // 3 System.out.println(solution2(A)); // 3 } } class Pair { int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } } ================================================ FILE: codility_training/lessons.lesson13.FibonacciNumbers.Ladder/JeongShin.js ================================================ function solution(A, B) { const [max_a, max_b] = [Math.max(...A), Math.max(...B)] const fibonacci = n => { const fib = [0, 1]; for (let i = 2; i < n + 2; i++) fib[i] = (fib[i - 1] + fib[i - 2]) & ((1 << max_b) - 1) return fib } const fib = fibonacci(max_a); return A.map((el, idx) => fib[el + 1] & ((1 << B[idx]) - 1)) } ================================================ FILE: codility_training/lessons.lesson13.FibonacciNumbers.Ladder/README.md ================================================ ## 출처 https://app.codility.com/programmers/lessons/13-fibonacci_numbers/ladder/ ## 원문 You have to climb up a ladder. The ladder has exactly N rungs, numbered from 1 to N. With each step, you can ascend by one or two rungs. More precisely: with your first step you can stand on rung 1 or 2, if you are on rung K, you can move to rungs K + 1 or K + 2, finally you have to stand on rung N. Your task is to count the number of different ways of climbing to the top of the ladder. For example, given N = 4, you have five different ways of climbing, ascending by: 1, 1, 1 and 1 rung, 1, 1 and 2 rungs, 1, 2 and 1 rung, 2, 1 and 1 rungs, and 2 and 2 rungs. Given N = 5, you have eight different ways of climbing, ascending by: 1, 1, 1, 1 and 1 rung, 1, 1, 1 and 2 rungs, 1, 1, 2 and 1 rung, 1, 2, 1 and 1 rung, 1, 2 and 2 rungs, 2, 1, 1 and 1 rungs, 2, 1 and 2 rungs, and 2, 2 and 1 rung. The number of different ways can be very large, so it is sufficient to return the result modulo 2P, for a given integer P. Write a function: class Solution { public int[] solution(int[] A, int[] B); } that, given two non-empty arrays A and B of L integers, returns an array consisting of L integers specifying the consecutive answers; position I should contain the number of different ways of climbing the ladder with A[I] rungs modulo 2B[I]. For example, given L = 5 and: A[0] = 4 B[0] = 3 A[1] = 4 B[1] = 2 A[2] = 5 B[2] = 4 A[3] = 5 B[3] = 3 A[4] = 1 B[4] = 1 the function should return the sequence [5, 1, 8, 0, 1], as explained above. Write an efficient algorithm for the following assumptions: L is an integer within the range [1..50,000]; each element of array A is an integer within the range [1..L]; each element of array B is an integer within the range [1..30]. ================================================ FILE: codility_training/lessons.lesson13.FibonacciNumbers.Ladder/sAp00n.py ================================================ def solution(A, B): # write your code in Python 3.6 N = max(A) + 1 fibo_list = getFibo(N) return [ fibo_list[A[idx]] % 2 ** B[idx] for idx in range(len(A)) ] def getFibo(N): fibo_list = [1, 1] for i in range(2, N): fibo_list.append(fibo_list[i - 1] + fibo_list[i - 2]) return fibo_list A = [4, 4, 5, 5, 1] B = [3, 2, 4, 3, 1] print(solution(A,B)) ================================================ FILE: codility_training/lessons.lesson13.FibonacciNumbers.Ladder/sjjyy.java ================================================ package lessons.lesson13.FibonacciNumbers.Ladder; import java.util.Arrays; public class sjjyy { public static int [] solution(int [] A, int [] B) { int len = A.length; double max1 = Math.pow(2, 30); // int max = (int) max1; int max = Integer.parseInt(String.valueOf(Math.round(max1))); int [] P = new int[len+2]; P[1] = 1; P[2] = 2; for (int i = 3 ; i < len+1 ; i++) P[i] = (P[i-1] + P[i-2]) % max; int [] c = new int[len]; for(int i = 0 ; i < len ; i++) { // div 2^B[i] c[i] = P[A[i]] % (int) Math.pow(2, B[i]); } return c; } public static void main(String [] args) { int [] A = {4, 4, 5, 5, 1}; int [] B = {3, 2, 4, 3, 1}; System.out.println(Arrays.toString(solution(A, B))); // [5, 1, 8, 0, 1] } } ================================================ FILE: codility_training/lessons.lesson14.BinarySearchAlgorithm.MinMaxDivision/JeongShin.js ================================================ function solution(K, M, A) { const dividable = (sum) => { let max = 0; const k = A.reduce(([k, acc], curr) => { if (acc + curr > sum) { k++; acc = 0; } max = Math.max(acc + curr, max); return [k, acc + curr]; }, [0, 0])[0] return [k + 1, max]; }; let minSum = Math.max(...A) let maxSum = A.reduce((acc, curr) => acc + curr); let min = Infinity; while (minSum <= maxSum) { const minMaxSum = ~~((minSum + maxSum) / 2); const [k, possibleMin] = dividable(minMaxSum); if (k <= K) { min = Math.min(min, possibleMin); maxSum = minMaxSum - 1; } else minSum = minMaxSum + 1; } return min; } ================================================ FILE: codility_training/lessons.lesson14.BinarySearchAlgorithm.MinMaxDivision/sAp00n.py ================================================ def blockSizeIsValid(A, max_block_cnt, max_block_size): block_sum = 0 block_cnt = 0 for element in A: if block_sum + element > max_block_size: block_sum = element block_cnt += 1 else: block_sum += element if block_cnt >= max_block_cnt: return False return True def binarySearch(A, max_block_cnt, using_M_will_give_you_wrong_results): lower_bound = max(A) upper_bound = sum(A) if max_block_cnt == 1: return upper_bound if max_block_cnt >= len(A): return lower_bound while lower_bound <= upper_bound: candidate_mid = (lower_bound + upper_bound) // 2 if blockSizeIsValid(A, max_block_cnt, candidate_mid): upper_bound = candidate_mid - 1 else: lower_bound = candidate_mid + 1 return lower_bound def solution(K, M, A): return binarySearch(A, K, M) #A = [2, 1, 5, 1, 2, 2, 2] A = [1,1] #print(solution(3, 5, A)) print(solution(1,1,[0])) ================================================ FILE: codility_training/lessons.lesson14.BinarySearchAlgorithm.MinMaxDivision/sAp00n_pseudo.md ================================================ > 원문 You are given integers K, M and a non-empty array A consisting of N integers. Every element of the array is not greater than M. You should divide this array into K blocks of consecutive elements. The size of the block is any integer between 0 and N. Every element of the array should belong to some block. The sum of the block from X to Y equals A[X] + A[X + 1] + ... + A[Y]. The sum of empty block equals 0. The *large sum* is the maximal sum of any block. For example, you are given integers K = 3, M = 5 and array A such that: ``` A[0] = 2 A[1] = 1 A[2] = 5 A[3] = 1 A[4] = 2 A[5] = 2 A[6] = 2 ``` The array can be divided, for example, into the following blocks: > - [2, 1, 5, 1, 2, 2, 2], [], [] with a large sum of 15; > - [2], [1, 5, 1, 2], [2, 2] with a large sum of 9; > - [2, 1, 5], [], [1, 2, 2, 2] with a large sum of 8; > - [2, 1], [5, 1], [2, 2, 2] with a large sum of 6. The goal is to minimize the large sum. In the above example, 6 is the minimal large sum. Write a function: > ``` > def solution(K, M, A) > ``` that, given integers K, M and a non-empty array A consisting of N integers, returns the minimal large sum. For example, given K = 3, M = 5 and array A such that: ``` A[0] = 2 A[1] = 1 A[2] = 5 A[3] = 1 A[4] = 2 A[5] = 2 A[6] = 2 ``` the function should return 6, as explained above. Write an ***\*efficient\**** algorithm for the following assumptions: > - N and K are integers within the range [1..100,000]; > - M is an integer within the range [0..10,000]; > - each element of array A is an integer within the range [0..M]. > 번역 정수 K, M 및 N 정수로 구성된 비어 있지 않은 배열 A가 제공됩니다. 배열의 모든 요소는 M보다 크지 않습니다. 이 배열을 연속 된 요소의 K 블록으로 나누어야합니다. 블록의 크기는 0과 N 사이의 정수입니다. 배열의 모든 요소는 일부 블록에 속해야합니다. X에서 Y까지의 블록의 합은 A [X] + A [X + 1] + ... + A [Y]와 같습니다. 빈 블록의 합은 0과 같습니다. 큰 합은 모든 블록의 최대 합입니다. 예를 들어 정수 K = 3, M = 5 및 배열 A가 다음과 같이 주어집니다. ``` A [0] = 2 A [1] = 1 A [2] = 5 A [3] = 1 A [4] = 2 A [5] = 2 A [6] = 2 ``` 예를 들어 배열을 다음 블록으로 나눌 수 있습니다. >- [2, 1, 5, 1, 2, 2, 2], [], []의 합이 15이고; >- 큰 합이 9 인 [2], [1, 5, 1, 2], [2, 2]; >- [2, 1, 5], [], [1, 2, 2, 2]의 합이 8이고; >- [2, 1], [5, 1], [2, 2, 2]의 합이 6입니다. >- 목표는 큰 금액을 최소화하는 것입니다. 위의 예에서 6은 최소 큰 합입니다. 함수를 작성하십시오. >- 데프 솔루션 (K, M, A) 즉, 정수 K, M 및 N 정수로 구성된 비어 있지 않은 배열 A가 주어지면 최소 큰 합을 반환합니다. 예를 들어, K = 3, M = 5 및 배열 A는 다음과 같습니다. ``` A [0] = 2 A [1] = 1 A [2] = 5 A [3] = 1 A [4] = 2 A [5] = 2 A [6] = 2 ``` 위에서 설명한 것처럼 함수는 6을 반환해야합니다. 다음 가정을위한 ***효율적인*** 알고리즘을 작성하십시오. >- N 및 K는 [1..100,000] 범위 내의 정수이며; >- M은 [0..10,000] 범위 내의 정수이며; >- 배열 A의 각 요소는 [0..M] 범위 내의 정수입니다. > Pseudo code * 목표 >-min_Max_division 구하기 * 이진탐색 이용 * 1. 예상값(low, middle, high)지정 2. 다중loop 돌려 예상값이 최적해에 부합하는지 검사. 2-1. 맞다면 값 리턴 2-2. 아니면 예상값을 이진탐색으로 범위 수정. ================================================ FILE: codility_training/lessons.lesson14.BinarySearchAlgorithm.NailingPlanks/JeongShin.js ================================================ /* * 방법이 도무지 떠오르지 않아 나중에 다시 시도 해보겠습니다. * */ function solution(A, B, C) { } solution([1, 4, 5, 8], [5, 6, 9, 10], [4, 6, 7, 10, 2]); ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.AbsDistinct/JeongShin.js ================================================ function solution(A) { return new Set(A.map(v => Math.abs(v))).size; } solution([-5, -3, -1, 0, 3, 6]); ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.AbsDistinct/README.md ================================================ ## 출처 http://app.codility.com/programmers/lessons/15-caterpillar_method/abs_distinct/ ## 원문 A non-empty array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array. For example, consider array A such that: A[0] = -5 A[1] = -3 A[2] = -1 A[3] = 0 A[4] = 3 A[5] = 6 The absolute distinct count of this array is 5, because there are 5 distinct absolute values among the elements of this array, namely 0, 1, 3, 5 and 6. Write a function: class Solution { public int solution(int[] A); } that, given a non-empty array A consisting of N numbers, returns absolute distinct count of array A. For example, given array A such that: A[0] = -5 A[1] = -3 A[2] = -1 A[3] = 0 A[4] = 3 A[5] = 6 the function should return 5, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]; array A is sorted in non-decreasing order. ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.AbsDistinct/sAp00n.py ================================================ def solution(A): distnct_num = 0 ele_dict = {} for ele in A: abs_ele = abs(ele) ele_dict[abs_ele] = ele_dict.get(abs_ele,True) return len(ele_dict) A = [-5, -3, -1, 0, 3, 6] print(solution(A)) ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.AbsDistinct/sjjyy.java ================================================ package lessons.lesson15.CaterpillarMethod.AbsDistinct; import java.util.Arrays; import java.util.HashSet; public class sjjyy { public static int solution(int[] A) { /* HashSet set = new HashSet<>(); for(int n : A) { int abs = Math.abs(n); set.add(abs); } return set.size(); */ return (int) Arrays.stream(A).map(Math::abs).distinct().count(); } public static void main(String[] args) { int[] A = {-5, -3, -1, 0, 3, 6}; System.out.println(solution(A)); // 5 } } ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.CountDistinctSlices/JeongShin.js ================================================ function solution(M, A) { const len = A.length let sum = 0, front = 0, back = 0 const appeared = [] while (front < len && back < len) { while (front < len && appeared[A[front]] === undefined) { sum += (front - back + 1) appeared[A[front]] = true front += 1 } while (A[back] !== A[front]) { appeared[A[back]] = undefined back += 1 } appeared[A[back]] = undefined back += 1 } return Math.min(sum, 1000000000) } console.log(solution(6, [3, 4, 5, 5, 2])) ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.CountDistinctSlices/sAp00n.py ================================================ def solution(M, A): appearance = [False] * (M + 1) N = len(A) front = 0 slices = 0 for back in range(N): while front < N and appearance[A[front]] == 0: appearance[A[front]] += 1 slices += front - back +1 front += 1 appearance[A[back]] -= 1 if slices >= 1000000000: return 1000000000 return slices M = 6 # A = [0] A = [3, 4, 5, 5, 2] #A = [1, 0, 1, 1, 0, 0] print(solution(M, A)) ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.CountDistinctSlices/sjjyy.java ================================================ package lessons.lesson15.CaterpillarMethod.CountDistinctSlices; public class sjjyy { public static int solution(int M, int[] A) { int len = A.length; boolean [] appearence = new boolean[M+1]; int front = 0; int back = 0; int result = 0; while(back < len) { while (front < len && !appearence[A[front]]) { appearence[A[front]] = true; result += (front - back + 1); front += 1; if (result >= 1000000000) return 1000000000; } appearence[A[back]] = false; back += 1; } return result; } public static void main(String[] args) { int M = 6; int[] A = {3, 4, 5, 5, 2}; System.out.println(solution(M, A)); // 9 } } ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.CountTriangles/JeongShin.js ================================================ function solution(A) { const len = A.length; let result = 0; A.sort((a, b) => a - b); for (let x = 0; x < len; x++) { let z = x + 2; for (let y = x + 1; y < len; y++) { while (z < len && (A[x] + A[y]) > A[z]) { z += 1 } result += (z - y - 1) } } return result; } solution([10, 2, 5, 1, 8, 12]) ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.CountTriangles/sjjyy.java ================================================ package lessons.lesson15.CaterpillarMethod.CountTriangles; import java.util.Arrays; public class sjjyy { public static int solution(int[] A) { int len = A.length; Arrays.sort(A); int result = 0; for(int i = 0 ; i < len - 2 ; i++) { int left = i+1; int right = i+2; while (left A[right]) right++; else { result += right - left - 1; left++; } } } return result; } public static void main(String[] args) { int[] A = {10, 2, 5, 1, 8, 12}; System.out.println(solution(A)); // 4 } } ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.MinAbsSumOfTwo/JeongShin.js ================================================ function solution(A) { const len = A.length; const abs = (x, y) => Math.abs(x + y); if (len < 2) return abs(A[0], A[0]); A.sort((a, b) => b - a); let min = Infinity; let x = 0, y = len - 1; while (x <= y) { const curr = abs(A[y], A[x]); const next = abs(A[y - 1], A[x]); [x, y] = curr < next ? [x + 1, y] : [x, y - 1]; min = Math.min(min, curr); } return min; } solution([-1, -4, -3, -5]); ================================================ FILE: codility_training/lessons.lesson15.CaterpillarMethod.MinAbsSumOfTwo/sjjyy.java ================================================ package lessons.lesson15.CaterpillarMethod.MinAbsSumOfTwo; import java.util.Arrays; public class sjjyy { public static int solution(int[] A) { int len = A.length; Arrays.sort(A); int start = 0; int end = len - 1; int minAbsSum = Math.abs(A[start]+A[end]); while(start <= end) { int sum = A[start] + A[end]; minAbsSum = Math.min(minAbsSum, Math.abs(sum)); if(sum <= 0) start++; else end--; } return minAbsSum; } public static void main(String[] args) { int[] A = {-8, 4, 5, -10, 3}; int[] B = {1, 4, -3}; System.out.println(solution(A)); // 3 System.out.println(solution(B)); // 1 } } ================================================ FILE: codility_training/lessons.lesson16.GreedyAlgorithms.MaxNonOverLappingSegments/JeongShin.js ================================================ function solution(A, B) { const len = A.length; if (len < 2) return len; let count = 1; let end = B[0]; for (let idx = 1; idx < len; idx++) { while (idx < len && A[idx] <= end) { idx++; } if (idx === len) break; count++; end = B[idx] } return count; } solution([1, 3, 7, 9, 9], [5, 6, 8, 9, 10]); ================================================ FILE: codility_training/lessons.lesson16.GreedyAlgorithms.MaxNonOverLappingSegments/sjjyy.java ================================================ package lessons.lesson16.GreedyAlgorithms.MaxNonOverLappingSegments; public class sjjyy { public static int solution(int[] A, int[] B) { int len = A.length; if(len <= 1) return len; int count = 1; int end = B[0]; // runtime error // if(len <= 1) // return len; for(int i = 1 ; i < len ; i++) { if(A[i] > end) // 첫 끝점 < 다음 시작점 { count++; end = B[i]; } } return count; } public static void main(String[] args) { int[] A = {1, 3, 7, 9, 9}; int[] B = {5, 6, 8, 9, 10}; System.out.println(solution(A, B)); // 3 } } ================================================ FILE: codility_training/lessons.lesson16.GreedyAlgorithms.TieRopes/JeongShin.js ================================================ function solution(K, A) { return A.reduce(([count, acc], curr) => acc + curr >= K ? [count + 1, 0] : [count, acc + curr], [0, 0])[0] } solution(4, [1, 2, 3, 4, 1, 1, 3]) ================================================ FILE: codility_training/lessons.lesson16.GreedyAlgorithms.TieRopes/sjjyy.java ================================================ package lessons.lesson16.GreedyAlgorithms.TieRopes; public class sjjyy { public static int solution(int K, int[] A) { int len = 0; int result = 0; for(int rope : A) { len += rope; if (len >= K) { result++; len = 0; } } return result; } public static void main(String[] args) { int K = 4; int[] A = {1, 2, 3, 4, 1, 1, 3}; System.out.println(solution(K, A)); } } ================================================ FILE: codility_training/lessons.lesson17.DynamicProgramming.MinAbsSum/JeongShin.js ================================================ /* 90점으로 Correctness Test Case 1 개에 있어서 통과를 못하겠어서 일단 넘어가고 다른 문제 먼저 풀겠습니다. */ function solution(A) { const len = A.length; if (len < 2) return Math.abs(A[len - 1] || 0); const absA = A.map(el => Math.abs(el)); let sum = absA.reduce((acc, curr) => acc + curr); absA.sort((a, b) => b - a); absA.forEach((val) => { const nextsum = sum - val * 2; if (nextsum >= 0 && nextsum < sum) { sum = nextsum } }); return sum; } // function solution(A) { // const len = A.length; // A.sort((a, b) => Math.abs(b) - Math.abs(a)) // if (len < 2) // return Math.abs(A[len - 1] || 0); // let parent = new Set().add(0); // A.forEach((x, idx) => { // const child = new Set(); // for (const y of parent) { // const left = len - idx; // if (y < left * Math.abs(x)) // child.add(Math.abs(x + y)); // child.add(Math.abs(x - y)) // } // console.log(child) // parent = child; // }); // return Math.min(...parent) // } /* Second Solution */ // function solution(A) { // const cache = {}; // const len = A.length; // let min = Infinity; // A.sort((a, b) => Math.abs(b) - Math.abs(a)) // const dp = (val, idx) => { // if (cache[[val, idx]] === true) { // return 0; // } else if (idx === len) { // min = Math.min(min, Math.abs(val)); // return 0; // } else if (val > Math.abs(A[idx]) * (len - idx)) { // return 0; // } // cache[[val, idx]] = true; // dp(val - A[idx], idx + 1); // dp(val + A[idx], idx + 1); // return 0; // }; // dp(0, 0); // return min; // } ================================================ FILE: codility_training/lessons.lesson17.DynamicProgramming.NumberSolitaire/JeongShin.js ================================================ function solution(A) { const len = A.length; const score = new Array(len).fill(-Infinity); score[0] = A[0]; for (let curr = 0; curr < len; curr++) { for (let k = 1; k < 7; k++) { const next = curr + k; if (next > len) break; const sum = score[curr] + A[next]; score[next] = Math.max(sum, score[next]); } } return score[len -1]; } console.log(solution([1, -2, 0, 9, -1, -2])) ================================================ FILE: codility_training/lessons.lesson17.DynamicProgramming.NumberSolitaire/sjjyy.java ================================================ package lessons.lesson17.DynamicProgramming.NumberSolitaire; import java.util.Arrays; // IntStream 사용해보기 reduce, map public class sjjyy { public static int solution(int[] A) { int len = A.length; int[] d = new int[len]; Arrays.fill(d, Integer.MIN_VALUE); d[0] = A[0]; for(int i = 0 ; i < len ; i++) { for(int j = i + 1 ; j < len && j < i + 7 ; j++) { int max = d[i] + A[j]; d[j] = Math.max(d[j], max); } } return d[len-1]; } public static int sol2(int[] A) { int len = A.length; int[] d = new int[len]; d[0] = A[0]; for(int i = 1 ; i < len ; i++) { int max = Integer.MIN_VALUE; for(int j = 0 ; j < 6 ; j++) { if(i>=j) max = Math.max(d[i-j]+A[i], max); } d[i] = max; } return d[len-1]; } public static void main(String[] args) { int[] A = {1, -2, 0, 9, -1, -2}; System.out.println(solution(A)); // 8 System.out.println(sol2(A)); // 8 } } ================================================ FILE: codility_training/lessons.lesson90.TasksFromIndeedPrime2015Challenge.FloodDepth/JeongShin.js ================================================ function solution(A) { let max = 0, min = Infinity, depth = 0; A.forEach((curr, idx) => { const next = A[idx + 1] || 0; if (curr > max) { min = curr; max = curr; } depth = Math.max(Math.min(next, max) - Math.min(curr, min), depth); }); return depth; } solution([1, 3, 2, 1, 2, 1, 5, 3, 3, 4, 2]); ================================================ FILE: codility_training/lessons.lesson90.TasksFromIndeedPrime2015Challenge.LongestPassword/JeongShin.js ================================================ function solution(S) { const alpha = /[A-Za-z]/g; const digit = /\d/g; const filtered = S.split(" ").filter(str => { // even # of alp const alp = str.match(alpha) !== null ? str.match(alpha).join("").length : 0; // odd # of dig const dig = str.match(digit) !== null ? str.match(digit).join("").length : 0; return !(alp % 2) && dig % 2 && ((alp + dig) === str.length) }); if (!filtered[0]) return -1; return filtered.reduce((max, curr) => Math.max(max, curr.length), 0); } ================================================ FILE: codility_training/lessons.lesson90.TasksFromIndeedPrime2015Challenge.SlalomSkiing/JeongShin.js ================================================ /* 너무 어려워서 커밋 해두고 나중에 다시 풀어보겠습니다. * */ function solution(A) { const getLongestSequence = arr => { const len = arr.length; const temp = new Array(len+1); temp[0] = -1; let result = 0; for (const val of arr) { let lower = 0; let upper = len - 1; while (lower <= upper) { let mid = ~~((upper + lower) / 2) if (val < temp[mid]) upper = mid - 1; else lower = mid + 1; } if (temp[lower]===undefined) { temp[lower] = val; result++; } else temp[lower] = Math.min(temp[lower], val); } return result; } const len = A.length; const map = new Array(len * 3); const max = Math.max(...A); for (let i = 0; i < len; i++) { map[i * 3] = max * 2 + A[i] + 1; map[i * 3 + 1] = max * 2 - A[i] + 1; map[i * 3 + 2] = A[i]; } return getLongestSequence(map); } // const A = [15, 13, 5, 7, 4, 10, 12, 8, 2, 11, 6, 9, 3] // console.log(solution(A)) ================================================ FILE: codility_training/lessons.lesson91.TaksFromIndeedPrime2016Challenge.DwarfsRafting/JeongShin.js ================================================ /* Assumption 에 each seat number can appear no more than once in the strings 이란 조건이 있는데 S, T 를 따로 놓고 봤을때 한번씩 나온다는 뜻이지 (S에서 "1B" 가 나오면 다시 안 나오지만 T에서 "1B"가 나올수 있음을 의미) S, T 에 중복으로 나오는 테스트 케이스가 있는거 같네요. 다른 분들 풀이 하실때 참고하시면 좋을꺼 같아요. * */ function solution(N, S, T) { const getIdx = str => { const number = [...str]; const alphabet = number.pop(); const [n, a] = [parseInt(number.join('')) - 1, alphabet.charCodeAt(0) - 65]; return ~~(n / (N / 2)) * 2 + ~~(a / (N / 2)); }; const raft = new Array(4).fill((N / 2) ** 2); let count = 0; if (S.length) S.split(" ").forEach((str) => { raft[getIdx(str)]--; }); let dwarfOnBoardCount = 0; if (T.length) { const dwarfOnBoard = T.split(" "); dwarfOnBoardCount = dwarfOnBoard.length; for (const str of dwarfOnBoard) { const curr = getIdx(str); const opposite = Math.abs(3 - curr); if ((--raft[curr] > -1) * (--raft[opposite] > -1) === 1) count += 2; else return raft[curr] === -1 && raft[opposite] === -1 ? 0 : -1; } } return (Math.min(raft[0], raft[3]) + Math.min(raft[1], raft[2])) * 2 + count - dwarfOnBoardCount } ================================================ FILE: codility_training/lessons.lesson91.TasksFromIndeedPrime2016Challenge.RectangleBuilderGreaterArea/JeongShin.js ================================================ /* * 커밋 해두고 다시 풀어보겠습니다 ,,, * */ function solution(A, X) { const temp = A.reduce((arr, val) => { arr[val] = (arr[val] || 0) + 1; return arr; }, {}); const temp2 = []; for (const [key, val] of Object.entries(temp)) { if (val >= 2) temp2.push(parseInt(key)); } const bound = ~~Math.sqrt(X); const len = temp2.length; let result = 0; for (let i = 0; i < bound; i++) { const curr = temp2[i]; const target = Math.ceil(X / curr); let start = bound; let end = len - 1; let mid; // target 보다 같거나 큰 가장 작은 수의 index 를 binary search while (start <= end) { mid = ~~((start + end) / 2) if (target === temp2[mid]) break; else if (target < temp2[mid]) end = mid - 1; else start = mid + 1; } result = result + len - mid; } return result; } solution([1, 2, 5, 1, 1, 2, 3, 5, 1, 11], 5); ================================================ FILE: codility_training/lessons.lesson91.TasksFromIndeedPrime2016Challenge.TreeProduct/JeongShin.js ================================================ /* * 이 문제는 과감하게 포기하겠습니다. * 구글링 해봐도 마땅한 solution 도 없고 제가 풀 수 있는 문제는 아니라고 판단 됩니다 😢 * */ function solution(A, B) { class Graph { constructor() { this.adjList = {}; } addVertex(v) { if (!this.adjList[v]) this.adjList[v] = []; } addEdge(from, to) { this.adjList[from].push(to); this.adjList[to].push(from); } dfs(start) { const path = []; const visited = {}; const adjList = this.adjList; (function dfs(v) { if (!v) return null; visited[v] = true; path.push(v); adjList[v].forEach(neighbor => { if (!visited[neighbor]) { return dfs(neighbor); } }) })(start); const len = path.length; // 나누지 않았을때, 둘로 나누었을때, 셋으로 나누었을때 const d2 = Math.floor(len / 2) * Math.ceil(len / 2); const d3 = Math.ceil(len / 3) * (Math.ceil(len / 3) - (len % 3 === 1)) * (Math.ceil(len / 3) - (len % 3 === 1 || len % 3 === 2)); const result = Math.max(len, d2, d3); return result.toString(); } } /* Build posts in Map */ const len = A.length; const Map = new Graph(); for (let i = 0; i <= len; i++) { Map.addVertex(i); } for (let idx = 0; idx < len; idx++) { const [from, to] = [A[idx], B[idx]]; Map.addEdge(from, to); } return Map.dfs('0'); } ================================================ FILE: codility_training/lessons.lesson92.TaskFromIndeedPrime2016CollegeCodersChallenge.SocksLaundering/JeongShin.js ================================================ /* * Solution 1 👉 Correctness 90% * 1.544 sRUNTIME ERROR, tested program terminated with exit code 134 * stderr: * terminate called after throwing an instance of 'std::bad_alloc' * what(): std::bad_alloc * * 모든 노드들 마다 socks 오브젝트가 복사 되어서 만들어지기 때문에 메모리를 너무 많이 할당해서 * 문제가 생기는거라 생각되는데 어떻게 해결해야할지 모르겠네요 ㅠ ㅠ * */ function solution(K, C, D) { class node { constructor(c, k, s) { this.c = c; this.k = k; this.s = s; } } const socks = {}; let clean_socks = 0; for (const val of C) { socks[val] = (socks[val] || 0) + 1; if (socks[val] === 2) { clean_socks++; socks[val] = 0; } } let stack = [new node(0, K, socks)]; const result = []; for (const val of D) { const next = []; while (stack.length) { const curr = stack.pop(); // val 을 포함 하는 경우 const temp = {...curr.s}; const new_pair = temp[val] === 1; temp[val] = (!new_pair) * 1; if (curr.k > 0) next.push(new node(curr.c + new_pair, curr.k - 1, temp)); else result.push(curr.c); // val 을 포함 안하는 경우 next.push(curr); } stack = next; } stack.forEach((val) => { result.push(val.c) }); return clean_socks + (result.length ? Math.max(...result) : 0); } solution(2, [1, 2, 1, 1], [1, 4, 3, 2, 4]); ================================================ FILE: codility_training/lessons.lesson92.TasksFromIndeedPrime2016.CollegeCodersChallenge.DiamondsCount/JeongShin.js ================================================ function solution(X, Y) { } // const getBound = arr => { // return arr.reduce(([min, max], curr) => { // return [Math.min(min, curr), Math.max(max, curr)]; // }, [Infinity, 0]) // }; // const getCoords = arr => { // return arr.reduce((obj, curr) => { // obj[curr] = (obj[curr] || 0) + 1; // return obj; // }, {}) // }; // const [x_min, x_max] = getBound(X); // const [y_min, y_max] = getBound(Y); // const x_coords = getCoords(X); // const y_coords = getCoords(Y); // console.log(x_coords); // console.log(y_coords); solution([1, 1, 2, 2, 2, 3, 3], [3, 4, 1, 3, 5, 3, 4]) ================================================ FILE: codility_training/lessons.lesson99.FutureTraining.ArrayInversionCount/JeongShin.js ================================================ /* * Solution 2 : O (n log n) 👉 Time Complexity of Merge Sort * 🌟 IDEA : number of inversion in merge() * let i = index of left sub - array & j = index of right sub - array * if a[i] > a[j], (mid - i) inversions * * 출처 : https://www.geeksforgeeks.org/counting-inversions/ * * */ function solution(A) { const merge = (arr, left, mid, right) => { let [i, j, k] = [left, mid, left]; let inv_count = 0; const temp = []; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } while (i <= mid - 1) temp[k++] = arr[i++]; while (j <= right) temp[k++] = arr[j++]; for (let i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } const mergeSort = (arr, left, right) => { let mid, inv_count = 0; if (right > left) { mid = ~~((right + left) / 2); inv_count = mergeSort(arr, left, mid); inv_count += mergeSort(arr, mid + 1, right); inv_count += merge(arr, left, mid + 1, right); } return inv_count > 1000000000 ? -1 : inv_count; } return mergeSort(A, 0, A.length - 1); } /* * Solution 2 : O (n ^ 2) 👉 Bad Idea ! * */ // function solution(A) { // const len = A.length; // let count = 0; // for (let i = 0; i < len; i++) { // const curr = A[i]; // for (let j = i + 1; j < len - 1; j++) { // const next = A[j]; // if (i < j && curr > next) // count++; // } // } // return count; // } ================================================ FILE: codility_training/lessons.lesson99.FutureTraining.StrSymmetryPoint/JeongShin.js ================================================ function solution(S) { const len = S.length; if (!len) return -1; const mid = ~~(len / 2); const left = S.slice(0, mid); const right = [...S.slice(mid + 1)].reverse().join(""); if (left === right) return mid; return -1; } ================================================ FILE: codility_training/lessons.lesson99.FutureTraining.TreeHeight/JeongShin.js ================================================ function solution(T) { const depth = tree => { if (!tree) return 0; return Math.max(depth(tree.l), depth(tree.r)) + 1; }; return Math.max(depth(T.l), depth(T.r)) } ================================================ FILE: package.json ================================================ { "name": "Algorithm", "version": "1.0.0", "description": "단국대학교 알고리즘 스터디", "main": "index.js", "repository": "https://github.com/JunilHwang/Algorithm", "author": "황준일 , 박은영 , 김형욱 , 박유림 , 신원규 , 신정웅 , 심지연 , 이노원 , 조우상 ", "license": "MIT", "devDependencies": { "assert": "^2.0.0" } } ================================================ FILE: programmers/socar/1.js ================================================ const timeToHM = (time) => time.split(':').map(v => Number(v)); const parseSchedules = (schedules) => schedules.map(schedule => { const [bread_time, bread_number] = schedule.split(' '); const [bread_hour, bread_min] = timeToHM(bread_time); return [bread_hour, bread_min, bread_number]; }); const getTakesTime = (current_time, last_time) => { const [current_hour, current_min] = current_time; const [last_hour, last_min] = last_time; if (current_hour === last_hour && current_min === last_min) return 0; const current = new Date(2020, 7, 23, ...current_time); const last = new Date(2020, 7, 23, last_hour, last_min); return Math.floor((last.getTime() - current.getTime()) / 60000); }; const getBreakTime = (schedules, K, current_hour, current_min) => { const schedule_length = schedules.length; let breakTime; for (let i = 0 ; i < schedule_length ; i++) { const [bread_hour, bread_min, bread_number] = schedules[i]; if (K < 1) { breakTime = i - 1; break; } if ((bread_hour < current_hour) || (bread_hour === current_hour && bread_min < current_min)) continue; K -= bread_number; } return [breakTime || (schedule_length - 1), K]; }; function solution (bakery_schedule, current_time, K) { current_time = timeToHM(current_time); const [current_hour, current_min] = current_time; const schedules = parseSchedules(bakery_schedule); const [breakTime, remain_break] = getBreakTime(schedules, K, current_hour, current_min); if (remain_break > 0) return -1; const last_time = schedules[breakTime]; return getTakesTime(current_time, last_time); } console.log( solution(['09:05 10', '12:20 5', '13:25 6', '14:24 5'], '12:05', 10) === 80, solution(['12:00 10'], '12:00', 10) === 0, solution(['12:00 10'], '12:00', 11) === -1, ); ================================================ FILE: programmers/난이도별/README.md ================================================ # 출처 https://programmers.co.kr/learn/challenges?tab=all_challenges **모든 문제에서 난이도별로 정리** ================================================ FILE: programmers/난이도별/level.01.두개_뽑아서_더하기/temp.py ================================================ ================================================ FILE: programmers/난이도별/level01.2016년/HyeonJeong.py ================================================ def solution(a, b): total = b day_list = ["THU", "FRI", "SAT", "SUN", "MON", "TUE", "WED"] months_31 = [1, 3, 5, 7, 8, 10, 12] months_30 = [4, 6, 9, 11] months_29 = [2] for i in range (1, a): if i in months_31: total += 31 elif i in months_30: total += 30 elif i in months_29: total += 29 rest = total % 7 answer = day_list [rest] return answer ================================================ FILE: programmers/난이도별/level01.2016년/Jaewon0702.py ================================================ from datetime import * def solution(a, b): weeks = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"] return weeks[datetime(2016, a, b).weekday()] # 100점 print(solution(5, 24) == "TUE") ================================================ FILE: programmers/난이도별/level01.2016년/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12901 ================================================ FILE: programmers/난이도별/level01.2016년/Siyoung-Yang.js ================================================ class Solution { public String solution(int a, int b) { String answer = ""; String weeks [] = {"SUN","MON","TUE","WED","THU","FRI","SAT"}; int month [] = {0,31,29,31,30,31,30,31,31,30,31,30,31}; int sum = 0; for (int i=0;i #include using namespace std; string solution(int a, int b) { const string dow[]={"THU", "FRI", "SAT", "SUN", "MON", "TUE", "WED"}; const int dom[]={31,29,31,30,31,30,31,31,30,31,30,31}; int day=b; for(int i=0;i #include using namespace std; string weeks[7] = { "FRI","SAT","SUN","MON","TUE","WED","THU"}; int month[12] = { 31,29,31,30,31,30,31,31,30,31,30,31 }; string solution(int a, int b) { string answer = ""; int day = 0; for (int k = 0; k <(a-1); k++) { day += month[k]; } day += (b-1); day %= 7; answer = weeks[day]; return answer; } ================================================ FILE: programmers/난이도별/level01.2016년/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12901 2016년 0. a월 b일의 요일 구하기 1. datetime 사용 ''' import datetime def solution(a, b): answer = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"] return answer[datetime.datetime(2016, a, b).weekday()] ''' library 사용이 안되었다면 다음과 같이 푸는게 best인 듯 def getDayName(a,b): months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] days = ['FRI', 'SAT', 'SUN', 'MON', 'TUE', 'WED', 'THU'] return days[(sum(months[:a-1])+b-1)%7] ''' ================================================ FILE: programmers/난이도별/level01.2016년/sjjyy.java ================================================ import java.util.Arrays; public class sjjyy { public static String solution(int a, int b) { int days = 0; String [] Day = {"SUN","MON","TUE","WED","THU","FRI","SAT"}; for(int i = 1 ; i < a ; i++) { if(i == 2) days += 29; // else if(i == 4 || i == 6 || i == 9 || i == 11) else if(Arrays.asList(4,6,9,11).contains(i)) days += 30; else days += 31; } days += 4 + b; return Day[days % 7]; } public static void main(String[] args) { int a = 5; int b = 24; System.out.println(solution(a,b)); // TUE } } ================================================ FILE: programmers/난이도별/level01.3진법_뒤집기/6047198844.py ================================================ def solution(n): answer = 0 three_digit = "" while n > 0: # n은 10개씩 묶인 상태이다. three_digit = str(n % 3) + three_digit n //= 3 for idx, i in enumerate(three_digit): answer += int(i) * pow(3, idx) return answer ================================================ FILE: programmers/난이도별/level01.3진법_뒤집기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/68935 문제 : 3진법 뒤집기 ''' def solution(n): answer = 0 tri = '' # 3진수로 만든 후 앞에 0 제거 while n>0 : tri += str(n%3) n //= 3 tri = str(int(tri)) # 역순으로 변환 후 list로 쪼갬 dec = list(map(int,tri[::-1])) # 10진수로 변환 for i in range(len(dec)) : answer += dec[i] * pow(3,i) return answer ================================================ FILE: programmers/난이도별/level01.3진법_뒤집기/develop-sell.js ================================================ function solution(n) { let answer = 0; var arr = []; var big = 0; let amount = n; while(1){ if(n / Math.pow(3, big) < 3){ break; } big++; } for(let i = big; i > -1; i-- ){ if(amount == 0){ arr.push('0') continue; } if( amount / (Math.pow(3, i)*2) >= 1){ amount -= (Math.pow(3, i)*2); arr.push('2') } else if(amount / Math.pow(3, i) >= 1){ amount -= Math.pow(3, i); arr.push('1') } else{ arr.push('0'); } } arr.reverse(); let size = arr.length - 1; arr.forEach(function (e){ answer += (Math.pow(3, size) * e) size--; }) return answer; } // 문제풀이: // 먼저 무한루프를 돌면서 3의 n제곱으로 나뉘는 값이 1,2인 경우의 n값을 구한다 // 여기서 n값은 big이고, big부터 0까지 계속 값을 나눈다. // 먼저 (3의 n제곱 * 2)으로 나뉘는지 보고 나눠지면 '2'를 arr에 푸시한다 // 그 다음 3의 n제곱으로 나눠지는지 보고 나눠지면 '1'를 arr에 푸시한다 // 마지막으로는 '0'를 푸시한다 // 그 후 array를 reverse해주고 // array의 사이즈 -1 만큼 돌면서 3의 n제곱을 하나씩 줄면서 answer에 값에 더해준다. // 헷갈린 점 / 어려운 점: // 1. for문 감소문 // - for(let i = 10 ; i > 0; i--) => 감소문의 가운데 조건은 부등호가 '>'로 바꿔야하는데, 계속 헤맸다. // 2. 3진법은 0,1,2까지 있다는 점 // - 2까지 있다는 것을 뒤늦게 캐치해서 경우를 추가해줬다! (처음엔 0,1만 있는줄 알았다) // 배운점: // 1. arr는 reverse()라는 함수가 있다! str는 따로 없으니 참고 // 2. forEach문도 array의 한 함수로 취급!! 다음에 짤 때 참고 // 3. Math.pow(n, m) => n의 m제곱 !! // 참고풀이: // (1) // n = n.toString(3).split('').reverse().join('') // return parseInt(n, 3) // toString(n)으로 10진법 => n진법으로 변경 // split('')으로 str 한 문자씩 저장한 배열 리턴 // join('')으로 배열을 str으로 붙여서 리턴 // parseInt(n, 3) n진법 => 10진법으로 변경 // (2) // return parseInt([...n.toString(3)].reverse().join(""), 3); // [...str] => split('')와 같은 기능 구현 ================================================ FILE: programmers/난이도별/level01.3진법_뒤집기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/68935 3진법 뒤집기 [풀이] 1. 10 -> 3 -> reverse -> 10 2. 진법 원리를 이용해 앞뒤반전으로 바로 리스트 생성 ''' def solution(n): answer = '' while n != 0: answer += str(divmod(n, 3)[1]) n //= 3 return int(answer, 3) ================================================ FILE: programmers/난이도별/level01.K번째수/6047198844.py ================================================ def solution(array, commands): answer = [] for command in commands: i, j, k = command answer.append(sorted(array[i-1:j])[k-1]) return answer ================================================ FILE: programmers/난이도별/level01.K번째수/Go-yj.py ================================================ # 링크 : https://programmers.co.kr/learn/courses/30/lessons/42748 # 문제이름 : K번째 수 def solution(array, commands): answer = [] temp_array = [] size = len(commands) for i in range(0,size): for j in range(commands[i][0]-1, commands[i][1]) : temp_array.append(array[j]) temp_array.sort() print(temp_array) answer.append(temp_array[commands[i][2]-1]) temp_array.clear() return answer ================================================ FILE: programmers/난이도별/level01.K번째수/HyeonJeong.py ================================================ # 1. 첫 시도 ''' def solution(array, commands): answer = [] for j in range(len(commands)) : new_array = [] for i in range(commands[j][0] - 1, commands[j][1]) : new_array.append(array [i]) new_array.sort() answer.append(new_array [(commands [j][2] - 1)]) return answer ''' # 2. list[:]이용 ''' def solution(array, commands): answer = [] for j in range(len(commands)) : new_array = array [commands[j][0] - 1 : commands[j][1]] new_array.sort() answer.append(new_array [(commands [j][2] - 1)]) return answer ''' # 3. sorted()이용 ''' def solution(array, commands): answer = [] for j in range(len(commands)) : new_array = sorted(array [commands[j][0] - 1 : commands[j][1]]) answer.append(new_array [(commands [j][2] - 1)]) return answer ''' # 4. 더 짧은 코드 이용 ''' def solution(array, commands): answer = [] for j in range(len(commands)) : answer.append(sorted(array [commands[j][0] - 1 : commands[j][1]])[(commands [j][2] - 1)]) return answer ''' # 5. 준일님의 코드 이용 def solution(array, commands): answer = [] for x, y, z in commands : answer.append(sorted(array [x - 1 : y])[z - 1]) return answer print(solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]])) ================================================ FILE: programmers/난이도별/level01.K번째수/Jaewon0702.py ================================================ def solution(array, commands) return [ sorted(array[v[0]-1 : v[1]])[v[2] - 1] for v in commands ] #return [ sorted(array[x-1 : y])[z - 1] for x, y, z in commands #점수 : 100점 ================================================ FILE: programmers/난이도별/level01.K번째수/README.md ================================================ # 출처 *** https://programmers.co.kr/learn/courses/30/lessons/42748 ================================================ FILE: programmers/난이도별/level01.K번째수/develop-sell.js ================================================ function solution(array, commands) { let answer = []; for(let i =0; i < commands.length; i++){ let sliced_arr = (array.slice(commands[i][0]-1, commands[i][1])); //아래에서 그냥 sliced_arr.sort()를 하게 되면 2번이 안 풀린다. sliced_arr.sort((a, b) => a - b) let num = sliced_arr[commands[i][2]-1]; answer.push(num); } return answer; } // >문제풀이방법 // slice함수를 통해 배열의 일부분을 선택하여 새로운 배열로 만들었다. // 그 후 sort함수로 정렬을 해주고 // 그 안에서 k번째 숫자를 찾아 배열에 push해주면 된다. // >헷갈린점 // 1. 문제에서 2번쨰 ~ 5번째라고 했지만, 실제 배열에선 [1] , [4] 였다. // -> console.log()를 통해 편하게 알 수 있었다! // 2. sort함수 , 뒤에 sortFunction도 넣어줘야한다 // -> 아무것도 안 넣으면 배열 각 요소를 문자열로 변환하고 유니코드값에 따라 정렬한다. // -> 즉, 여기선 숫자를 또 문자열로 변환해서 유니코드값에 따라 정렬하기 때문에 어떤 경우는 문제가 될 수 있었다 // -> 따라서 숫자 배열을 정렬할 때는 반드시 함수 "(a, b) => a - b" 를 넣어준다(오름차순) // 출처: https://fluorite94.tistory.com/220 // 3. array(배열)은 push 함수를 통해 넣는다! "+=" 이건 string의 경우에 사용! // junihwang.js 참고 // return commands.map(([i, j, k]) => array.slice(i-1, j).sort((a, b) => a- b)[k-1]) // 코드 보고 감탄했네요..! // map은 배열에 접근해 각 요소들에게 행한 값들을 따로 배열로 만드는 것이다. // 이 경우 2차원 배열에 접근해 각 [0],[1],[2]를 i,j,k로 명칭하고 // 각각 i,j,k를 용도에 맞게 사용해서 나오는 값들을 따로 배열로 만들어주는, 이 문제에 아주 적합한 용도이다. ================================================ FILE: programmers/난이도별/level01.K번째수/dkdlelk99.py ================================================ def solution(array, commands): answer = [] for i in range(len(commands)): temp = array[commands[i][0] - 1 : commands[i][1] ] temp.sort() # print(temp) answer.append(temp[ commands[i][2] - 1 ]) return answer a = [[3, 3, 1], [3, 5, 2], [2, 7, 4]] b = [2, 3, 5, 4, 6, 1, 7, 9, 8] # 함수 내부의 print문 결과 # [5] # [4, 5, 6] # [1, 3, 4, 5, 6, 7] print(solution(b,a) == [5, 5, 5]) ================================================ FILE: programmers/난이도별/level01.K번째수/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42748?language=javascript function solution(array, commands) { return commands.map(([i, j, k]) => array.slice(i-1, j).sort((a, b) => a- b)[k-1]) } console.log(solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]]),[5, 6, 3]) //console.log(solution([1,1,1,1,3,2,2,2,2], [[]]),[]) ================================================ FILE: programmers/난이도별/level01.K번째수/junilhwang.py ================================================ def solution(array, commands): result = [] for v in commands: i, j, k = v temp = array[i-1:j] temp.sort() result.append(temp[k-1]) return result a = [[2, 5, 3], [4, 4, 1], [1, 7, 3]] b = [1, 5, 2, 6, 3, 7, 4] print(solution(b,a)) ================================================ FILE: programmers/난이도별/level01.K번째수/khw970421.js ================================================ function solution(array, commands) { let sort; let answer=[]; const commands_length= commands.length; for(let i=0;i(A-B)) answer.push(sort[commands[i][2]-1]); } return answer; } ================================================ FILE: programmers/난이도별/level01.K번째수/pul8219.js ================================================ function solution(array, commands) { var answer = []; let slicing = []; commands.forEach(command => { slicing = array.slice(command[0]-1, command[1]); // array의 i ~ j번째까지 잘라 새로운 배열에 저장 slicing.sort((a,b) => a-b); // 정렬 answer.push(slicing[command[2]-1]); slicing = []; // slicing 배열 초기화 }); return answer; ================================================ FILE: programmers/난이도별/level01.K번째수/rockmiin.py ================================================ def solution(array, commands): result=[] for i in range (len(commands)): cut=array[commands[i][0]-1:commands[i][1]] cut=sorted(cut) result.append(cut[commands[i][2]-1]) return result if __name__=="__main__": array=[1,5,2,6,3,7,4] commands=[[2,5,3],[4,4,1],[1,7,3]] solution(array, commands) ================================================ FILE: programmers/난이도별/level01.K번째수/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42748 K번째수 1. 주어진 배열의 i~j 인덱스의 부분 배열을 정렬 후 k번째 값 찾기 2. 문제 그대로 풀이 ''' def solution(array, commands): return [ sorted(array[ a - 1 : b ])[ c - 1 ] for (a, b, c) in commands ] ''' ''' ================================================ FILE: programmers/난이도별/level01.K번째수/sjjyy.java ================================================ package 난이도별.level01.K번째수; import java.util.Arrays; import java.util.stream.IntStream; // commands[[i,j,k],[i,j,k]] public class sjjyy { public static int[] solution(int[] array, int[][] commands) { int len = commands.length; int [] answer = new int[len]; for(int i = 0 ; i < len ; i++) { int [] nowCommands = commands[i]; int [] tmp = new int[nowCommands[1]-(nowCommands[0]-1)]; int tLen = tmp.length; for(int j = 0 ; j < tLen; j++) tmp[j] = array[(nowCommands[0]-1) + j]; // System.arraycopy(array, 0 + (commands[i][0] - 1), tmp, 0, tLen); Arrays.sort(tmp); answer[i] = tmp[nowCommands[2]-1]; } return answer; } public static int[] solution2(int[] array, int[][] commands) // 다른 사람 풀이 { int[] answer = new int[commands.length]; for(int i = 0 ; i < commands.length ; i++) { int [] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]); Arrays.sort(temp); answer[i] = temp[commands[i][2]-1]; } return answer; } public static int[] solution3(int[] array, int[][] commands) { return IntStream.range(0, commands.length).map(i -> { int[] nowCommands = commands[i]; int [] temp = Arrays.copyOfRange(array, nowCommands[0]-1, nowCommands[1]); Arrays.sort(temp); return temp[nowCommands[2]-1]; }).toArray(); } public static void main(String [] args) { int[] arr= {1, 5, 2, 6, 3, 7, 4}; int[][] commands = {{2, 5, 3}, {4, 4, 1}, {1, 7, 3}}; System.out.println(Arrays.toString(solution(arr, commands))); // [5, 6, 3] System.out.println(Arrays.toString(solution2(arr, commands))); // [5, 6, 3] System.out.println(Arrays.toString(solution3(arr, commands))); // [5, 6, 3] } } ================================================ FILE: programmers/난이도별/level01.[1차]_다트_게임/6047198844.py ================================================ import re def solution(dartResult): result = [] numbers = re.findall('[0-9]+',dartResult) commands = re.findall('[SDT][*#]?',dartResult) powers = ' SDT' for number, command in zip(numbers,commands): result.append(pow(int(number),powers.index(command[0]))) #옵션이 존재하는 경우 if len(command) == 2: if command[1] == '#': result[-1] = -result[-1] else: result[-1] = result[-1]*2 if len(result) > 1: result[-2] = result[-2]*2 return sum(result) ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/6047198844.py ================================================ def solution(x, n): return list(range(x,x*n+x,x)) if x != 0 else [0 for _ in range(n)] ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12954 문제 : x만큼 간격이 있는 n개의 숫자 x를 리스트에 넣고 x만큼 더하는 과정을 n번 반복하였습니다. ''' def solution(x, n): answer = [] num = x for i in range(0,n) : answer.append(num) num += x return answer ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/HyeonJeong.py ================================================ #방법1 def solution(x, n): if x == 0 : return [0] * n return [a for a in range(x, x * n + x, x)] #방법2 def solution(x, n): return [x * a for a in range(1, n + 1)] print( solution(2, 5) == [2,4,6,8,10], solution(4, 3) == [4,8,12], solution(-4, 2) == [-4, -8] ) ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12954 ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/develop-sell.js ================================================ function solution(x, n) { let answer = []; for(let i = 0; i< n; i++){ answer.push(x + x * i); } return answer; } // 문제풀이: // 간단한 배열 문제였다. // 한줄 풀이: // return Array(n) // .fill(x) // .map((v, i) => (i + 1) * v) // Array(n) : n 크기의 배열을 만든다 // fill(x) : x값으로 배열을 다 채운다 // => 만약 이미 다른 값이 들어있어도 x값으로 배열을 다 채워버린다. // map((v, i)) : 여기서 v는 값, i는 인덱스이고, "인덱스 + 1" 만큼 값으로 곱해주면 된다. ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/dkdlelk99.py ================================================ def solution(x, n): return [i*x for i in range(1, n+1)] print(solution(2,5) == [2, 4, 6, 8, 10]) print(solution(4,3) == [4, 8, 12]) print(solution(-4,2) == [-4, -8]) ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/khw970421.js ================================================ function solution(x, n) { const answer = []; for(let i=1;i<=n;i++) answer.push(x*i) return answer; } ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12954 x만큼 간격이 있는 n개의 숫자 0. x의 배수를 n개만큼 출력 ''' def solution(x, n): return [i*x for i in range(1, n+1)] ''' ''' ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/sjjyy.java ================================================ package 난이도별.level01.x만큼_간격이_있는_n개의_숫자; import java.util.Arrays; import java.util.stream.LongStream; public class sjjyy { public static long[] solution(int x, int n) { /* long tmp = x; long[] answer = new long[n]; for(int i = 0 ; i < n ; i++) answer[i] = tmp * (i + 1); return answer; */ return LongStream.rangeClosed(1, n).map(i -> x * i).toArray(); } public static void main(String [] args) { System.out.println(Arrays.toString(solution(2, 5))); // [2, 4, 6, 8, 10] System.out.println(Arrays.toString(solution(4, 3))); // [4, 8, 12] System.out.println(Arrays.toString(solution(-4, 2))); // [-4, -8] } } ================================================ FILE: programmers/난이도별/level01.x만큼_간격이_있는_n개의_숫자/x만큼_간격_있는_n개의_숫자.py ================================================ def solution(x, n): return [v * x for v in range(1, n + 1)] print(solution(2, 5) == [2, 4, 6, 8, 10]) print(solution(-4, 2) == [-4, -8]) ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/6047198844.py ================================================ def solution(s): N = len(s) return s[N//2-1:(N+2)//2] if N % 2 == 0 else s[N//2] ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12903 문제 : 가운데 글자 가져오기 ''' def solution(s): n = len(s)//2 return s[n-1:n+1] if len(s)%2==0 else s[n] ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/Jaewon0702.py ================================================ def solution(s): if len(s) % 2 == 0: return s[int(len(s) / 2 - 1) : int(len(s) / 2 + 1)] else: return s[int((len(s) - 1) / 2)] # 100점 print(solution("abcde") == "c") print(solution("qwer") == "we") ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/README.md ================================================

#출처

https://programmers.co.kr/learn/courses/30/lessons/12903 ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/develop-sell.js ================================================ function solution(s) { let answer = ''; let isOdd = true; if (s.length % 2 == 0) isOdd = false; if (isOdd == true){ //홀수 for(let i = 0; i < s.length; i++){ //아래 콘솔 2개는 소수점으로 자동 형변환하는 걸 확인하기 위함 console.log(s.length / 2) console.log(i) if(i == s.length / 2 - 0.5){ return s.charAt(i) } } } else{ //짝수 for(let i = 0; i < s.length; i++){ if(i === s.length / 2){ return s.charAt(i-1) + s.charAt(i); } } } return answer; } // 원리: // - 홀수, 짝수 분기 처리해서 진행했습니다. // - isOdd가 true면 홀수, 아니면 짝수입니다 // - 홀수의 경우 가운데 1자만 빼고, 짝수는 2자를 빼게 됩니다. // 헷갈린점: // 1. // - 네이밍에서 isOdd로 했는데, 말 그래도 Odd(홀수)인지를 묻는 걸로 네이밍했으면 그렇게 믿어야함 // - 즉, isOdd가 true면 홀수이고, 아니면 짝수인건데 반대로 생각하고 있었다 // 2. // - 홀수에서 s.length와 i가 같을 때 return s.charAt(i) 가운데 한 글자만 빼려고 했는데 // - s.length / 2 가 처음에 몫만 나오는 줄 알았는데, js는 저절로 형변환을 해서 소수점이 나오게 된다 // - ex. 5 -> 2.5가 나옴!! (c언어는 안 그랬던거 같은데... 아닌가? ) // - 자동 형변환 잘 확인할 것 ! // 다른 사람 코드 참고 (eyabc.js) // const middle = s.length / 2; // const floor = ~~middle; // return (Number.isInteger(middle) ? s[floor - 1] : '') + s[floor]; // 정확히 반 나눈 middle(소수점 포함 값)이 int가 아니면 홀수니까 s[floor]만 // 짝수면 s[floor - 1] + s[floor] 로 return 한다 //double tilde( ~~ ) 연산자 : Math.floor() 연산자와 비슷하다 => "내림" 같은 표현 (소수점 없애는) // 양수에선 결과가 같으나 음수에선 결과가 다르다 // var num1 = 1234.5678; // var num2 = -5.9; // console.log(Math.floor(num1)); // console.log(~~num1); // console.log('---'); // console.log(Math.floor(num2)); // console.log(~~num2); // > 1234 // > 1234 // > --- // > -6 // > -5 // 참고자료 : https://dreamyoungs.github.io/js/tilde-and-double-tilde-operator // 느낀점: // 애초에 for문 돌릴 필요가 없었고, s.length의 가운데 값의 해당되는 문자를 빼면 되었다. ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12903 * @param s 길이가 1 이상, 100이하인 스트링 * @return s 의 가운데 글자를 반환하는 함수, 짝수라면 가운데 두 글자를 반환 */ function solution(s) { const middle = s.length / 2; const floor = ~~middle; return (Number.isInteger(middle) ? s[floor - 1] : '') + s[floor]; } console.log(solution('abcde') === 'c'); console.log(solution('qwer') === 'we'); // 옛날에 푼 것 function solution2(s) { let a = Math.floor(s.length / 2); if (s.length % 2 === 1) { return s.slice(a, a + 1); } else { return s.slice(a - 1, a + 1); } // '홀' : '짝' } ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/rockmiin.py ================================================ def solution(s): if(len(s)%2==0): return s[len(s)//2-1:len(s)//2+1] else: return s[len(s)//2] ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/s2uyeoii.cpp ================================================ #include #include using namespace std; string solution(string s) { string answer = ""; int len = s.length(); if (len % 2 == 1) { answer = s[len / 2]; } else { answer += s[len / 2 - 1]; answer += s[len / 2]; } return answer; } ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12903 가운데 글자 출력 0. 길이가 짝수면 2개의 char 출력 ''' def solution(s): size = len(s) return (s[size//2-1] if size % 2 == 0 else "") + s[size//2] ''' ''' ================================================ FILE: programmers/난이도별/level01.가운데_글자_가져오기/sjjyy.java ================================================ package 난이도별.level01.가운데_글자_가져오기; public class sjjyy { public static String solution(String s) { int len = s.length(); // if (len % 2 == 0) // return s.substring(len/2 - 1 , len/2 + 1); // else // return s.substring(len/2, len/2 + 1); // return len % 2 == 0 ? s.substring(len/2 -1 , len/2 + 1) : s.substring(len/2, len/2 +1); return s.substring(len/2 - (len % 2 == 0 ? 1 : 0), len/2 + 1); } public static void main(String[] args){ System.out.println(solution("abcde")); // c System.out.println(solution("qwer")); // we } } ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/6047198844.py ================================================ def solution(arr): answer = [arr[0]] for i in arr: if answer[-1] != i: answer.append(i) return answer ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12906 문제 : 같은 숫자는 싫어 빈 값일 때 arr[-1]을 하면 런타임 에러가 발생해서 if elif로 비었을 때를 미리 처리해주었는데 arr[-1:]을 사용하면 빈 값이어도 죽지 않는다네요 (✪ ω ✪) [메모] if answer[-1:] != arr[-1] : answer.append(arr[-1]) ''' def solution(arr): answer = [arr[i] for i in range(len(arr)-1) if arr[i] != arr[i+1]] if not answer : answer.append(arr[-1]) elif answer[-1] != arr[-1] : answer.append(arr[-1]) return answer ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/HyeonJeong.py ================================================ def solution(arr): answer = [arr[0]] for i in arr: if i != answer[-1]: answer.append(i) return answer print( solution([1,1,3,3,0,1,1]) == [1,3,0,1], solution([4,4,4,3,3]) == [4,3] ) ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/Jaewon0702.py ================================================ def solution(arr): removed = [arr[0]] for i in range(1, len(arr)): if arr[i] != arr[i - 1]: removed.append(arr[i]) return removed # 100점 print(solution([1, 1, 3, 3, 0, 1, 1])==[1,3,0,1]) print(solution([4, 4, 4, 3, 3])==[4,3]) ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/README.md ================================================ # 출처 *** https://programmers.co.kr/learn/courses/30/lessons/12906 ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/Siyoung-Yang.java ================================================ package programmers.난이도별.level01.같은_숫자는_싫어; import java.util.*; class SiyoungYang { public int[] solution(int []arr) { List list = new ArrayList(); if(arr.length > 0) list.add(arr[0]); for(int i=1; i num !== arr[i + 1]); } ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/dkdlelk00.py ================================================ def solution(a): answer = [] answer.append(a[0]) for i in range(1,len(a)): if a[i] != a[i-1]: answer.append(a[i]) return answer a = [1,1,3,3,0,1,1] print(solution(a) == [1,3,0,1]) b = [1,5,2,2,2,4,4,5,5,5,0,9,9] print(solution(b) == [1,5,2,4,5,0,9]) ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12906 * @param arr : 배열 arr의 크기 : 1,000,000 이하의 자연수 : 배열 arr의 원소의 크기 : 0~ 9 정수 * @return rr 에서 연속적으로 나타나는 숫자는 하나만 남기고 전부 제거하고 남은 수들을 return */ function solution(arr) { return arr.filter((num, i) => num !== arr[i + 1]); } console.log(solution([1, 1, 3, 3, 0, 1, 1])); // [1,3,0,1] console.log(solution([4, 4, 4, 3, 3])); //[4,3] // 옛날에 푼것 function solution2(arr) { return arr.filter((i, k) => { return i !== arr[k + 1]; }); } ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/rockmiin.py ================================================ def solution(arr): answer=[] answer.append(arr[0]) for i in range(1, len(arr)): if(arr[i]!=arr[i-1]): answer.append(arr[i]) # print(answer) return answer print( solution([1, 1, 3, 3, 0, 1, 1]), solution([1, 1, 3, 3, 0, 1, 1])==[1, 3, 0, 1], solution([4, 4, 4, 3, 3]), solution([4, 4, 4, 3, 3])==[4, 3] ) ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12906 같은 숫자는 싫어 [풀이] 1. 앞자리 수와 비교해서 제거해감 ''' def solution(arr): answer = [] temp = arr[0] for i in arr[1:]: if temp != i: answer.append(temp) temp = i answer.append(temp) return answer ''' 배울점이 있는 코드 다른사람 코드 def no_continuous(s): a = [] for i in s: if a[-1:] == [i]: continue a.append(i) return a ''' ================================================ FILE: programmers/난이도별/level01.같은_숫자는_싫어/sjjyy.java ================================================ package 난이도별.level01.같은_숫자는_싫어; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class sjjyy { public static int [] solution(int[] array) { List arrayList = new ArrayList<>(); int len = array.length - 1; for(int i = 0 ; i < len ; i++) { if(array[i] != array[i+1]) arrayList.add(array[i]); } arrayList.add(array[len]); // 마지막 인덱스 값 int aLen = arrayList.size(); int[] ans = new int[aLen]; for(int i = 0 ; i < aLen ; i++) ans[i] = arrayList.get(i); return ans; } public static int [] solution2(int[] array) { List arrayList = new ArrayList<>(); int len = array.length - 1; for(int i = 0 ; i < len ; i++) { if(array[i] != array[i+1]) arrayList.add(array[i]); } arrayList.add(array[len]); // 마지막 인덱스 값 return arrayList.stream().mapToInt(Integer::intValue).toArray(); } public static void main(String [] args) { int[] arr = {1, 1, 3, 3, 0, 1, 1}; System.out.println(Arrays.toString(solution(arr))); // [1, 3, 0, 1] System.out.println(Arrays.toString(solution2(arr))); // [1, 3, 0, 1] } } ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/6047198844.py ================================================ def solution(arr, divisor): answer = sorted([number for number in arr if number % divisor == 0]) return answer if answer else [-1] ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12910 문제 : 나누어 떨어지는 숫자 배열 나머지 확인하고 추가하는 과정을 그냥 정석대로 나타냄 다른 사람 코드 보니 for문과 if 문을 한 줄로 써버리던데 한 줄로 쓰는 것은 의식하고 연습하지 않으면 놓치기 쉽고 익숙해지지 않는 것 같다 앞으로 코드 써보고 간단하게 줄여보는 연습도 함께 꼭 해봐야겠다 [메모] sorted([i for i in arr if i%divisor==0]) ''' def solution(arr, divisor): answer = [] for i in arr : if i%divisor==0 : answer.append(i) if not answer : answer.append(-1) return sorted(answer) ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/HyeonJeong.py ================================================ # 1차 def solution(arr, divisor): answer = [] for a in arr: if a % divisor == 0: answer += [a] if answer == []: answer += [-1] answer.sort(reverse = False) return answer # 2차 def solution(arr, divisor): answer = [] for a in arr: if a % divisor == 0: answer += [a] return sorted(answer) if answer != [] else [-1] # 3차 def solution(arr, divisor): answer = [a for a in arr if a % divisor == 0] return sorted(answer) if answer != [] else [-1] ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/Jaewon0702.py ================================================ def solution(arr, divisor): return sorted([v for v in arr if v % divisor == 0]) or [-1] # 100점 print(solution([5, 9, 7, 10], 5) == [5, 10]) print(solution([2, 36, 1, 3], 1) == [1, 2, 3, 36]) print(solution([3, 2, 6], 10) == [-1]) ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12910 ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/develop-sell.js ================================================ function solution(arr, divisor) { let answer = []; let arr2 = arr.map((i) => {if (i % divisor === 0){ return i }}) let arr3 = arr.filter(i => i % divisor === 0) arr3.sort((a, b) => a - b) return arr3.length === 0 ? [-1] : arr3; } // 문제풀이: // 이번 문제는 배열에서 규칙(룰)에 맞는 요소만 빼서 배열로 다시 만들어야 하는 문제이다. // 이 경우 filter라는 함수를 쓰면 매우 수월하다. // 처음에 filter란 함수를 모르고 그 동안 많이 봤던 map함수로 코드를 짜봤다. (arr2) // 문제는 map은 배열의 모든 요소를 return 한다는 점이었다. // 즉 map함수는 배열의 모든 요소에 접근해서 규칙에 따라 그 요소를 변경할 때 쓰는 용도이다.a // 따라서 map함수를 접고, filter라는 함수로 // 룰에 맞는 요소만 배열로 남기고, 이를 sort해서 return하면 된다. // 마지막에 배열의 길이가 0이면 [-1] 배열을 리턴하고, 아니면 그대로 리턴하도록 짰다. // 느낀점: // 오... 얼마 안되었지만 // map, filter 함수의 용도를 뭔가 알아가는 느낌이 처음으로 들어 기분이 좋았다! // 아마도 더 생각했으면 코드를 1-2줄로도 충분히 짤 수 있을것 같았다! // 사용 함수 및 기능: // map : 배열에서 규칙에 따라 요소를 바꿔 배열로 만듬 (처음과 return해서 나온 배열의 길이 동일) => 2차원배열에서 큰 힘을 발휘할 듯 싶다! 저번 문제처럼 // filter : 배열에서 규칙에 맞는 요소만 빼서 배열로 만들 때 사용 // sort : sort((a,b) => a-b) 오름차순! // 삼항연산자 : return 마지막 문 ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/dkdlelk99.py ================================================ def solution(arr, divisor): answer = [] for i in arr: if i % divisor == 0: answer.append(i) answer.sort() if answer == []: return [-1] return answer print(solution([5,9,7,10],5) == [5,10] ) ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12910 * @param arr : 자연수를 담은 배열 * arr[i] ≠ arr[j] * 길이 1 이상인 배열 * @param divisor : 자연수 * @return divisors 로 나누어 떨어지는 원소를 오름차순으로 정렬한 배열 * divisor로 나누어 떨어지는 element가 하나도 없다면 [-1] */ function solution(arr, divisor) { const result = arr.filter((num) => num % divisor === 0); return result.length > 0 ? result.sort((a, b) => a - b) : [-1]; } console.log(solution([5, 9, 7, 10], 5)); //[5, 10] console.log(solution([2, 36, 1, 3], 1)); //[1, 2, 3, 36] console.log(solution([3, 2, 6], 10)); //[-1] // 옛날에 푼 것 function solution2(arr, divisor) { var answer = []; answer = arr.filter(i => i % divisor === 0).sort((a, b) => a - b); if (answer.length === 0) { return [-1]; } return answer; } ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/khw970421.js ================================================ function solution(arr, divisor) { let answer=[]; arr.forEach(function(e){ if(e%divisor==0) //나누어 떨어지면 추가 answer.push(e); }) answer.sort((a,b)=>a-b); //정렬 return (answer.length>0)?answer:[-1]; //값이 존재하면 answer 아니면 [-1]리턴 } ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/rockmiin.py ================================================ def solution(arr, divisor): answer=[] for i in arr: if i % divisor ==0: answer.append(i) if(answer==[]): answer.append(-1) return sorted(answer) print( solution([5, 9, 7, 10], 5), solution([5, 9, 7, 10], 5)==[5, 10] ) ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12910 나누어 떨어지는 숫자 배열 [풀이] 0. 나머지가 0 인 수 찾기 1. divmod 사용 ''' def solution(arr, divisor): answer = [i for i in sorted(arr) if divmod(i, divisor)[1] == 0] return answer if len(answer) != 0 else [-1] ''' 배울 점이 있는 코드 def solution(arr, divisor): return sorted([n for n in arr if n%divisor == 0]) or [-1] len == 0 을 비교할 때는 if else 대신 False or True 를 이용할 수 있음 ''' ================================================ FILE: programmers/난이도별/level01.나누어_떨어지는_숫자_배열/sjjyy.java ================================================ package 난이도별.level01.나누어_떨어지는_숫자_배열; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class sjjyy { public static int[] solution(int[] arr, int divisor) { List List = new ArrayList<>(); for (int value : arr) { if (value % divisor == 0) List.add(value); } if (List.isEmpty()) List.add(-1); int[] ans = new int[List.size()]; for (int i = 0 ; i < List.size() ; i++) ans[i]= List.get(i); Arrays.sort(ans); return ans; } public static int[] solution2(int[] arr, int divisor) { int [] answer = Arrays.stream(arr) .boxed() .filter(v -> v % divisor == 0) .sorted((a, b) -> a - b) .mapToInt(Integer::valueOf) .toArray(); return answer.length == 0 ? new int[]{-1} : answer; } public static void main(String [] args) { int[] arr = {5, 9, 7, 10}; int divisor = 5; System.out.println(Arrays.toString(solution(arr, divisor))); // [5, 10] System.out.println(Arrays.toString(solution2(arr, divisor))); // [5, 10] } } ================================================ FILE: programmers/난이도별/level01.내적/6047198844.py ================================================ def solution(a, b): return sum([i*j for i,j in zip(a,b)]) ================================================ FILE: programmers/난이도별/level01.내적/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/70128 문제 : 내적 ''' def solution(a, b): return sum([x*y for x,y in zip(a,b)]) ================================================ FILE: programmers/난이도별/level01.내적/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/70128 내적 [풀이] 1. zip 사용 ''' def solution(a, b): return sum([i*j for i, j in zip(a, b)]) ''' ''' ================================================ FILE: programmers/난이도별/level01.다트_게임/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/17682 문제 : 다트 게임 10점짜리를 list로 쪼갰을 때 1,0으로 구분하지 않도록 십으로 바꿔준 후 한글자씩 쪼갰습니다. 그 후 score에 점수 넣고 조건별로 계산하도록 했습니다. 다른 사람 풀이 보고 덕분에 정규식 공부하긴 했는데 다른 문제 풀 때 정규식을 적용시킬 수 있을런지  ̄▽ ̄;; ''' def solution(dartResult): score = [] pow_score = { 'S' : 1, 'D' : 2, 'T' : 3 } if '10' in dartResult : dartResult = dartResult.replace('10','십') answer = list(dartResult) for i in answer : if i.isdigit() : score.append(int(i)) elif i == '십' : score.append(10) elif i in pow_score : score[-1] = pow(score[-1],pow_score[i]) elif i == '*' : score[-1] *= 2 if len(score) >= 2 : score[-2] *= 2 else : score[-1] *= -1 return sum(score) ================================================ FILE: programmers/난이도별/level01.다트_게임/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/17682 ================================================ FILE: programmers/난이도별/level01.다트_게임/develop-sell.js ================================================ function solution(dartResult) { let answer = 0; let temp = 0; let checkoption = true; let post = 0; const pow = (num, upper) => (Math.pow(num, upper)) //삼항연산자로 3개의 조건을 걸 수 있는 방법은 없는가? function pow_num (num, char){ if(char === 'S') { return num; } if (char === 'D') { return pow(num, 2); } return pow(num, 3) } function option_num(num, char){ if(char === '*'){ answer = answer - post + post * 2; return num * 2; } else{ return num * (-1); } } dartResult = dartResult.split('') let len = dartResult.length let char = '' for(let i = 0; i < len; i++){ char = dartResult[i] //integer인지, float인지, string인지, array인지 아는 방법 찾기 if (char * 1 >= 0 && char * 1 <= 10 ){ if (checkoption === false){ answer += temp; post = temp } if (char * 1 === 1){ if(dartResult[i+1] * 1 === 0 ){ i ++; temp = 10 } else temp = char * 1; } else{ temp = char * 1; } } else if (char === 'S' || char === 'D' || char === 'T'){ temp = pow_num(temp, char); checkoption = false; } else{ if(checkoption === false){ checkoption = true temp = option_num(temp, char) answer += temp; post = temp } } } if(dartResult[len - 1] !== '*' && dartResult[len - 1] !== '#') answer += temp return answer; } // 문제풀이: // 먼저 숫자인지, S,D,T인지, opiton인지에 따라 분기처리 했습니다. // 숫자의 경우, 만약 숫자가 10이면 i ++해서 다음 index는 실행하지 않게 하고, 대신 temp(현재 변하는 값을 담는 변수)를 // 10으로 설정했습니다. // S,D,T의 경우가 가장 쉬웠는데, // 문자에 따라 제곱하는 숫자가 다르도록 함수를 짜서 진행했습니다. // 마지막 옵션의 경우 // *이면 전 값도 두배로 하는 부분이 까다로웠습니다. // 이걸 다른 분들 코드 보니까, 아예 1회차,2회차마다 값을 저처럼 answer에 더하는게 아니라 // 어떠한 배열에 1회차, 2회차 값 별로 정리하는게 * 옵션을 다룰 때 훨씬 좋겠다는 생각했습니다. // #이면 현재 값을 -1을 곱해주면 되어서 쉬었습니다. // 마지막으로 옵션은 말그대로 옵션이라서 // 있을 수도, 없을 수도 있는데 // 그걸 판단하기 위해 checkoption 변수를 둬서 // checkoption은 S,D,T 분기 부분 끝나고 무조건 false로 만들게 했고, // 그 다음 옵션과 숫자로 가는데, // 만약 숫자로 가게 되면 옵션이 없이 연산이 끝난거니까, 바로 temp를 answer에 더했습니다. // 그리고 전 값이 필요해서 post 변수에 temp를 저장했습니다. // 옵션으로 가게 되어도 이 부분을 추가했습니다. // 후기: // 와우... 처음으로 긴 알고리즘을 풀었는데 너무 어려웠네요, // 혹시 더 좋은 코드 있으면 알려주시면 감사하겠습니다! ================================================ FILE: programmers/난이도별/level01.다트_게임/dkdlelk99.py ================================================ def solution(dartResult): score = [] for i in range(len(dartResult)): if dartResult[i] == "S": if dartResult[i-2:i] == '10': score.append(10) score.append(int(dartResult[i-1])) elif dartResult[i] == "D": if dartResult[i-2:i] == '10': score.append(100) score.append(int(dartResult[i-1]) ** 2) elif dartResult[i] == "T": if dartResult[i-2:i] == '10': score.append(1000) score.append(int(dartResult[i-1]) ** 3) elif dartResult[i] == "*": if len(score) > 1: score[-2] *= 2 score[-1] *= 2 elif dartResult[i] == "#": score[-1] *= -1 return sum(score) print(solution("1S2D*3T") == 37) print(solution("1D2S#10S") == 9) print(solution("1D2S0T") == 3) print(solution("1S*2T*3S") == 23) print(solution("1D#2S*3S") == 5) print(solution("1T2D3D#") == -4) print(solution("1D2S3T*") == 59) ================================================ FILE: programmers/난이도별/level01.다트_게임/eyabc.js ================================================ const JSTestModule = require('/Users/ey/DKU/Algorithm/JSTestModule.js'); const englishToNumber = { 'S': 1, 'D': 2, 'T': 3, }; function solution (dartResult) { const answer = [0, 0, 0]; const dartLen = dartResult.length; const ansLen = answer.length; let i = 0, a = -1; while (a < ansLen && i < dartLen) { const currChar = dartResult.charAt(i); if (currChar === '#') { answer[a] *= -1; i++; continue; } if (currChar === '*') { answer[a] *= 2; answer[a - 1] && (answer[a - 1] *= 2); i++; continue; } if (dartResult.charAt(i + 1)) { let nextChar = dartResult.charAt(i + 1); const Squared = englishToNumber[nextChar]; a++; if (!Squared) { answer[a] = (currChar + nextChar) ** englishToNumber[dartResult.charAt(i + 2)]; i += 3; continue; } answer[a] = currChar ** Squared; i += 2; } } return answer.reduce((sum, value) => sum + value); }; JSTestModule('/Users/ey/DKU/Algorithm/programmers/카카오/다트게임/test.json', solution); ================================================ FILE: programmers/난이도별/level01.다트_게임/rockmiin.py ================================================ def solution(dartResult): result = [] for i, j in enumerate(dartResult): if j == "S": if dartResult[i - 2: i] == "10": result.append(10) else: result.append(int(dartResult[i - 1])) elif j == "D": if dartResult[i - 2: i] == "10": result.append(10 ** 2) else: result.append(int(dartResult[i - 1]) ** 2) elif j == "T": if dartResult[i - 2: i] == "10": result.append(10 ** 3) else: result.append(int(dartResult[i - 1]) ** 3) elif j == "*": if len(result) < 2: result[-1] *= 2 elif len(result) >= 2: result[-1] *= 2 result[-2] *= 2 elif j == "#": result[-1] *= -1 return sum(result) print( solution("1S*2D#3T"), solution("1S*2D#3T")==25 ) ================================================ FILE: programmers/난이도별/level01.다트_게임/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17682 다트 게임 0. 숫자, 보너스, 옵션에 대한 점수 계산 1. 정규식 사용 ''' import re def solution(dartResult): record = re.findall('[0-9]{1,2}[SDT][*#]|[0-9]{1,2}[SDT]', dartResult) scores = [] for i in record: a = int(''.join(re.findall('[0-9]', i))) b = ''.join(re.findall('[SDT]', i)) c = ''.join(re.findall('[*#]', i)) if b == 'S': score = a elif b == 'D': score = a ** 2 else: score = a ** 3 if c == "*": score *= 2 if scores: scores[-1] *= 2 elif c == "#": score = -score scores.append(score) return sum(scores) ''' if문으로 해당 index의 값을 비교하기 보다는, 미리 딕셔너리화 해서 key값으로 바로 참조하기 정규식을 좀 더 깔끔하게 쓸 것 def solution(dartResult): bonus = {'S' : 1, 'D' : 2, 'T' : 3} option = {'' : 1, '*' : 2, '#' : -1} p = re.compile('(\d+)([SDT])([*#]?)') dart = p.findall(dartResult) for i in range(len(dart)): if dart[i][2] == '*' and i > 0: dart[i-1] *= 2 dart[i] = int(dart[i][0]) ** bonus[dart[i][1]] * option[dart[i][2]] answer = sum(dart) return answer ''' ================================================ FILE: programmers/난이도별/level01.다트_게임/sjjyy.java ================================================ package 난이도별.level01.다트_게임; public class sjjyy { public static int solution(String dartResult) { char[] darts = dartResult.toCharArray(); int[] score = new int[3]; int index = -1; for (int i = 0; i < darts.length; i++) { if (darts[i] >= '0' && darts[i] <= '9') { index++; if (darts[i] == '1' && darts[i + 1] == '0') // 두자릿수 숫자(10)일 때 { score[index] = 10; i++; } else score[index] = darts[i] - '0'; } else if (darts[i] == 'D') score[index] = (int) Math.pow(score[index], 2); else if (darts[i] == 'T') score[index] = (int) Math.pow(score[index], 3); else if (darts[i] == '*') { if (index > 0) score[index - 1] *= 2; score[index] *= 2; } else if (darts[i] == '#') score[index] *= -1; } return score[0] + score[1] + score[2]; } public static void main(String[] args) { String dartResult = "1S2D*3T"; System.out.println(solution(dartResult)); // 37 System.out.println(solution("1D2S#10S")); // 9 System.out.println(solution("1D2S0T")); // 3 System.out.println(solution("1S*2T*3S")); // 23 System.out.println(solution("1D#2S*3S")); // 5 System.out.println(solution("1T2D3D#")); // -4 System.out.println(solution("1D2S3T*")); // 59 } } ================================================ FILE: programmers/난이도별/level01.동물의_아이디와_이름/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT ANIMAL_ID, NAME FROM ANIMAL_INS ORDER BY ANIMAL_ID ================================================ FILE: programmers/난이도별/level01.두 정수 사이의 합/6047198844.py ================================================ def solution(a, b): if a > b: return solution(b, a) return sum(range(a,b+1)) ================================================ FILE: programmers/난이도별/level01.두_개_뽑아서_더하기/6047198844.cpp ================================================ #include #include #include using namespace std; vector solution(vector numbers) { vector answer; set s; int numbers_size = numbers.size(); for(int i=0;i { return(a-b);}) return answer; } ================================================ FILE: programmers/난이도별/level01.두_개_뽑아서_더하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/68644 두 개 뽑아서 더하기 [풀이] ''' def solution(numbers): answer = [] size = len(numbers) for i in range(size-1): for j in range(i+1,size): answer.append(numbers[i] + numbers[j]) return sorted(set(answer)) ''' ''' ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12912 문제 : 두 정수 사이의 합 min, max로 a,b값을 재설정해주고 더하였습니다. 굳이 for문을 사용하지 않아도 sum 함수 안에 범위를 지정해줄 수 있더라구요 [메모] sum(range(a,b+1)) ''' def solution(a, b): sum = 0 a,b = min(a,b),max(a,b) for i in range(a,b+1) : sum += i return sum ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/HyeonJeong.c ================================================ #include #include #include int main(void){ printf("%d %d", &solution(a,b), 12L) } long long solution(int a, int b) { long long answer = 0; if(a != b){ int max = a > b ? a : b; int min = a < b ? b : a; for (int i = 0; i <= max - min; i++) answer += min + i; } else // a와 b가 같은 경우는 둘 중 아무 수나 리턴 answer = a; return answer; } ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/Jaewon0702 .py ================================================ def solution(a, b): return sum(range(min(a, b), max(a, b) + 1)) print(solution(3, 5) == 12) print(solution(3, 3) == 3) print(solution(5, 3) == 12) ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/README.md ================================================ # 출처 *** https://programmers.co.kr/learn/courses/30/lessons/12912 ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/develop-sell.js ================================================ function solution(a, b) { var answer = 0; var max = 0; var min = 0; if (a >= b){ max = a; min = b; } else{ max = b; min = a; } for (var i = min; i <= max; i++){ answer += i; } return answer; } // 정말 너무 길게 생각 없이 짠거 같다.. // 아마 max나 min이라는 함수가 있지 않을까? 한 줄 코드는 불가능한가? // var result = 0 // //함수를 완성하세요 // return (a+b)*(Math.abs(b-a)+1)/2; // 역시 한 줄 코드가 있었다. // 양 끝의 숫자의 합 * 숫자 개수 / 2 = 덧셈 1~n의 값 (가우스의 법칙) ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/dkdlelk99.py ================================================ def solution(a, b): answer = 0 if a == b: return a elif a > b: for i in range(b,a+1): answer += i elif b > a: for i in range(a,b+1): answer += i # 같은 결과, 좋은 코드 # x, y = max(a,b) , min(a,b) # for i in range(y, x+1): # answer += i return answer print(solution(4, 4) == 4) print(solution(4, 6) == 4 + 5 + 6) print(solution(-4, 3) == (-4) + (-3) + (-2) + (-1) + 0 + 1 + 2 + 3) ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12912?language=javascript * @param a 정수 / -10,000,000 이상 10,000,000 이하 * @param b 정수 / -10,000,000 이상 10,000,000 이하 * @return {number} a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수 */ const sumDirectionAbs = (num) => { const abs = Math.abs(num); const direction = num > 0 ? 1 : -1; return [(abs + 1) * abs / 2, direction, abs]; }; function solution(a, b) { if ((a + b) === 0) return 0; const [aSum, aDirection, aAbs] = sumDirectionAbs(a); const [bSum, bDirection, bAbs] = sumDirectionAbs(b); if (aDirection !== bDirection) return aSum * aDirection + bSum * bDirection; let [diff, small] = [bSum - aSum, aAbs]; if (diff < 0) [diff, small] = [aSum - bSum, bAbs]; return (diff + small) * aDirection; } // 상민님 풀이 function solution2(a, b) { return ~~((a + b) * (Math.abs(a - b) + 1) / 2); } console.log(solution(3, 5) === 12); console.log(solution(-3, -5) === -12); console.log(solution(-3, 5) === 9); // -6 + 15 = 9 console.log(solution(3, -5) === -9); console.log(solution(3, 3) === 3); console.log(solution(5, 3) === 12); console.log(solution(0, 0) === 0); console.log(solution(0, 1) === 1); console.log(solution(0, 1) === 1); console.log(solution(1, 1) === 1); console.log(solution(-1, 1) === 0); ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/rockmiin.py ================================================ def solution(a, b): sum=0 for i in range(a if ab else b+1): sum+=i return sum print(solution(3, 5), solution(3, 5)==12, solution(5, 3), solution(5, 3)==12 ) ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12912 두 정수 사이의 합 [풀이] 1. 간단한 수학적 공식 이용 : n(n+1)/2 ''' def solution(a, b): return (a+b)*(abs(a-b)+1)//2 ''' ''' ================================================ FILE: programmers/난이도별/level01.두_정수_사이의_합/sjjyy.java ================================================ package 난이도별.level01.두_정수_사이의_합; import java.util.stream.LongStream; public class sjjyy { public static long solution(int a, int b) { long answer = 0; if (a <= b) { for (int i = a; i <= b; i++) answer += i; } else { for (int i = b; i <= a; i++) answer += i; } return answer; } public static long solution2(int a, int b) { long ans = 0; int x = Math.min(a, b); int y = Math.max(a, b); for(int i = x ; i <= y ; i++) ans += i; return ans; } public static long solution3(int a, int b) { int min = Math.min(a, b), max = Math.max(a, b); return LongStream.rangeClosed(min, max).reduce(0, Long::sum); } public static void main(String [] args) { System.out.println(solution(3, 5)); // 12 System.out.println(solution(3, 3)); // 3 System.out.println(solution(5, 3)); // 12 System.out.println(solution2(3, 5)); // 12 System.out.println(solution2(3, 3)); // 3 System.out.println(solution2(5, 3)); // 12 System.out.println(solution3(3, 5)); // 12 System.out.println(solution3(3, 3)); // 3 System.out.println(solution3(5, 3)); // 12 } } ================================================ FILE: programmers/난이도별/level01.로또의_최고_순위와_최저_순위/6047198844.py ================================================ def solution(lottos, win_nums): cnt = 0 for l in lottos: cnt += l in win_nums high = min(6,7-cnt-lottos.count(0)) low = min(6,7-cnt) return [high,low] ================================================ FILE: programmers/난이도별/level01.로또의_최고_순위와_최저_순위/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/77484 문제 : 로또의 최고 순위와 최저 순위 lottos의 숫자가 win_nums에 있는지 확인하고, 0이 모두 정답일 때와 0이 모두 정답이 아닐 때를 넣어줍니다. ''' def solution(lottos, win_nums): answer = [] rank = [6,6,5,4,3,2,1] win = 0 zero = lottos.count(0) for i in set(lottos) : if i in win_nums : win += 1 answer.append(rank[win+zero]) answer.append(rank[win]) return answer ================================================ FILE: programmers/난이도별/level01.로또의_최고_순위와_최저_순위/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/77484 로또의 최고 순위와 최저 순위 [풀이] ''' def solution(lottos, win_nums): rank = [6, 6, 5, 4, 3, 2, 1] unk = lottos.count(0) win = 6 - len(set(win_nums) - set(lottos)) return [rank[win + unk], rank[win]] ''' ''' ================================================ FILE: programmers/난이도별/level01.모든_레코드_조회하기/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT * FROM ANIMAL_INS ORDER BY ANIMAL_ID ================================================ FILE: programmers/난이도별/level01.모의고사/6047198844.py ================================================ import collections def solution(answers): give_up_maths = [[1, 2, 3, 4, 5], [2, 1, 2, 3, 2, 4, 2, 5], [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]] cnts = [] for idx, answer in enumerate(answers): for n in range(0,3): if give_up_maths[n][idx % len(give_up_maths[n])] == answer: cnts.append(n+1) cnts = collections.Counter(cnts).most_common() return sorted([i for i, cnt in cnts if cnt == cnts[0][1]]) ================================================ FILE: programmers/난이도별/level01.모의고사/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/42840 문제 : 모의고사 i%len(student)로 나머지를 이용해 검사하였습니다. max값을 가진 index를 return하여 답을 구하였습니다. ''' def solution(answers): answer = [0,0,0] student1 = [1,2,3,4,5] student2 = [2,1,2,3,2,4,2,5] student3 = [3,3,1,1,2,2,4,4,5,5] for i in range(len(answers)) : if answers[i] == student1[i%len(student1)] : answer[0] += 1 if answers[i] == student2[i%len(student2)] : answer[1] += 1 if answers[i] == student3[i%len(student3)] : answer[2] += 1 return [x+1 for x in range(len(answer)) if answer[x]==max(answer)] ================================================ FILE: programmers/난이도별/level01.모의고사/HyeonJeong.py ================================================ def solution(answers): student = [0, 0, 0] check = [[1, 2, 3, 4, 5], [2, 1, 2, 3, 2, 4, 2, 5], [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]] for i, n in enumerate(answers): for j, m in enumerate(check): if m[i % len(m)] == n: student[j] += 1 return [s + 1 for s in range(len(student)) if student[s] == max(student)] print(solution([1,2,3,4,5]) == [1]) print(solution([1,3,2,4,2]) == [1,2,3]) ================================================ FILE: programmers/난이도별/level01.모의고사/Jaewon0702 .py ================================================ def solution(answers): math_haters=[[1,2,3,4,5], [2,1,2,3,2,4,2,5], [3,3,1,1,2,2,4,4,5,5]] scores=[0]*len(math_haters) for i,answer in enumerate(answers) : for k,marking in enumerate(math_haters) : if answer==marking[i%len(marking)] : scores[k]+=1 return [i+1 for i,score in enumerate(scores) if max(scores)==score] #100점 print(solution([1,2,3,4,5])==[1]) print(solution([1,3,2,4,2])==[1,2,3]) ================================================ FILE: programmers/난이도별/level01.모의고사/JeongShin.js ================================================ /* 주석은 코드 리뷰 수정 */ function solution(answers) { // const students = [[1, 2, 3, 4, 5], [2, 1, 2, 3, 2, 4, 2, 5], [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]] // .map(arr => arr = {pattern: arr, len: arr.length}) const students = [[1, 2, 3, 4, 5], [2, 1, 2, 3, 2, 4, 2, 5], [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]] .map(pattern => ({ pattern, isMatch: (idx, ans) => (pattern[idx % pattern.length] === ans) * 1 })) const scores = answers.reduce((scores, currAns, idx) => { return scores.map((currScore, currStudent) => // { const {pattern, len} = students[currStudent]; // return currScore + (pattern[idx % len] === currAns) } currScore + students[currStudent].isMatch(idx, currAns) ) }, new Array(3).fill(0)); const max = Math.max(...scores); return scores.reduce((arr, score, idx) => { score === max ? arr.push(idx + 1) : 0 return arr; }, []).sort((a, b) => a - b); } function solution2(answers) { const students = [[1, 2, 3, 4, 5], [2, 1, 2, 3, 2, 4, 2, 5], [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]] .map(pattern => ({ pattern, isMatch: (idx, ans) => (pattern[idx % pattern.length] === ans) * 1 })); const scores = answers.reduce((scores, currAns, idx) => { return scores.map((currScore, currStudent) => currScore + students[currStudent].isMatch(idx, currAns)) }, new Array(3).fill(0)); const max = Math.max(...scores); return scores.reduce((arr, score, idx) => { score === max ? arr.push(idx + 1) : 0; return arr; }, []).sort((a, b) => a - b); } solution([1, 2, 3, 4, 5]) ================================================ FILE: programmers/난이도별/level01.모의고사/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42840 ================================================ FILE: programmers/난이도별/level01.모의고사/develop-sell.js ================================================ function solution(answers) { let answer = [1,2,3] const p1 = [1,2,3,4,5] //5 const p2 = [2,1,2,3,2,4,2,5] //8 const p3 = [3,3,1,1,2,2,4,4,5,5] //10 let p1_c = answers.filter((v, i) => (p1[i % 5] === v ? v : "")).length let p2_c = answers.filter((v, i) => (p2[i % 8] === v ? v : "")).length let p3_c = answers.filter((v, i) => (p3[i % 10] === v ? v : "")).length let arr = [p1_c, p2_c, p3_c]; let max = 0; max = p1_c > p2_c ? p1_c : p2_c; max = max > p3_c ? max : p3_c return answer.filter((v, i) => (arr[i] >= max ? v : "")); } // 문제풀이: // player 1,2,3의 답이 계속 중복되는데, // 이때 중복되는 구간의 사이즈가 다르다. 1부터 5,8,10 사이즈 // 그래서 먼저 그 구간을 값을 넣은 배열로 const 지정해줬다. // 그 후 filter 함수를 통해 answers 배열과 맞는 경우만 탐색해서 그것의 length를 구해서 // 맞은 갯수가 알게 되었다. // 이때 p2[i % 8] 이런식으로 하면 딱 안 나눠지는 부분까지 캐치하게 된다 (중요 포인트!) // 그 후 값들의 가장 큰 값을 max 구해서, max과 같거나 큰 answer를 filter해서 제출한다. // 배운점: // Math.max 함수 존재 // var max = Math.max(a1c,a2c,a3c); ================================================ FILE: programmers/난이도별/level01.모의고사/dkdlelk99.py ================================================ def solution(answers): # 1번 12345 # 2번 2 1 2 3 2 4 2 5 8개 반복 # 3번 33 11 22 44 55 10개 반복 answer_1 = [1,2,3,4,5] answer_2 = [2,1,2,3,2,4,2,5] answer_3 = [3,3,1,1,2,2,4,4,5,5] a, b, c = 0, 0, 0 for i in range(len(answers)): if answers[i] == answer_1[i%5]: a += 1 if answers[i] == answer_2[i%8]: b += 1 if answers[i] == answer_3[i%10]: c += 1 temp = [[a,1],[b,2],[c,3]] temp = sorted(temp, reverse = True) answer = [temp[0][1]] if temp[1][0] == temp[0][0]: answer.append(temp[1][1]) if temp[2][0] == temp[0][0]: answer.append(temp[2][1]) return sorted(answer) print(solution([1, 2, 3, 4, 5]) == [1] ) print(solution([1, 3, 2, 4, 2]) == [1, 2, 3] ) ================================================ FILE: programmers/난이도별/level01.모의고사/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42840 function solution(answers) { const arr = [ [1, 2, 3, 4, 5], [2, 1, 2, 3, 2, 4, 2, 5], [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] ] const len = arr.map(v => v.length) const result = arr.map((v, k) => answers.map((v2, k2) => v[k2 % len[k]] === v2).filter(v2 => v2).length) const max = Math.max(...result) const answer = [] result.forEach((v, k) => { if (v == max) answer.push(k + 1) }) return answer } console.log(solution([1,2,3,4,5]),[1]) console.log(solution([1,3,2,4,2]),[1, 2, 3]) ================================================ FILE: programmers/난이도별/level01.모의고사/rockmiin.py ================================================ def solution(answers): cnt=[0, 0, 0] ret_value=[] m1=[1, 2, 3, 4, 5] m2=[2, 1, 2, 3, 2, 4, 2, 5] m3=[3, 3, 1, 1, 2, 2, 4, 4, 5, 5] for i, j in enumerate(answers): if answers[i] == m1[i%5]: cnt[0]+=1 if answers[i] == m2[i%8]: cnt[1]+=1 if answers[i] == m3[i%10]: cnt[2]+=1 for i in range(3): if max(cnt)==cnt[i]: ret_value.append(i+1) return ret_value print( solution([1, 3, 2, 4, 2]), solution([1, 3, 2, 4, 2])==[1,2,3], solution([1,2,3,4,5]), solution([1,2,3,4,5])==[1] ) ================================================ FILE: programmers/난이도별/level01.모의고사/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42840# 모의고사 [풀이] 0. 각자의 비법을 실제 문제와 비교 True 개수를 비교하여 출력 ''' def solution(answers): size = len(answers) score = lambda x, y : x == y one = list(map(score, answers, [1,2,3,4,5]*(size // 5 + 1))).count(True) two = list(map(score, answers, [2,1,2,3,2,4,2,5]*(size // 8+ 1))).count(True) thr = list(map(score, answers, [3,3,1,1,2,2,4,4,5,5]*(size // 10 + 1))).count(True) answers = [one, two, thr] return [i+1 for i in range(3) if answers[i] == max(one, two, thr)] ''' ''' ================================================ FILE: programmers/난이도별/level01.모의고사/sjjyy.java ================================================ package 난이도별.level01.모의고사; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; public class sjjyy { public static int[] solution(int[] answers) { int[] ans1 = {1, 2, 3, 4, 5}; int[] ans2 = {2, 1, 2, 3, 2, 4, 2, 5}; int[] ans3 = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5,}; int a = 0, b = 0, c = 0; int len = answers.length; for (int i = 0; i < len; i++) { if (answers[i] == ans1[i % 5]) a++; if (answers[i] == ans2[i % 8]) b++; if (answers[i] == ans3[i % 10]) c++; } int max = Math.max(a, Math.max(b, c)); List list = new ArrayList<>(); if (max == a) list.add(1); if (max == b) list.add(2); if (max == c) list.add(3); int[] answer = new int[list.size()]; for (int i = 0; i < list.size(); i++) { answer[i] = list.get(i); } return answer; } public static int[] solution2(int[] answers) { int[] ans1 = {1, 2, 3, 4, 5}; int[] ans2 = {2, 1, 2, 3, 2, 4, 2, 5}; int[] ans3 = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5,}; int[] score = new int[3]; int len = answers.length; for (int i = 0; i < len; i++) { if (answers[i] == ans1[i % 5]) score[0]++; if (answers[i] == ans2[i % 8]) score[1]++; if (answers[i] == ans3[i % 10]) score[2]++; } int max = Math.max(score[0], Math.max(score[1], score[2])); List list = new ArrayList<>(); if (max == score[0]) list.add(1); if (max == score[1]) list.add(2); if (max == score[2]) list.add(3); int[] answer = new int[list.size()]; for (int i = 0; i < list.size(); i++) { answer[i] = list.get(i); } return answer; } public static int[] solution3(int[] answers) { int[][] ans = { {1, 2, 3, 4, 5}, {2, 1, 2, 3, 2, 4, 2, 5}, {3, 3, 1, 1, 2, 2, 4, 4, 5, 5} }; int[] score = new int[3]; int len = answers.length; for (int i = 0; i < len; i++) { if (answers[i] == ans[0][i % 5]) score[0]++; if (answers[i] == ans[1][i % 8]) score[1]++; if (answers[i] == ans[2][i % 10]) score[2]++; } int max = Math.max(score[0], Math.max(score[1], score[2])); return IntStream.rangeClosed(1, 3) .filter(i -> score[i - 1] == max) .toArray(); /* List list = new ArrayList<>(); if (max == score[0]) list.add(1); if (max == score[1]) list.add(2); if (max == score[2]) list.add(3); return list.stream().mapToInt(i -> i).toArray(); */ } public static void main(String[] args) { System.out.println(Arrays.toString(solution(new int[]{1, 2, 3, 4, 5}))); // [1] System.out.println(Arrays.toString(solution(new int[]{1, 3, 2, 4, 2}))); // [1, 2, 3] System.out.println(Arrays.toString(solution2(new int[]{1, 2, 3, 4, 5}))); System.out.println(Arrays.toString(solution2(new int[]{1, 3, 2, 4, 2}))); System.out.println(Arrays.toString(solution3(new int[]{1, 2, 3, 4, 5}))); System.out.println(Arrays.toString(solution3(new int[]{1, 3, 2, 4, 2}))); } } ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/6047198844.py ================================================ def solution(s): return s.count('p') + s.count('P') == s.count('y') + s.count('Y') ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12916 문제 : 문자열 내 p와 y의 개수 count() 함수를 이용해서 p와 y의 개수를 구하고 비교하였습니다. if문을 사용하여 판별하고 return 하였는데 다른 사람 코드를 보니 단순히 한 줄로 True, False를 판별하고 반환할 수 있네요 [메모] return s.lower().count('p') == s.lower().count('y') ''' def solution(s): p = s.count('p') + s.count('P') y = s.count('y') + s.count('Y') return True if p==y else False ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/HyeonJeong.java ================================================ package 난이도별.level01.문자열_내_p와_y의_개수; public class HyeonJeong { public static boolean solution(String s) { return s.chars() .reduce(0, (count, c) -> { if (c == 'P' || c == 'p') return count + 1; if (c == 'Y' || c == 'y') return count - 1; return count; }) == 0; } public static void main(String[] args) { System.out.println(solution("pPoooyY")); //true System.out.println(solution("Pyy")); //false } } ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/HyeonJeong.py ================================================ def solution(s): p_num = 0 y_num = 0 for c in s: if c in 'pP': p_num += 1 elif c in 'yY': y_num += 1 return p_num == y_num print( solution("pPoooyY") == True, solution("Pyy") == False ) ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/Jaewon0702.py ================================================ def solution(s): return s.lower().count("p") == s.lower().count("y") # 100점 print(solution("pPoooyY") == True) print(solution("Pyy") == False) ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12916 ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/develop-sell.js ================================================ function solution(s){ var answer = true; var ans = 0; for(let i =0; i < s.length; i++){ let char = s.charCodeAt(i); (char === 80 || char === 112) ? ans += 1 : ''; (char === 89 || char === 121) ? ans -= 1 : ''; } if (ans !== 0){ answer = false } return answer; } // 아이디어: 개수만큼 각각 더하고, 빼서 0이면 true, 아니면 false로 되게 만들었다. // 생각보다 긴 코드로 짠 것 같다.. // programmers 한줄코드 // return s.toUpperCase().split("P").length === s.toUpperCase().split("Y").length; // toUpperCase : 다 대문자로 만들어버림..!! // split : 문자열을 일정한 구분자로 잘라서 배열로 저장하기 위해서 쓴다 // 여기선 각각 P, Y로 split하는데, 갯수가 같으면 같은 값이 나오기에 true가 나온다. // 근데 배열로 split이 되는데, 왜 true가 나올까? 배열의 size로 비교하기 때문인가? // ex. pypy => ["", "y", "y"] / ypyp => ["", "p", "p"] // 라고 생각했는데 뒤에 length가 있었다... ㅎㅎ length가 같은걸로 비교 !! ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/dkdlelk99.py ================================================ def solution(s): s = s.lower() print(s) return s.count('p') == s.count('y') print(solution("oooo") == True) print(solution('pPooYy') == True) print(solution("pPPYy") == False) ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/junilhwang.js ================================================ function solution(s){ const str = [ ...s ] return str.filter(v => ['p', 'P'].indexOf(v) !== -1).length === str.filter(v => ['y', 'Y'].indexOf(v) !== -1).length; } require('./test.json').forEach(({ input, output }) => console.log(solution(...input) === output)) ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/junilhwang.py ================================================ import json def solution(s): s = s.lower() return s.count('p') == s.count('y') with open('./test.json') as testFile: for v in json.load(testFile): print(solution(*v['input']) == v['output']) ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/rockmiin.py ================================================ def solution(s): cnt_p=0; cnt_y=0 for i in s: if i == 'P' or i=='p': cnt_p+=1 if i == 'Y' or i == 'y': cnt_y+=1 if cnt_p==cnt_y: return True return False solution('pPoooyY') ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12916 문자열 내 p와 y의 개수 : P,p와 Y,y의 개수 비교 count ''' def solution(s): return s.count('p') + s.count('P') == s.count('y') + s.count('Y') ''' 대소문자 무관하게 비교 할 때는 lower() 또는 upper() 사용하기 return s.lower().count('p') == s.lower().count('y') ''' ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/sjjyy.java ================================================ package 난이도별.level01.문자열_내_p와_y의_개수; public class sjjyy { public static boolean solution(String s) { // int p = s.toLowerCase().split("p").length; // int y = s.toLowerCase().split("y").length; return s.toLowerCase().chars().filter(i -> 'p' == i).count() == s.toLowerCase().chars().filter(i -> 'y' == i).count(); } public static boolean solution2(String s) { int p = 0, y = 0; s = s.toLowerCase(); for (int i = 0 ; i < s.length(); i++) { if (s.charAt(i) == 'p') p++; if(s.charAt(i) == 'y') y++; } return p == y; } public static void main(String[] args) { String s = "Pyy"; System.out.println(solution(s)); // false System.out.println(solution("pPoooyY")); // true System.out.println(solution("oooo")); // true System.out.println(solution2("PypY")); // true System.out.println(solution2("oooo")); // true System.out.println(solution2("pPoooyY")); // true } } ================================================ FILE: programmers/난이도별/level01.문자열_내_p와_y의_개수/test.json ================================================ [ { "input": [ "oooo" ], "output": true }, { "input": [ "pPooYy" ], "output": true }, { "input": [ "pPPYy" ], "output": false } ] ================================================ FILE: programmers/난이도별/level01.문자열_내_마음대로_정렬하기/6047198844.txt ================================================ def solution(strings, n): return sorted(sorted(strings), key = lambda string:string[n]) ================================================ FILE: programmers/난이도별/level01.문자열_내_마음대로_정렬하기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12915 문제 : 문자열 내 마음대로 정렬하기 처음에는 dictionary의 key에 문자열 넣고, value에 n자리 값 넣어서 value 정렬하려고 혼자 이것저것 뻘짓하고 value 정렬법 찾다가 sorted에 lambda사용해서 너무 간단하게 정렬하는 방법을 알게 됐다. 헤멘건 나뿐인가봐,, 똑똑한 사람들 ⚆_⚆;; ''' def solution(strings, n): return sorted(sorted(strings), key=lambda x:x[n]) ================================================ FILE: programmers/난이도별/level01.문자열_내_마음대로_정렬하기/HyeonJeong.py ================================================ def solution(strings, n): return sorted(sorted(strings) , key=lambda s: s[n]) # 내부 sorted는 인덱스 n의 값이 같은 것은 사전 순 배열이 필요 print( solution(["sun", "bed", "car"],1) == ['car', 'bed', 'sun'], solution(["abce", "abcd", "cdx"], 2) == ["abcd", "abce", "cdx"] ) ================================================ FILE: programmers/난이도별/level01.문자열_내_마음대로_정렬하기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12915 ================================================ FILE: programmers/난이도별/level01.문자열_내_마음대로_정렬하기/develop-sell.js ================================================ function solution(strings, n) { let arr = strings.map((str) => str[n]+str); arr.sort(); return arr.map((str) => str.slice(1)) } // 문제풀이: // 우선 같은 길이의 배열을 반환한다는 점에서 map함수를 활용 해야겠다고 생각했다. // 단, 같은 길이의 배열이지만 요소의 순서가 바뀐다는 조건이 하나가 더 있었다. // 그래서 우선 map를 해서 n번째에 해당되는 요소를 먼저 빼고 생각해봤다. // 처음엔 map((str,i) => str[n] +i) 로 해서 index를 같이 넘겨주고 이에 맞게 해야하나 // 싶었는데, 이 또한 2번 일하는 것 같다는 느낌이 들었다. // 그러다 조건을 읽으니 같은 문자의 경우 사전순으로 정렬한다고 했다. // 그래서 str[n]에 원래 str값도 뒤에 붙여서 넘겼고, // 문자열에 맞게 sort 후 // 맨 앞 자리의 str[0]만 빼려고 slice()함수를 활용했다. // 활용하기 좋은 방법: // 1. 중간중간에 console.log 로 내가 하는 것이 맞는가 확인할 것 // console.log(arr); // arr.sort(); // console.log(arr); // 여기선 이렇게 해서 sort가 제대로 먹는지 확인했다. (문자열은 그냥 sort()해도 괜찮나보다...? 맞나요??? ) // 숫자 sort할 때는 sort((a,b)=> a-b)로 해야 오름차순이 된다. // 배운점: // 오... 진짜 꾸준히 해서 그런지 함수들이 점차 익숙해지고 있는 느낌이 든다! // map(), sort(), slice() 함수를 활용했고, // slice()의 경우 지난번에 배웠는데 기억이 잘 안났지만, // console로 찍어보면서 숫자 하나만 넣으면 해당 인덱스부터 끝까지 자를거 같은 느낌으로 했더니 되었다! ㅎㅎ ================================================ FILE: programmers/난이도별/level01.문자열_내_마음대로_정렬하기/dkdlelk99.py ================================================ def solution(strings, n): return sorted(sorted(strings), key= lambda x : x[n]) print(solution( ["sun", "bed", "car"],1) == ['car', 'bed', 'sun']) print(solution( ["abce", "abcd", "cdx"], 2) == ["abcd", "abce", "cdx"]) ================================================ FILE: programmers/난이도별/level01.문자열_내_마음대로_정렬하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12915 문자열 내 마음대로 정렬하기 : 원하는 인덱스를 키로 문자 정렬하기 해당 인덱스의 문자를 문자열 맨 앞으로 추가해서 정렬 ''' def solution(strings, n): return [i[1:] for i in sorted([i[n] + i for i in strings])] ''' sorted는 key를 가지고 정렬할 수 있다는 점 알기 return sorted(strings, key=lambda x: x[n]) ''' ================================================ FILE: programmers/난이도별/level01.문자열_내_마음대로_정렬하기/sjjyy.java ================================================ package 난이도별.level01.문자열_내_마음대로_정렬하기; import java.util.*; public class sjjyy { public static String[] solution(String[] strings, int n) { int len = strings.length; for (int i = 0 ; i < len ; i++) strings[i] = strings[i].charAt(n) + strings[i]; Arrays.sort(strings); String [] ans = new String[len]; for (int i = 0 ; i < len ; i++) ans[i] = strings[i].substring(1); return ans; } public static String[] solution2(String[] strings, int n) { List list = new ArrayList<>(); for (String string : strings) list.add(string.charAt(n) + string); Collections.sort(list); String [] ans = new String[list.size()]; for (int i = 0 ; i < list.size() ; i++) ans[i] = list.get(i).substring(1); return ans; } public static String[] solution3(String [] strings, int n) { return Arrays.stream(strings) .sorted(String::compareTo) .sorted(Comparator.comparingInt(a -> a.charAt(n))) .toArray(String[]::new); } public static void main(String [] args) { String [] strings = {"sun", "bed", "cat"}; String [] strs = {"abcd", "abce", "cdx"}; // System.out.println(Arrays.toString(solution(strings, 1))); // System.out.println(Arrays.toString(solution(strs, 2))); // System.out.println(Arrays.toString(solution2(strings, 1))); // System.out.println(Arrays.toString(solution2(strs, 2))); System.out.println(Arrays.toString(solution3(strings, 1))); System.out.println(Arrays.toString(solution3(strs, 2))); } } ================================================ FILE: programmers/난이도별/level01.문자열_내_마음대로_정렬하기/turquoiseluv.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12915 처음에 sorted와 lambda로 string[n:]을 기준으로 정렬하는 코드를 썼다가 질문하기에서 25점 맞은 분 팁을 읽고 n 인덱스가 같은 문자열끼리는 전체 문자의 순서로 정렬하는 것을 깨달음 1) 소문자 알파벳(범위 제시됨) 크기의 alphabet 배열 생성 1) n 인덱스가 같은 문자들끼리 append 3) alphabet 안의 각 배열 정렬 4) 모든 배열 합친 ans 반환 string[n:] => (string[n], string) 이런식으로 했으면 바로 정렬 가능 튜플 정렬: "첫번쨰 원소 같으면 두번째 원소로 정렬 된다." def solution(strings, n): return sorted(strings, key=lambda str: (str[n], str)) ''' strings = ["abce", "abcd", "cdx"] n = 2 def solution(strings, n): ans = [] alphabet = [[] for _ in range(26)] for string in strings: alphabet[ord(string[n])-ord("a")].append(string) return sum(list(map(lambda x : x.sort(), alphabet))) print(solution(strings, n)) ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/6047198844.py ================================================ def solution(s): return ''.join(sorted(s))[::-1] ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12917 문제 : 문자열 내림차순으로 배치하기 처음에는 ord(), chr()을 이용해서 아스키 코드로 바꾸고 정렬해서 문제를 해결했는데 매번 피드백 받은 것처럼 한 줄로 줄이고 더 간단하게 할 수 있는지 이것저것 시도해보다가 문자열 자체로도 정렬이 가능한 걸 알게 됐네요 ^^ 피드백 감사합니다! ''' def solution(s): return "".join(sorted(s,reverse=True)) ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/HyeonJeong.py ================================================ # 정렬이 소문자 -> 대문자 됨. def solution(s): return "".join(sorted(s, reverse = True)) print(solution("Zbcdefg") == "gfedcbZ") ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/Jaewon0702.py ================================================ def solution(s): return "".join(sorted(list(s), reverse=True)) # 100점 print(solution("Zbcdefg") == "gfedcbZ") ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12917 ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/develop-sell.js ================================================ function solution(s) { var answer = ''; var ans = []; for(let i=0; i < s.length; i++ ){ ans.push(s.charAt(i)); } ans.sort((a, b) => a < b ? 1 : -1) answer = ans.join(''); return answer; } // sort하는 부분에서 헤매다가 junilhwang님 코드를 보고 풀었습니다 // join하고도 seperater부분에 ''을 넣어줘야 ','가 안 들어갑니다 (,가 default인가..??) ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/dkdlelk99.py ================================================ def solution(s): return ''.join(sorted(list(s), reverse=True)) print(solution("Zbcdefg") == "gfedcbZ") print(solution("bdcaET") == "dcbaTE") ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/junilhwang.js ================================================ function solution (s) { return [ ...s ].sort((a, b) => a < b ? 1 : -1).join('') } require('./test.json').forEach(({ input, output }) => console.log(solution(...input) === output)) ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/junilhwang.py ================================================ import json def solution(s) : return ''.join(sorted(list(s), reverse=True)) with open('./test.json') as testFile: for v in json.load(testFile): print(solution(*v['input']) == v['output']) ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/khw970421.js ================================================ function solution(s) { const split =s.split(''); let number=[]; let answer=[]; split.forEach(function(e){ number.push(e.charCodeAt(0)) //문자를 아스키 코드 숫자로 변환 }) number.sort((A,B)=>B-A); //아스키코드 숫자로 정렬 number.forEach(function(e){ answer+=String.fromCharCode(e); //정렬후 다시 문자로 변환 }) return answer; } //junilwang.js 코드를 본 후 const를 이용해 변수생성할 필요는 없구나 s.split('') === [...s] function solution(s) { let number=[]; let answer=[]; [...s].forEach(function(e){ number.push(e.charCodeAt(0)) //문자를 아스키 코드 숫자로 변환 }) number.sort((A,B)=>B-A); //아스키코드 숫자로 정렬 number.forEach(function(e){ answer+=String.fromCharCode(e); //정렬후 다시 문자로 변환 }) return answer; } //junilwang.js 코드를 본 후 function solution (s) { return [ ...s ].sort((a, b) => a < b ? 1 : -1).join(''); } /* [..s]로 전부 배열에 문자열을 분리시킨 후 sort를 이용해 a= 0 ; i--) { if (c[i] >= 'a') lower.append(c[i]); else upper.append(c[i]); } return String.valueOf(lower.append(upper)); } public static String solution2(String str) { char[] c = str.toCharArray(); Arrays.sort(c); return new StringBuilder(new String(c)).reverse().toString(); } public static void main(String[] args) { System.out.println(solution("Zbcdefg")); System.out.println(solution2("Zbcdefg")); } } ================================================ FILE: programmers/난이도별/level01.문자열_내림차순으로_배치하기/test.json ================================================ [ { "input": [ "Zbcdefg" ], "output": "gfedcbZ" }, { "input": [ "bdcaET" ], "output": "dcbaTE" } ] ================================================ FILE: programmers/난이도별/level01.문자열_다루기_기본/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12918 문제 : 문자열 다루기 기본 파이썬 예외처리를 이용해서 int로 바꿀 때 error가 나면 false를 반환해주도록 했습니다. 다른 사람 풀이를 보니 isdigit()이라는 유용한 함수가 있어 기록합니다. [메모] return s.isdigit() and len(s) in (4,6) ''' def solution(s): if len(s)==4 or len(s)==6 : try : n = int(s) except : return False else : return False return True ================================================ FILE: programmers/난이도별/level01.문자열_다루기_기본/HyeonJeong.py ================================================ def solution(s): # 조건에 안맞는 것들을 바로 return 시키면 더 효율적인 코드가 됨. if len(s) != 4 and 6 : return False for i in s : if i not in "0123456789": return False return True print(solution("a234")) ================================================ FILE: programmers/난이도별/level01.문자열_다루기_기본/Jaewon0702.py ================================================ def solution(s): return s.isdigit() and len(s) in [4, 6] # 100점 print(solution("a234")) print(solution("1234")) ================================================ FILE: programmers/난이도별/level01.문자열_다루기_기본/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12918 ================================================ FILE: programmers/난이도별/level01.문자열_다루기_기본/dkdlelk99.py ================================================ def solution(s): for i in s: try: if type(int(i)) != int: return False except: return False return len(s) == 4 or len(s) == 6 print(solution('a12f') == False) print(solution('1234') == True) ================================================ FILE: programmers/난이도별/level01.문자열_다루기_기본/rockmiin.py ================================================ def solution(s): if len(s)==4 or len(s)==6: for i in s: if ord(i)>=58: return False return True return False print(solution("a234")==False) ================================================ FILE: programmers/난이도별/level01.문자열_다루기_기본/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12918 문자열 다루기 기본 [풀이] 1. 문자열의 길이가 4 또는 6이면서 숫자로만 구성하기 2. str을 int casting 할 때의 에러로 구분. ''' def solution(s): try: return str(int(s)) == s and (len(s) == 4 or len(s) == 6) except: return False ''' isalpha와 isdigit을 사용하면 쉽게 문자열의 문자, 숫자 판단을 할 수 있다. or 을 이용한 비교 보다는 in (4, 6)으로 비교하면 간단하다. def alpha_string46(s): return s.isdigit() and len(s) in (4, 6) ''' ================================================ FILE: programmers/난이도별/level01.문자열_다루기_기본/sjjyy.java ================================================ package 난이도별.level01.문자열_다루기_기본; public class sjjyy { public static boolean solution(String s) { int len = s.length(); if (len == 4 || len == 6) { try { Integer.parseInt(s); // 문자열 -> 정수 return true; } catch (NumberFormatException e) { // 숫자 형식 오류 return false; } } return false; } public static boolean solution2(String s) { int len = s.length(); if (len == 4 || len == 6) return s.matches("[0-9]+"); return false; } public static void main(String[] args) { System.out.println(solution("1234")); // true System.out.println(solution("s123")); // false System.out.println(solution2("1234")); // true System.out.println(solution2("s123")); // false System.out.println(solution2("4323s2")); // false } } ================================================ FILE: programmers/난이도별/level01.문자열을_정수로_바꾸기/6047198844.py ================================================ def solution(s): return int(s) ================================================ FILE: programmers/난이도별/level01.문자열을_정수로_바꾸기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12925 문제 : 문자열을 정수로 바꾸기 ''' def solution(s): return int(s) ================================================ FILE: programmers/난이도별/level01.문자열을_정수로_바꾸기/HyeonJeong.py ================================================ #1 '''def solution(s): if "+-" not in s: return int(s) return int(+s[1:]) if s[0] == "+" else int(-s[1:])''' #2 s가 정수일 때 가능함 def solution(s): return int(s) print(solution("-1234") == -1234) ================================================ FILE: programmers/난이도별/level01.문자열을_정수로_바꾸기/Jaewon0702.py ================================================ def solution(s): return int(s) print(solution("1234") == 1234) print(solution("-1234") == -1234) ================================================ FILE: programmers/난이도별/level01.문자열을_정수로_바꾸기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12925 ================================================ FILE: programmers/난이도별/level01.문자열을_정수로_바꾸기/develop-sell.js ================================================ function solution(s) { return s * 1; } //가볍게 생각하면 되는 문자였다. //자바스크립트는 문자를 숫자로 형변환할 때 곱하기 1 해주는 것이 좋은 방법 같다. ================================================ FILE: programmers/난이도별/level01.문자열을_정수로_바꾸기/dkdlelk99.py ================================================ def solution(s): if s.find('.') != -1: return int(s) else: return float(s) print(solution('12345') == 12345) print(solution('-321') == -321) ================================================ FILE: programmers/난이도별/level01.문자열을_정수로_바꾸기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12925 문자열을 정수로 바꾸기 : 문제가 아무래도 캐스팅 없이 풀어야 되는 문제인가 싶다 int ''' def solution(s): return int(s) ''' ''' ================================================ FILE: programmers/난이도별/level01.문자열을_정수로_바꾸기/sjjyy.java ================================================ package 난이도별.level01.문자열을_정수로_바꾸기; public class sjjyy { public static int solution(String s) { return Integer.parseInt(s); } public static void main(String[] args) { System.out.println(solution("12435")); // 12435 System.out.println(solution("+2314")); // 2314 System.out.println(solution("-314")); // -314 } } ================================================ FILE: programmers/난이도별/level01.비밀지도/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/17681 문제 : [1차] 비밀지도 비트 연산자를 사용해서 arr1과 arr2를 or연산한 후 2진수로 바꿔줬습니다. zfill 함수를 사용해서 앞의 여백을 0으로 채워 5글자로 만들고 1을 #으로 0을 ' '로 바꿔주었습니다. ''' def solution(n, arr1, arr2): answer = [] for i in range(n) : binary = bin(arr1[i]|arr2[i])[2:].zfill(n) cipher = binary.replace('1','#') cipher = cipher.replace('0',' ') answer.append(cipher) return answer ================================================ FILE: programmers/난이도별/level01.비밀지도/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/17681 ================================================ FILE: programmers/난이도별/level01.비밀지도/dkdlelk99.py ================================================ def solution(n, arr1, arr2): answer = [] for i in range(n): array = "" binary1 = bin(arr1[i])[2:] binary2 = bin(arr2[i])[2:] if len(binary1) < n: binary1 = "0" * (n-len(binary1)) + binary1 if len(binary2) < n: binary2 = "0" * (n-len(binary2)) + binary2 for j in range(n): if binary1[j] == '1' or binary2[j] == '1': array += "#" else: array += " " answer.append(array) return answer print(solution( 5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28]) == \ ["#####", "# # #", "### #", "# ##", "#####"]) print(solution( 6, [46, 33, 33, 22, 31, 50], [27, 56, 19, 14, 14, 10]) == \ ["######", "### #", "## ##", " #### ", " #####", "### # "]) ================================================ FILE: programmers/난이도별/level01.비밀지도/eyabc.js ================================================ const convertToBinary = (num, n) => num.toString(2).padStart(n, '0'); function solution(n, arr1, arr2) { return arr1.map((num, i) => { const map1 = convertToBinary(num, n); const map2 = convertToBinary(arr2[i], n); let newMap = ""; for (let i = 0; i < n ; i++) { newMap += ((map1[i]*1 + map2[i]*1) === 0) ? ' ' : '#'; } return newMap; }) } const assert = require('assert').strict; require('./test.json').forEach(({ input, output }) => { assert.deepEqual(solution(...input), output); }); ================================================ FILE: programmers/난이도별/level01.비밀지도/khw970421.js ================================================ //처음 성공한 코드 (for문에 난잡) function solution(n, arr1, arr2) { let answer = []; let number,length=arr1.length; let Sarr1 =[]; let Sarr2 = []; for(let i=0;i(a|arr2[i]).toString(2).padStart(n,0).replace(/0/g,' ').replace(/1/g,'#')) } ================================================ FILE: programmers/난이도별/level01.비밀지도/rockmiin.py ================================================ def solution(n, arr1, arr2): def combine(arr1, arr2): com=['' for _ in range(len(arr1))] for i in range(len(arr1)): for j in range(len(arr2)): if(arr1[i][j]==1 or arr2[i][j]==1): com[i]+='#' else: com[i]+= ' ' return com def binary(array): res=[[0 for _ in range(n)]for _ in range(n)] for i in range(len(array)): for j in range(n): if (array[i] >= pow(2, n - j - 1)): res[i][j] = 1 array[i] -= pow(2, n - j - 1) return res res1= binary(arr1) res2= binary(arr2) # print(res1) # print(res2) return combine(res1, res2) if __name__=="__main__": n=5 arr1=[9, 20, 28, 18, 11] arr2=[30, 1, 21, 17, 28] print(solution(n, arr1, arr2)) ================================================ FILE: programmers/난이도별/level01.비밀지도/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17681 비밀지도 1. array의 원소는 어떤 이진수의 십진수. 이 이진수는 n*n에 대한 암호 => 두 개의 array를 합한 array는 최종 암호이다. 1은 #으로 0은 공백으로 표현 => bin으로 이진수 치환. zip으로 바로 리스트화. re.sub으로 1과 0 대체 ''' import re def solution(n, arr1, arr2): cipher = [bin(i | j)[-n:] for i, j in zip(arr1, arr2)] for i in range(len(cipher)): cipher[i] = re.sub('1','#',cipher[i]) cipher[i] = re.sub('[0b]',' ',cipher[i]) return cipher ''' 배울만한 풀이. 1) rjust 함수 => 오른쪽 정렬 후 해당 크기 만큼 문자열 생성, 빈 공간을 해당 문자로 치환 2) re.sub 대신 간단하게 replace 사용 가능 def solution(n, arr1, arr2): answer = [] for i,j in zip(arr1,arr2): a12 = str(bin(i|j)[2:]) a12=a12.rjust(n,'0') a12=a12.replace('1','#') a12=a12.replace('0',' ') answer.append(a12) return answer ''' ''' 한줄 풀이 1) 문자열 포맷터를 이용 => int: {0:d}, bin: {0:b}, oct: {0:o}, hex: {0:x}".format(num) 2) 위 rjust와는 0으로만 채울 수 있는 점을 제외하고는 비슷. => str.zfill(n) : 해당 자리수가 되도록 앞에 0을 채움 return [''.join(map(lambda x: '#' if x=='1' else ' ', "{0:b}".format(row).zfill(n))) for row in (a|b for a, b in zip(arr1, arr2))] ''' ================================================ FILE: programmers/난이도별/level01.비밀지도/sjjyy.java ================================================ package 난이도별.level01.비밀지도; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.IntStream; public class sjjyy { public static String[] solution(int n, int[] arr1, int[] arr2) { String [] arr = new String[n]; for(int i = 0 ; i < n ; i++) { arr[i] = Integer.toBinaryString(arr1[i] | arr2[i]) .replace("1", "#") .replace("0", " "); } return arr; } public static String solution2(int n, int[] arr1, int[] arr2) { return IntStream.range(0, n).mapToObj(i -> Integer.toBinaryString(arr1[i] | arr2[i]) .replace("1", "#") .replace("0", " ")).collect(Collectors.joining(", ")); } public static void main(String[] args) { int[] arr1 = new int[]{9, 20, 28, 18, 11}; int[] arr2 = new int[]{30, 1, 21, 17, 28}; System.out.println(Arrays.toString(solution(5, arr1, arr2))); // [#####, # # #, ### #, # ##, #####] System.out.println(solution2(5, arr1, arr2)); // [#####, # # #, ### #, # ##, #####] } } ================================================ FILE: programmers/난이도별/level01.상위_n개_레코드/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT NAME FROM ANIMAL_INS ORDER BY DATETIME LIMIT 1 ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/6047198844.py ================================================ def solution(seoul): return "김서방은 " + str(seoul.index("Kim")) + "에 있다" ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12919 문제 : 서울에서 김서방 찾기 index 함수를 사용해서 Kim이 있는 index를 찾아 반환하였습니다. 반환할 때 저는 string을 +로 합쳐서 반환하였는데 다른 사람들 코드에서 format을 사용하는 게 많아 잊지 않으려고 메모합니다. [메모] '김서방은 {}에 있다'.format(seoul.index("Kim")) ''' def solution(seoul): return '김서방은 '+str(seoul.index("Kim"))+'에 있다' ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/HyeonJeong.java ================================================ package 난이도별.level01.서울에서_김서방_찾기; public class HyeonJeong { public String solution(String[] seoul) { String answer = ""; for(int i = 0; i < seoul.length; i++){ if(seoul[i].equals("Kim")){ answer = "김서방은 "+i+"에 있다"; break; } } return answer; } } ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/HyeonJeong.py ================================================ #방법1 ''' def solution(seoul): for m, n in enumerate(seoul): if "Kim" == n: return ("김서방은 %d에 있다" %m) # return "김서방은 {}에 있다".format(m) ''' #방법2 : "Kim"이 리스트에 한번만 존재하므로 index()사용 def solution(seoul): return "김서방은 %d에 있다" %index("Kim") # return "김서방은 {}에 있다".format(seoul.index("Kim")) print(solution(["Jane","Kim"]) == "김서방은 1에 있다") ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/Jaewon0702.py ================================================ def solution(seoul): return "김서방은 %d에 있다" % seoul.index("Kim") # 100점 print(solution(["Jane", "Kim"]) == "김서방은 1에 있다") ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/README.md ================================================ # 출처 *** https://programmers.co.kr/learn/courses/30/lessons/12919?language=python3 ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/develop-sell.js ================================================ function solution(seoul) { let index = seoul.findIndex((i) => i === "Kim") return "김서방은 " + index +"에 있다"; } // 문제 풀이: // 처음에는 배열의 길이보다 작은 배열을 뽑기 때문에 // index를 빼기 위해 기존의 filter라는 함수를 쓰려고 했다. // 그러다가 filter 함수는 요소(배열의 원소) 내용을 // 바꿀 수 없다는 것을 알게 되었다. // 그래서 고민하다가 구글링을 통해 findIndex라는 함수를 알게 되어 // 사용해서 풀게 되었다. // 배운점: // console.log(seoul.indexOf('Kim')) // indexOf 라는 함수도 동일한 역할을 한다. // console.log(seoul.filter((i) => i ==="Kim")) // filter는 이런 경우 사용 용도가 불분명하다. // filter는 string의 가운데 값이 뭐인 경우만 뺄 때, // 혹은 int값이 뭐보다 크거나 작은 경우 , 뺄 때 사용한다 ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/dkdlelk99.py ================================================ def solution(seoul): index = seoul.index('Kim') answer = '김서방은 %d에 있다'%index return answer seoul = ['Jane', 'Kim'] print(solution(seoul)) ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/rockmiin.py ================================================ def solution(seoul): answer="" for i in range(len(seoul)): if seoul[i]=="Kim": answer="김서방은 "+str(i)+"에 있다" return answer print( solution(["Jane", "Kim"]), solution(["Jane", "Kim"])=="김서방은 1에 있다" ) ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12919 서울에서 김서방 찾기 1. list.index ''' def solution(seoul): return "김서방은 "+str(seoul.index("Kim"))+"에 있다" ''' ''' ================================================ FILE: programmers/난이도별/level01.서울에서_김서방_찾기/sjjyy.java ================================================ package 난이도별.level01.서울에서_김서방_찾기; public class sjjyy { public static String solution(String[] seoul) { int index = 0; for (int i = 0 ; i < seoul.length ; i++) { if (seoul[i].equals("Kim")) index = i; } return "김서방은 " + index + "에 있다"; } public static void main(String [] args) { String [] seoul = {"Jane", "Kim"}; System.out.println(solution(seoul)); } } ================================================ FILE: programmers/난이도별/level01.소수_만들기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12977 소수 만들기 [풀이] 1. 아리스토테네스의 채 ''' from itertools import combinations def solution(nums): nums = sorted([sum(i) for i in combinations(nums, 3)]) rear = nums[-1] sieve = [True] * (rear+1) for i in range(2, rear+1): if sieve[i] == True: for j in range(i+i, rear+1, i): sieve[j] = False return [sieve[i] for i in nums].count(True) ''' ''' ================================================ FILE: programmers/난이도별/level01.소수찾기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12921 문제 : 소수 찾기 처음에는 본인을 제외한 2 이상의 수로 나누어 떨어지는 것이 없는지 전부 계산하여 소수를 찾았습니다. 그러면 효율성 테스트가 0점이 나오더라구요. 소수를 더 빠르게 구하는 방법으로 에라토스테네의 체를 알게 되었고 배열에 소수를 찾을 범위를 넣고, 배수를 없애는 방법으로 문제를 풀었습니다. ''' def solution(n): answer = 0 n_array = [i for i in range(n+1)] for i in range(2,n+1) : if n_array[i] : for j in range(i*2,n+1,i) : n_array[j] = False for i in range(2,n+1) : if n_array[i] : answer += 1 return answer ================================================ FILE: programmers/난이도별/level01.소수찾기/HyeonJeong.py ================================================ #시도 ''' def solution(n): answer = [2] for x in range(3, n + 1, 2): if x == 3: answer.append(3) else: for y in range(3, x, 2): if x % y == 0: break elif y == x - 2: answer.append(x) return len(answer) ''' # 에라토스테네스의 체 코드로 완성 def solution(n): num = [False, False] + [True] * (n - 1) for i in range(2, n + 1): if num[i] == True: for j in range(i + i, n + 1, i): num[j] = False return len([i for i in range(2, n + 1) if num[i] == True]) print( solution(10) == 4, solution(5) == 3 ) ================================================ FILE: programmers/난이도별/level01.소수찾기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12921 ================================================ FILE: programmers/난이도별/level01.소수찾기/develop-sell.js ================================================ // 내 코드 function solution(n) { let answer = 0; for(let i = 2; i <= n; i++){ let isPrime = true; if (i === 2){ answer ++; continue; } if (i === 3){ answer ++; continue; } if (i % 2 === 0){ continue; } for(let j = 2; j < i/2; j++){ if(i % j === 0){ isPrime = false; break; } } if (isPrime === true) answer++; } return answer; } // 소수찾기 생각보다 쉬워보여서 도전했다가 생각보다 오랜 시간이 걸렸다 // 소수찾는 로직은 쉬웠지만, 효율성에서 문제가 발생했다. // 소수찾는 로직(처음) : 이중 for문으로 2~ n-1 수까지 n을 나눠보고 만약 값이 딱 맞게 나눠지면(i % j == 0) 그 수는 소수가 아닌 것이다. // 1차 효율성 고려 : 자신 수의 절반 숫자로까지만 나누자. (ex. 14의 경우 절반인 7까지만 나눠보면 소수인지 아닌지 판단할 수 있다.) // i / 2 까지만 확인 // 2차 효율성 고려 : 자신 수+1 의 루트만큼만 나누자. // Math.sqrt(i+1) 까지만 확인 // 3차 효율성 고려 : 2의 배수는 다 제거하자 // 앞에 2로 나눠서 0이 되는 경우는 다 제거해주자 // 이렇게 총 3번 도전을 했는데, 마지막 4개의 효율성에선 문제가 계속 있어서 계속 고려하다가 eyabc님의 코드를 보고 이해하는 것으로 공부했다. // 출처 : eyabc.js // 아이디어는 위에 2로 나눠서 0이 되는 경우뿐만 아니라 // 3,5 등 계속 소수면 그에 해당되는 배수들을 접근할때 바로 소수가 아니라고 지칭하는 것이다. (false -> true) // 그렇게 되면 현저히 나누는 값들의 개수가 줄어들게 된다. // ex. 11을 확인할때는 이미 1,2,3 ... 10까지 할 때 2,3,5,7들의 배수들인 4,6,8,10 / 3,6,9 / 5,10 은 이미 true 값이라 // 비교를 안하고 continue문으로 빠져나간다. // 그렇게 되면 이 경우엔 1,2,3,4,5,6,7,8,9,10까지 모든 숫자가 비교를 안해도 되고 바로 소수임을 인정하고 이에 해당되는 모든 배수를 또 소수로 만드는 식이다. // 배수를 true로 바꿔주는 식 (i+i , j = j + i) 이 식이 헷갈렸다 for (let j = i + i ; j < N ; j += i) { primeTable[j] = true; } // 생각보다 비교하는 식이 오래걸린다. // 제외할 조건들은 continue로 최대한 빼주고 // for문 도는 횟수를 줄이는 것이 목표다. (for문 한번 돌 때 status를 바꿔주는 식 ) ================================================ FILE: programmers/난이도별/level01.소수찾기/dkdlelk99.py ================================================ def solution(n): num = {i for i in range(3, n+1, 2)} for i in range(3, n+1, 2): num -= set(i for i in range(i*2, n+1, i)) return len(num) + 1 print(solution(5) == 3) print(solution(10) == 4) print(solution(20) == 8) ================================================ FILE: programmers/난이도별/level01.소수찾기/dosimpact.py ================================================ # 토스 체 def solution(n: int): # check -1 이면 검사 안한것 check = [-1 for i in range(0, n + 1)] pc = 0 # prime count pn = [] # prime array # 2,3,....n for i in range(2, n + 1): if check[i] == -1: pc += 1 pn.append(i) # 5*5 =25 , 30, 35 ,... n for j in range(i * i, n + 1, i): check[j] = 1 # print(f"Primse is {pn}") return pc print(solution(10)) print(solution(5)) ================================================ FILE: programmers/난이도별/level01.소수찾기/eyabc.js ================================================ /** https://programmers.co.kr/learn/courses/30/lessons/12921 * 1부터 입력받은 숫자 n 사이에 있는 소수의 개수를 반환하는 함수, * 소수는 1과 자기 자신으로만 나누어지는 수를 의미합니다. (1은 소수가 아닙니다.) * n은 2이상 1000000이하의 자연수입니다. * @param n * @return */ function solution(n) { const N = n + 1; // 해당 수가 소수인지 아닌지를 기록하는 표(배열을 만듭니다) // n 이 10 이라면 [false,.... 가 11개 존재합니다.] 0 은 사용하지 않는 인덱스 입니다. const primeTable = new Array(N).fill(false); const max = Math.sqrt(N); // 2부터 Math.sqrt(N) 까지 수가 소수인지 판별하는 로직 입니다. // 1 은 소수가 아니므로 2 부터 셉니다. for (let i = 2 ; i < max ; i++) { // 만약 셀려는 값의 인덱스가 true 이면, 해당 수는 이미 어떤 소수의 배수이므로, 해당 수의 배수가 되는 수를 찾을 필요가 없습니다. if (primeTable[i]) continue; // 해당 수가 소수일 경우, 해당 수의 배수가 되는 수는 모두 소수가 아니므로 true 로 바꾸어 줍니다. for (let j = i + i ; j < N ; j += i) { primeTable[j] = true; } } // primeTable 에서 false (소수인 수) 의 수를 셉니다. 2를 빼는 이유는 0 과 1 인덱스는 소수가 아니기 때문입니다. return primeTable.filter((n) => !n).length - 2; } /* 테스트 1 〉 통과 (0.06ms, 30.1MB) 테스트 2 〉 통과 (0.12ms, 30MB) 테스트 3 〉 통과 (0.16ms, 30MB) 테스트 4 〉 통과 (0.26ms, 30.3MB) 테스트 5 〉 통과 (0.18ms, 30.1MB) 테스트 6 〉 통과 (1.03ms, 29.9MB) 테스트 7 〉 통과 (0.43ms, 30.3MB) 테스트 8 〉 통과 (0.85ms, 29.9MB) 테스트 9 〉 통과 (1.11ms, 30.2MB) 테스트 10 〉 통과 (25.18ms, 35.2MB) 테스트 11 〉 통과 (31.86ms, 40.5MB) 테스트 12 〉 통과 (14.56ms, 35.7MB) 효율성 테스트 테스트 1 〉 통과 (33.26ms, 41.1MB) 테스트 2 〉 통과 (32.92ms, 41.1MB) 테스트 3 〉 통과 (33.98ms, 41.1MB) 테스트 4 〉 통과 (32.76ms, 40.9MB) */ console.log(solution(10) === 4); console.log(solution(5) === 3); // 옛날에 푼 것 function solution2(n) { const arr = []; for (let i = 0 ; i < n ; i++) arr.push(i + 1); delete arr[0]; const max = Math.sqrt(n); for (let i = 2 ; i <= max ; i++) { if (arr[i - 1]) for (let j = i + i ; j <= n ; j += i) delete arr[j - 1]; } return arr.filter(v => v).length; } /* 테스트 1 〉 통과 (1.69ms, 37.3MB) 테스트 2 〉 통과 (1.71ms, 37.2MB) 테스트 3 〉 통과 (1.79ms, 37.3MB) 테스트 4 〉 통과 (1.84ms, 37.4MB) 테스트 5 〉 통과 (1.81ms, 37.5MB) 테스트 6 〉 통과 (3.10ms, 37.6MB) 테스트 7 〉 통과 (2.09ms, 37.8MB) 테스트 8 〉 통과 (2.69ms, 37.5MB) 테스트 9 〉 통과 (3.27ms, 37.6MB) 테스트 10 〉 통과 (42.28ms, 46.9MB) 테스트 11 〉 통과 (128.40ms, 69.2MB) 테스트 12 〉 통과 (45.19ms, 46.9MB) 효율성 테스트 테스트 1 〉 통과 (129.85ms, 69.1MB) 테스트 2 〉 통과 (127.70ms, 68.9MB) 테스트 3 〉 통과 (130.71ms, 69.2MB) 테스트 4 〉 통과 (129.56ms, 69MB) */ ================================================ FILE: programmers/난이도별/level01.소수찾기/junilhwang-01.js ================================================ function solution(n) { const p = [2] for (let i = 3; i <= n; i+=2) { let bool = true for (let j = 1; p[j] <= Math.pow(i, 1/2); j++) { if (i % p[j] === 0) { bool = false break } } if (bool) p.push(i) } return p.length } ================================================ FILE: programmers/난이도별/level01.소수찾기/junilhwang-02.js ================================================ function solution(n) { const arr = [] for (let i = 0; i < n; i++) arr.push(i+1) delete arr[0] const max = Math.pow(n, 1/2) for (let i = 2; i <= max; i++) { if (arr[i-1]) for (let j = i+i; j <= n; j += i) delete arr[j-1] } return arr.filter(v => v).length } ================================================ FILE: programmers/난이도별/level01.소수찾기/khw970421.js ================================================ //처음 생성한 코드 (효율성 및 큰 n에따라 런타임아웃) function solution(n) { let k=[],count=0; for(let i=2;i<=n;i++) { count=0; for(let j=2;j1 ''' ================================================ FILE: programmers/난이도별/level01.소수찾기/sjjyy.java ================================================ package 난이도별.level01.소수찾기; import java.util.Arrays; public class sjjyy { public static int solution(int n) // 75/100 { int ans = 0; for (int i = 2; i <= n; i++) { boolean isPrime = true; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { isPrime = false; break; } } if (isPrime) ans++; } return ans; } public static int solution2(int n) // 100/100 { int ans = 0; int[] num = new int[n + 1]; for (int i = 2; i <= n; i++) // 2~n까지 배열에 추가 num[i] = i; for (int i = 2; i <= n; i++) { if(num[i] == 0) continue; for (int j = 2*i ; j <= n ; j+=i) // 값이 0이 아닌 수의 배수는 모두 0ㅇ로 처리 num[j]= 0; } // for (int i = 2 ; i <= n ; i++) // 값이 0이 아닌 수 (= 소수)의 개수 측정 // { // if (num[i] != 0) // ans++; // } // // return ans; return (int) Arrays.stream(num).filter(v -> v > 0).count(); } public static void main(String[] args) { System.out.println(solution(10)); System.out.println(solution2(10)); // 4 System.out.println(solution(5)); System.out.println(solution2(5)); // 3 } } ================================================ FILE: programmers/난이도별/level01.수박수박수박수/6047198844.py ================================================ def solution(n): return (10000*'수박')[:n] ================================================ FILE: programmers/난이도별/level01.수박수박수박수/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12922 문제 : 수박수박수박수박수박수? 저는 리스트를 만들어 n 수만큼 반복해서 넣어줬는데 다른 사람들 풀이를 보니 굳이 리스트를 만들지 않고 문자열 그대로 n 수만큼 곱해서 넣어주면 되더라구요 [메모] "".join(["수박"[i%2] for i in range(n)]) ''' def solution(n): answer = '' s = ['수','박'] for i in range (n) : answer += s[i%2] return answer ================================================ FILE: programmers/난이도별/level01.수박수박수박수/HyeonJeong.py ================================================ # 방법 1 ''' def solution(n): answer = '' word1 = '수' word2 = '박' for i in range(n) : if i % 2 == 0 : answer += word1 else : answer += word2 return answer ''' # 방법 2(더 간단하고 효율적인 코드로) def solution(n): return '수박' * (n//2) + '수' * (n % 2) print("n이 3일때 : " + solution(3)) ================================================ FILE: programmers/난이도별/level01.수박수박수박수/Jaewon0702.py ================================================ def solution(n): return "수박" * int(n // 2) + "수" * int(n % 2) print(solution(3) == "수박수") print(solution(4) == "수박수박") ================================================ FILE: programmers/난이도별/level01.수박수박수박수/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12922 ================================================ FILE: programmers/난이도별/level01.수박수박수박수/develop-sell.js ================================================ function solution(n) { var answer = ''; for(var i = 0 ; i #include #include #include char* solution(int n) { char* answer = (char*)malloc(n*sizeof(char)*3); //덤프 방지 strcpy(answer,""); for(int i=0;i find 함수는 하나만 찾기 때문에 이런 문자열 함수들을 자세히 알아둬야함 ''' def solution(s): number = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] for idx, n in enumerate(number): s = s.replace(n, str(idx)) return int(s) ''' ''' ================================================ FILE: programmers/난이도별/level01.시저_암호/6047198844.py ================================================ def solution(s, n): answer = '' for char in s: # 공백이면 안민다. if str.islower(char): char = chr(ord('a') + (ord(char) - ord('a') + n) % 26) elif str.isupper(char): char = chr(ord('A') + (ord(char) - ord('A') + n) % 26) answer += char return answer ================================================ FILE: programmers/난이도별/level01.시저_암호/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12926 문제 : 시저 암호 아스키 코드로 변경하여 n만큼 수를 더해주는 방법을 사용하였습니다. 저는 대문자, 소문자를 확인할 때도 아스키 코드를 사용하였는데 isupper(), islower()를 사용하여 더 간단하게 대소문자를 구분할 수 있었습니다. 또한 n만큼 더했을 때 알파벳 범위를 벗어나는 경우를 저는 따로 if를 사용하여 판별하였는데 이 또한 26으로 나눈 나머지를 이용하여 한 번에 구할 수 있었습니다. [메모] 대문자의 경우 : chr((ord(i)-ord('A')+n)%26+ord('A')) 소문자의 경우 : chr((ord(i)-ord('a')+n)%26+ord('a')) ''' def solution(s, n): answer = '' s = list(s) for i in s : if ord(i) == ord(' ') : answer += ' ' elif ord(i) <= ord('Z') : if n+ord(i) > ord('Z') : answer += chr(ord(i)+n-26) else : answer += chr(ord(i)+n) else : if n+ord(i) > ord('z') : answer += chr(ord(i)+n-26) else : answer += chr(ord(i)+n) return answer ================================================ FILE: programmers/난이도별/level01.시저_암호/HyeonJeong.py ================================================ def solution(s, n): answer = "" for i in s: if i == " ": answer += " " else: start = ord('A') if i.isupper() else ord('a') answer += chr((ord(i) - start + n) % 26 + start) return answer print( solution("AB", 1) == "BC", solution("z", 1) == "a", solution("a B z", 4) == "e F d" ) ================================================ FILE: programmers/난이도별/level01.시저_암호/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12926 ================================================ FILE: programmers/난이도별/level01.시저_암호/develop-sell.js ================================================ function solution(s, n) { let arr = s.split(""); let ans_arr = [] let num = 0; arr.forEach(e => { if(e === " "){ ans_arr.push(e); return; } num = e.charCodeAt(0) if(num >= 65 && num <= 90){ if(num + n > 90){ ans_arr.push(String.fromCharCode(num+n - 26)) } else ans_arr.push(String.fromCharCode(num+n)) } else{ if(num+n > 122){ ans_arr.push(String.fromCharCode(num+n - 26)) } else ans_arr.push(String.fromCharCode(num+n)) } }) return ans_arr.join(""); } // 문제풀이: // 먼저 split함수로 str을 배열로 만들고, // 배열을 forEach문으로 돌면서 n값만큼 더해준 값을 다시 ans_arr에 push하고, // ans_arr를 join함수로 다시 str로 바꿔서 제출한다. // 사용한 함수: // char.charCodeAt(0): 영문자인 char를 숫자로 바꿔주는 함수 // String.fromCharCode(num): 숫자인 num을 영문자로 바꿔주는 함수 // 알게된 점: // 1. str함수인 split를 통해 str를 배열로 만들기 // 2. forEach문은 continue문이 안 먹힌다.. return문 사용해야 함 // 3. array함수인 join을 통해 배열의 모든 요소의 병합을 str로 바꿔준다 ================================================ FILE: programmers/난이도별/level01.시저_암호/dkdlelk99.py ================================================ def solution(s, n): small = [chr(i) for i in range(ord('a'), ord('z') + 1)] big = [chr(i) for i in range(ord('A'), ord('Z') + 1)] answer = [] for c in s : if (c.isspace()): answer += c continue target = small if c.islower() else big answer += target[(target.index(c) + n) % 26] return ''.join(answer) print(solution('sdf Z',1) == 'teg A') print(solution('a B z',4) == 'e F d') ================================================ FILE: programmers/난이도별/level01.시저_암호/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12926 시저 암호 [풀이] 1. 알파벳 리스트를 사전에 구성 ''' def solution(s, n): U = [chr(i) for i in range(65, 91)] L = [chr(i) for i in range(97, 123)] answer = '' for i in s: if i in U : answer += U[(U.index(i)+n)%26] elif i in L : answer += L[(L.index(i)+n)%26] else : answer += i return answer ''' 문자열에는 isupper와 islower가 있음 if s[i].isupper(): s[i]=chr((ord(s[i])-ord('A')+ n)%26+ord('A')) elif s[i].islower(): s[i]=chr((ord(s[i])-ord('a')+ n)%26+ord('a')) ''' ================================================ FILE: programmers/난이도별/level01.시저_암호/sjjyy.java ================================================ package 난이도별.level01.시저_암호; import java.util.stream.Collectors; public class sjjyy { public static String solution(String s, int n) { StringBuilder ans = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isLowerCase(c)) c = (char) ('a' + (c + n - 'a') % 26); else if (Character.isUpperCase(c)) c = (char) ('A' + (c + n - 'A') % 26); ans.append(c); } return ans.toString(); } public static String solution2(String s, int n) { return s.chars() .map(c -> Character.isUpperCase(c) ? (char) ('A' + (c + n - 'A') % 26) : Character.isLowerCase(c) ? (char) ('a' + (c + n - 'a') % 26) : c) .mapToObj(c -> Character.toString((char) c)) .collect(Collectors.joining("")); } public static String solution3(String s, int n) { StringBuilder ans = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); ans.append( Character.isLowerCase(c) ? (char) ('a' + (c + n - 'a') % 26) : Character.isUpperCase(c) ? (char) ('A' + (c + n - 'A') % 26) : c ); } return ans.toString(); } public static void main(String[] args) { System.out.println(solution("AB", 1)); // BC System.out.println(solution("z", 1)); // a System.out.println(solution("a B z", 4)); // e F d System.out.println(solution2("AB", 1)); // BC System.out.println(solution2("z", 1)); // a System.out.println(solution2("a B z", 4)); // e F d System.out.println(solution3("AB", 1)); // BC System.out.println(solution3("z", 1)); // a System.out.println(solution3("a B z", 4)); // e F d } } ================================================ FILE: programmers/난이도별/level01.신규 아이디_추천/dosimpact.py ================================================ import sys import math from typing import * sys.setrecursionlimit(10**6) input = sys.stdin.readline # 규칙에 맞지 않는 아이디를 입력했을 때 아이디와 유사하면서 규칙에 맞는 아이디를 추천해주는 # 아이디의 길이는 3자 이상 15자 이하여야 합니다. # 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.) 문자만 사용 # 단, 마침표(.)는 처음과 끝에 사용할 수 없으며 또한 연속으로 사용할 수 없습 def solution(new_id: str): new_id = list(new_id) new_id = list(map(lambda x: (x).lower() if (x).isupper() else x, new_id)) print(new_id) # 1 def ST2(ch: str): if ch.isalnum() or ch == '-' or ch == '_' or ch == '.': return True return False new_id = list(filter(ST2, new_id)) print(new_id) # 2 new_id_parsed = [new_id[0]] for i in range(1, len(new_id)): if new_id_parsed[-1] == '.' and new_id[i] == '.': continue new_id_parsed += [new_id[i]] new_id = new_id_parsed print(new_id) # 3 if new_id and new_id[0] == '.': new_id.pop(0) if new_id and new_id[-1] == '.': new_id.pop(len(new_id)-1) print(new_id) # 4 if len(new_id) == 0: new_id += ['a'] if len(new_id) >= 16: new_id = new_id[:15] if new_id[-1] == '.': new_id.pop(len(new_id)-1) if len(new_id) == 2: new_id += [new_id[-1]] if len(new_id) == 1: new_id += [new_id[-1]]*2 return "".join(new_id) ================================================ FILE: programmers/난이도별/level01.신규_아이디_추천/6047198844.cpp ================================================ #include #include using namespace std; //새로 가입하는 유저들이 카카오 아이디 규칙에 맞지 않는 아이디를 입력했을 때, //입력된 아이디와 유사하면서 규칙에 맞는 아이디를 추천해주는 프로그램을 개발하는 것 /* 규칙 - 아이디의 길이는 3자 이상 15자 이하여야 합니다 - 아이디는 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.) 문자만 사용할 수 있습니다. - 단, 마침표(.)는 처음과 끝에 사용할 수 없으며 또한 연속으로 사용할 수 없습니다. - 7단계의 순차적인 처리 과정 */ string level7(string& new_id) { string level7Id = new_id; while (level7Id.size() <= 2) level7Id += new_id.back(); return level7Id; } string level6(string& new_id) { if (new_id.size() >= 16) { new_id = new_id.substr(0, 15); if (new_id.back() == '.') new_id.pop_back(); } return level7(new_id); } string level5(string& new_id) { if (new_id.empty()) new_id += 'a'; return level6(new_id); } string level4(string& new_id) { if (new_id[0] == '.') new_id = new_id.substr(1); if (new_id.back() == '.') new_id.pop_back(); return level5(new_id); } string level3(string& new_id) { string level3Id = ""; bool flag = false; for (int i = 0; i < new_id.size(); i++) { if (!flag|| new_id[i] != '.') { if (new_id[i] == '.') flag = true; else flag = false; level3Id += new_id[i]; } } return level4(level3Id); } string level2(string& new_id) { string level2Id = ""; for (char c : new_id) { if (c == '-' || c == '_' || c == '.' || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9')) level2Id += c; } return level3(level2Id); } string level1(string& new_id) { for (int idx = 0; idx < new_id.size(); idx++) { if ('A' <= new_id[idx] && new_id[idx] <= 'Z') new_id[idx] += 32; } return level2(new_id); } string level_start(string& new_id) { return level1(new_id); } string solution(string new_id) { string answer = level_start(new_id); return answer; } int main() { solution("...!@BaT#*..y.abcdefghijklm"); } ================================================ FILE: programmers/난이도별/level01.신규_아이디_추천/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/72410 문제 : 신규 아이디 추천 정~말 자신없었던 정규식을 쓸 수밖에 없는 문제라서 자신없게 시작한 문제였다. 공부는 했지만 막상 적용해보니 원하는대로 결과가 안나와서 당황;;; 다른 사람들 풀이를 봐보니 정규식을 안 쓰면 훨씬훨씬 복잡해지는걸 보고 정규식 공부하라고 사이트랑 같이 리뷰 달아준 오빠한테 무한 감사를 느꼈습니다 ❁´◡`❁ ''' import re def solution(new_id): new_id = new_id.lower() # 소문자로 변경 new_id = re.sub("[^a-z0-9-_.]","",new_id) # 숫자, 알파벳 소문자, 주어진 특수문자 외 나머지 삭제 new_id = re.sub("\.{2,}",".",new_id) # .이 2개 이상 연속할 경우 한 개로 변경 new_id = re.sub("^\.|\.$","",new_id) # .으로 시작하거나 .으로 끝날 경우 . 제거 if not new_id : new_id+='a' # 빈 값일 경우 'a' 추가 new_id = new_id[:15] # 길이 15까지로 자름 new_id = re.sub("\.$","",new_id) # .으로 끝날 경우 . 제거 if len(new_id) <= 2 : # 길이 짧을 경우 마지막 글자 더하기 while len(new_id) < 3 : new_id += new_id[-1] return new_id ================================================ FILE: programmers/난이도별/level01.신규_아이디_추천/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/72410 신규 아이디 추천 [풀이] 0. 정규식 사용 문제. 정규식을 모른다면 끔찍하다. ''' import re def solution(new_id): new_id = new_id.lower() new_id = ''.join(re.findall('[a-z]|[0-9]|[.]|[_]|[-]', new_id)) new_id = re.sub('[.]{2,}', '.', new_id) if len(new_id) and new_id[0] == ".": new_id = new_id[1:] if len(new_id) and new_id[-1] == ".": new_id = new_id[:-1] size = len(new_id) if not size: new_id += "a" if size >= 16: new_id = new_id[:15] if new_id[-1] == ".": new_id = new_id[:-1] while len(new_id) < 3: new_id = new_id + new_id[-1] return new_id ''' 정규식이랑 if를 너무 혼재해서 사용한 듯 하다 나보다 더 정규식을 잘 쓴 사람 코드를 배워야겠다 심지어 코드 구성도 멋지다 import re def solution(new_id): st = new_id st = st.lower() st = re.sub('[^a-z0-9\-_.]', '', st) # [^] 는 특정 문자를 제외하라는 의미 st = re.sub('\.+', '.', st) # 이 부분은 re.sub('[.]{2,}', '.', new_id)와 차이는 없다. st = re.sub('^[.]|[.]$', '', st) # ^는 ~로 시작하는, $는 ~로 끝나는. 이 정규식 문법을 생각을 못했다. 문제 의도는 이거였던것 같다 st = 'a' if len(st) == 0 else st[:15] # 5~6단계를 합친 조건. 멋있다 st = re.sub('^[.]|[.]$', '', st) # 이 때는 첫 시작은 고려하지 않아도 된다. 그냥 복붙한 것으로 추정. st = st if len(st) > 2 else st + "".join([st[-1] for i in range(3-len(st))]) return st ''' ================================================ FILE: programmers/난이도별/level01.실패율/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42889 실패율 [풀이] 0. 스테이지에 도달했으나 아직 클리어하지 못한 플레이어의 수 / 스테이지에 도달한 플레이어 수 1. 실패율을 오름차순과 내림차순이 섞여있는 기준으로 정렬 하기. 2. key = (x[0], -x[1])을 사용하면 섞여있는 정렬 가능. ''' def solution(N, stages): failure = [stages.count(i) for i in range(1, N+2)] play = [sum(failure[i:]) for i in range(N)] rate = [(i, v[0]/v[1]) if v[1] != 0 else (i, v[0] and 1) for i, v in enumerate([a, b] for a, b in zip(failure, play))] return list(map(lambda x : x[0]+1, sorted(rate, key=lambda x: (x[1], -x[0]), reverse=True))) ''' ''' ================================================ FILE: programmers/난이도별/level01.아픈_동물_찾기/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT ANIMAL_ID, NAME FROM ANIMAL_INS WHERE INTAKE_CONDITION = 'Sick' ORDER BY ANIMAL_ID ================================================ FILE: programmers/난이도별/level01.약수의_개수와_덧셈/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/77884 문제 : 약수의 개수와 덧셈 약수의 개수가 홀수일때는 제곱근이 정수일때이기 때문에 이를 판별하여 홀, 짝을 구해줬습니다. ''' import math def solution(left, right): answer = 0 for i in range(left, right+1) : num = math.sqrt(i) if int(num) == num : answer -= i else : answer += i return answer ================================================ FILE: programmers/난이도별/level01.약수의_개수와_덧셈/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/77884 약수의 개수와 덧셈 [풀이] ''' def solution(left, right): return sum([-num if num ** 0.5 == int(num ** 0.5) else num for num in range(left, right+1)]) ''' ''' ================================================ FILE: programmers/난이도별/level01.약수의_합/6047198844.py ================================================ def solution(n): return sum([i for i in range(1,n+1) if n % i == 0]) ================================================ FILE: programmers/난이도별/level01.약수의_합/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12928 문제 : 약수의 합 나머지를 사용하여 약수를 구하고 합을 반환하였습니다. 다른 사람 코드에서 이를 한 줄로 표현하는 방법이 있어 메모합니다 [메모메모] sum([i for i in range(1,n+1) if n%i==0]) ''' def solution(n): answer = 0 for i in range(1,n+1) : if n%i == 0 : answer += i return answer ================================================ FILE: programmers/난이도별/level01.약수의_합/HyeonJeong.py ================================================ #처음 코드 ''' def solution(n): total = 0 for i in range(1, n+1): if (n % i == 0): total += i return total ''' #더 효율적인 코드 def solution(n): total = 0 for i in range(1, n // 2 + 1): if n % i == 0: total += i return total + n #테스트로 출력하기 위한 코드 print(solution(12)) ================================================ FILE: programmers/난이도별/level01.약수의_합/Jaewon0702.py ================================================ def solution(n): return sum([n] + [i for i in range(1, n // 2 + 1) if n % i == 0]) print(solution(12) == 28) print(solution(5) == 6) ================================================ FILE: programmers/난이도별/level01.약수의_합/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12928 ================================================ FILE: programmers/난이도별/level01.약수의_합/develop-sell.js ================================================ function solution(n) { if (n < 2) return n; let answer = 0; let arr = []; let limit = Math.sqrt(n); for(let i = 1; i <= limit ; i ++){ if (n % i === 0){ if (n / i === i) { arr.push(i); } else{ arr.push(n / i) arr.push(i); } } } answer = arr.reduce((sum, num) => sum + num, 0); return answer; } // 문제풀이: // 약수를 구해서 배열에 넣고 해당 배열의 합을 구하는 식으로 구현했다. // 지난번 풀었던 문제 중 약수를 구할 때 Math.sqrt()까지 진행해도 약수를 구할 수 있음을 알고 // 이 문제에 적용시켰다. // 알게된 점: // 배열을 굳이 만들 필요 없이 바로 sum이라는 integer형 변수에 더하면 더 효율적이었을 것 같다. // reduce 함수를 통해 배열의 합을 구할 수 있다. // arr.reduce((sum, num) => sum + num, 0); => num은 배열 요소, sum은 최종 합 ================================================ FILE: programmers/난이도별/level01.약수의_합/dkdlelk99.py ================================================ def solution(n): d = [] answer = 0 for i in range(1, n + 1): if n % i == 0: d.append(i) print(d) for i in d: answer += i return answer print(solution(12) == 28) print(solution(6) == 12) ================================================ FILE: programmers/난이도별/level01.약수의_합/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12928 * 정수 n을 입력받아 n의 약수를 모두 더한 값을 리턴하는 함수 * 제한 사항 | n은 0 이상 3000이하인 정수입니다. * @param n */ function solution(n) { if (n < 2) return n; let ans = 0; const max = Math.sqrt(n); // n 의 최대 Math.sqrt(n); 으로 나눈다. for (let i = 2 ; i <= max ; i++) { // 약수가 아닌 경우 if ((n % i) !== 0) continue; // q 는 몫 const q = n / i; // 나누는 수와 몫이 같을 때 ? 9 의 3 * 3 일 때 if (i === q) { ans += i; break; } ans = ans + i + q; } return 1 + n + ans; } /* 테스트 1 〉 통과 (0.06ms, 30MB) 테스트 2 〉 통과 (0.07ms, 30.3MB) 테스트 3 〉 통과 (0.07ms, 30.3MB) 테스트 4 〉 통과 (0.07ms, 30.2MB) 테스트 5 〉 통과 (0.07ms, 30.1MB) 테스트 6 〉 통과 (0.07ms, 29.9MB) 테스트 7 〉 통과 (0.08ms, 29.8MB) 테스트 8 〉 통과 (0.07ms, 30.1MB) 테스트 9 〉 통과 (0.07ms, 30.2MB) 테스트 10 〉 통과 (0.07ms, 30.1MB) 테스트 11 〉 통과 (0.08ms, 30.2MB) 테스트 12 〉 통과 (0.05ms, 30MB) 테스트 13 〉 통과 (0.07ms, 30.3MB) 테스트 14 〉 통과 (0.07ms, 30.3MB) 테스트 15 〉 통과 (0.07ms, 30.1MB) 테스트 16 〉 통과 (0.06ms, 30MB) 테스트 17 〉 통과 (0.07ms, 30.2MB) */ console.log( solution(0) === 0, solution(1) === 1, solution(2) === 3, solution(12) === 28, solution(5) === 6, solution(9) === 13, ); // 옛날에 푼 것 function solution2(n) { var answer = n; let i = 2; if (n > 1) { answer += 1; for (; i < n ; i++) { n % i === 0 ? answer += i : ''; } } return answer; } /* 통과 (1.67ms, 37.3MB) 테스트 2 〉 통과 (1.68ms, 37.2MB) 테스트 3 〉 통과 (1.66ms, 37.4MB) 테스트 4 〉 통과 (1.70ms, 37.3MB) 테스트 5 〉 통과 (1.70ms, 37.6MB) 테스트 6 〉 통과 (1.66ms, 37.2MB) 테스트 7 〉 통과 (1.71ms, 37.2MB) 테스트 8 〉 통과 (1.68ms, 37.3MB) 테스트 9 〉 통과 (1.69ms, 37.3MB) 테스트 10 〉 통과 (1.72ms, 37.4MB) 테스트 11 〉 통과 (1.69ms, 37.5MB) 테스트 12 〉 통과 (1.73ms, 37.3MB) 테스트 13 〉 통과 (1.63ms, 37.2MB) 테스트 14 〉 통과 (1.66ms, 37.4MB) 테스트 15 〉 통과 (1.70ms, 37.6MB) 테스트 16 〉 통과 (1.63ms, 37.2MB) 테스트 17 〉 통과 (1.74ms, 37.3MB) */ ================================================ FILE: programmers/난이도별/level01.약수의_합/khw970421.js ================================================ function solution(n) { let sum=0; for(let i=1;i<=n;i++) { if(n%i==0) //나누어 떨어지면(약수이면) sum+=i //약수이므로 더해준다. } return sum; } function solution(n) { let sum=0; return [ ...Array(n).keys() ] .map(i => i + 1) .filter(i => n % i == 0) .reduce((sum, i) => sum + i); } /* Array(n)은 n개의 배열을 생성 Array(n).keys()는 배열의 key값에 대한 iterator(반복을 위해 설계된, 특별한 인터페이스를 가진 객체)를 만든다. [ ...Array(n).keys() ] : n개의 배열의 키값에 대한 배열을 만든다. 즉 [...Array(5).keys()] 는 [0,1,2,3,4]가 된다. 그리고 이러한 iterator와 관련된 for문으로 for of가 있다. (for...of 명령문은 반복가능한 객체 (Array, Map, Set, String, TypedArray, arguments 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대해 실행되는 문이 있는 사용자 정의 반복 후크를 호출하는 루프를 생성합니다.) 그러한 for of를 담당하는 것이 있는데 Map객체 입니다. Map 객체는 요소의 삽입 순서대로 원소를 순회합니다. for...of 반복문은 각 순회에서 [key, value]로 이루어진 배열을 반환합니다. 결과적으로 [...Array(n).keys()]는 0부터 n까지의 배열을 생성 .map(i=>i+1)을 통해 그다음으로 return하는것은 1부터 n까지로 알 수 있고 .filter(i=>n%i==0)을 통해 n이라는 값으로 map에서 return 한 값들이 나누어지면 true이므로 .reduce로 가고 false이면 .reduce로 가지않는다. 마지막으로 .reduce에서는 나누어떨어지는 값들이 온 것을 첫번째인자인 누산기 sum에다가 더해주는것을 반복하고 전부 끝나면 return한다. */ ================================================ FILE: programmers/난이도별/level01.약수의_합/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12928 약수의 합 [풀이] 1. 제곱근 까지 약수를 구하기. 대칭값까지 더하기. 성능 중심 ''' def solution(n): answer = [i for i in range(1, int(n**0.5)+1) if n % i == 0] return sum(set(answer + [n // i for i in answer])) ''' ''' ================================================ FILE: programmers/난이도별/level01.약수의_합/sjjyy.java ================================================ package 난이도별.level01.약수의_합; public class sjjyy { public static int solution(int n) { int sum = 0; for (int i = 1 ; i <= n ; i++) { if (n % i == 0) sum += i; } return sum; } public static void main(String[] args) { System.out.println(solution(12)); // 28 System.out.println(solution(5)); // 6 } } ================================================ FILE: programmers/난이도별/level01.어린_동물_찾기/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT ANIMAL_ID, NAME FROM ANIMAL_INS WHERE INTAKE_CONDITION != 'Aged' ORDER BY 1 ================================================ FILE: programmers/난이도별/level01.없는 숫자 더하기/6047198844.py ================================================ def solution(numbers): return sum(set(range(0, 10)) - set(numbers)) ================================================ FILE: programmers/난이도별/level01.여러_기준으로_정렬하기/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT ANIMAL_ID, NAME, DATETIME FROM ANIMAL_INS ORDER BY 2 ASC, 3 DESC ================================================ FILE: programmers/난이도별/level01.역순_정렬하기/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT NAME, DATETIME FROM ANIMAL_INS ORDER BY ANIMAL_ID DESC ================================================ FILE: programmers/난이도별/level01.예산/6047198844.py ================================================ def solution(costs, budget): answer = 0 costs.sort() for cost in costs: if cost <= budget: budget -= cost answer += 1 return answer ================================================ FILE: programmers/난이도별/level01.예산/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12982 문제 : 예산 오름차순으로 정렬하여 작은 수부터 더해 예산을 넘는지 확인해주었습니다. ''' def solution(d, budget): answer = 0 n = 0 if sum(d) <= budget : return len(d) for i in sorted(d) : if n+i <= budget : n += i answer += 1 return answer ================================================ FILE: programmers/난이도별/level01.예산/HyeonJeong.py ================================================ def solution(d, budget): tries = 0 for n in sorted(d): if budget < n: break #break는 for문에서 빠져나오게 함. budget -= n tries += 1 return tries print( solution([1,3,2,5,4], 9) == 3, solution([2,2,3,3], 10) == 4 ) ================================================ FILE: programmers/난이도별/level01.예산/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12982 Summer/Winter Coding(~2018) ================================================ FILE: programmers/난이도별/level01.예산/develop-sell.js ================================================ function solution(d, budget) { let answer = 0; let sort_arr = d.sort((a, b) => (a-b)) let len = sort_arr.length let total_cost = 0; for(let i = 0; i < len; i++){ if (total_cost + d[i] > budget) break; else{ total_cost += d[i] answer++ } } console.log(d) console.log(sort_arr) return answer; } // 문제풀이: // 문제 조건 1) 최대한 많은 부서에게 물품을 구매할수록 있도록 한다 // 문제 조건 2) 각 부서마다 비용이 다르다 // 문제 조건 3) 한 부서에게 지불해줄 시 신청한 금액 전체를 다 지원해줘야 한다. // (ex. 신청 금액이 5원인데, 4원만 지원 불가능) // 가장 작은 비용의 부서부터 지원해줘야 최대한 많은 부서들에게 지원해주는 것이다. // 그래서 비용이 작은 순으로 부서별 비용 배열을 sort 시켰다. // 그 다음 for문을 돌면서 총 비용(total_cost)가 budget를 넘기 전까지 // 부서들을 지원해주면 된다. // (부서 지원해주면 total_cost가 그 만큼 늘어나고(total_cost +=d[i]), 지원해준 부서 숫자(answer)도 늘어남) // 궁금한 점: // 원래는 reduce 함수를 써서, // total 값이 budget을 넘지 않기 전까지의 answer 값을 구하려고 했는데, // 아직 개념이 헷갈려서 그런지 쉽지 않았다. // 그런데 생각해보니, reduce는 중간에 break 기능이 없어 배열은 엄청 긴데 비용이 높아 이제부턴 못 지원해주는 경우에 // 모든 요소를 다 돌아야하니 덜 효율적이라고 생각했다. (for문은 break문으로 빠져나오기 때문) // 그래도 reduce로 짜는 방법을 알고 싶은데, // 아래 코드까진 짜보았는데, 뭔가 문제가 있어 보입니다. // sort_arr.reduce((total, current) => ((total + current <= budget) ? (answer ++ , total+= current) : answer ), 0) // return answer // budget보다 작으면 돌면서 total 값에 current 값을 더하고, anwser++ 하는 건데, // 초기값은 0으로 지정해줬습니다. 무엇이 문제일까요? // 입력1: [1,2,3,4,5] , 9 / 정답1: 3 / 위 reduce 함수에서: 4 // 입력2: [2,2,3,4] , 10 / 정답2: 4 / 위 reduce 함수에서: 4 // 알게 된 점: // 위에 식에서 14,15줄을 보면 내가 sort한 arr를 sort_arr로 두게 되었는데, // 실수로 for문 안에서는 d 배열로 돌리게 되어 틀릴 줄 알았는데, 맞았다. // 즉, sort() 함수는 하는 순간 바로 그 배열 자체에서 sort가 적용된다. // ex. let arr1 = arr2.sort() ===> 이때 arr1, arr2의 값이 동일해진다. ================================================ FILE: programmers/난이도별/level01.예산/dkdlelk99.py ================================================ def solution(d, budget): answer = 0 d.sort() for i in d: budget -= i answer += 1 if budget < 0: answer -= 1 break return answer print(solution([2,3,1,5,4],9) == 3) print(solution([2,3,2,3],10) == 4) ================================================ FILE: programmers/난이도별/level01.예산/rockmiin_예산.py ================================================ def solution(d, budget): d.sort() for i in range(len(d)): print(sum(d[:i+1])) if budget < sum(d[:i+1]): return i return len(d) print( solution([2, 2, 3, 3], 10), # solution([1, 3, 2, 5, 4], 9) ) ================================================ FILE: programmers/난이도별/level01.예산/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12982 예산 : 최적의 해 찾기 문제 부서를 정렬 후, 앞 부서가 할당받지 못하면 뒷 부서 역시 할당받지 못한다고 간주. ''' def solution(d, budget): for i, v in enumerate(sorted(d)): if budget < v: return i budget -= v return len(d) ''' ''' ================================================ FILE: programmers/난이도별/level01.예산/sjjyy.java ================================================ package 난이도별.level01.예산; import java.util.Arrays; public class sjjyy { public static int solution(int[] d, int budget) { int answer = 0; int a = 0; int len = d.length; Arrays.sort(d); for (int i = 0; i < len; i++) { a += d[i]; if (a > budget) // 신청 금액이 예산보다 커짐 { answer = i; // 커지기 직전 개수 return answer; } } if (a <= budget) // 예산이 남거나 딱 맞음 answer = len; return answer; } public static int solution2(int[] d, int budget) { int answer = 0; Arrays.sort(d); for (int i : d) { budget -= i; if (budget < 0) break; answer++; } return answer; } public static void main(String[] args) { int[] d1 = {1,3,2,5,4}; int[] d2 = {2,2,3,3}; System.out.println(solution(d1, 9)); // 3 System.out.println(solution(d2, 10)); // 4 System.out.println(solution2(d1, 9)); // 3 System.out.println(solution2(d2, 10)); // 4 } } ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/6047198844.cpp ================================================ #include #include #include using namespace std; string solution(vector participant, vector completion) { map mp; for (auto completion_person : completion) mp[completion_person]++; for (auto participant_person : participant) mp[participant_person]--; for (auto answer_check : mp) if (answer_check.second) return answer_check.first; } ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/HyeonJeong.py ================================================ def solution(participant, completion): participant.sort() completion.sort() for i in range(len(completion)): if participant[i] != completion[i]: return participant[i] return participant[-1] print( solution(["leo", "kiki", "eden"], ["eden", "kiki"]) == "leo", solution(["marina", "josipa", "nikola", "vinko", "filipa"], ["josipa", "filipa", "marina", "nikola"]) == "vinko", solution(["mislav", "stanko", "mislav", "ana"], ["stanko", "ana", "mislav"]) == "mislav" ) ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/Jaewon0702.py ================================================ def solution(participant, completion): answer='' participant.sort() completion.sort() completion.append('') for i in range(len(completion)) : if participant[i]!=completion[i] : answer=participant[i] break return answer ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/JeongShin.js ================================================ function solution(participant, completion) { const obj = {} completion.forEach((el)=> { obj[el]=(obj[el]||0) + 1; }) for (const p of participant) { if ((obj[p]||0)< 1) return p obj[p]-- } } ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42576 ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/develop-sell.js ================================================ function solution(participant, completion) { let answer = ''; participant.sort(); completion.sort(); const len = participant.length for(let j = 0; j < len; j ++){ for(let i = 0; i < completion.length; i++){ if (participant[j] === completion[i]){ completion.splice(i, 1) participant.splice(j, 1) j--; break; } } } //participant.map((word, index) => word + index); //console.log(participant.filter((word) => completion.indexOf(word) < 0)); return participant[0]; } //처음 해법 => 효율성에서 문제 function solution(participant, completion) { let answer = ''; participant.sort(); completion.sort(); const len = participant.length; let i = 0; while(i < len) { if (participant[i] !== completion[i]) return participant[i]; i++; } } // 문제 풀이: // 효율성 문제 때문에 최대한 이중 for문을 안 사용하려고 고민을 많이 했다. // 그러나 해결하기 어려워서, 우선 sort함수로 순서를 맞춰주면 비교적 // 괜찮을 것 같아보였다. // 그래도 해결이 안되어서 length 함수를 계속 호출하지 않도록 밖으로 뺐다. // 그래도 해결이 안되어서 고민하다 // eyabc.js 님의 풀이를 참고했다. // sort를 하면 순서대로 짜지기 때문에 달라지는 순번의 요소가 정답이었다. // participant와 completion의 길이 차이가 -1이기 때문. // 배운 점: // for문을 줄이는 연습을 더 해보자..! ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/dkdlelk99.py ================================================ def solution(participant, completion): participant.sort() completion.sort() answer = '' for i in range(len(completion)): if participant[i] != completion[i]: answer = participant[i] return answer return participant[-1] print( solution(['leo', 'kiki', 'eden'], ['eden', 'kiki'] ) == 'leo', solution(['marina', 'josipa', 'nikola', 'vinko', 'filipa'], ['josipa', 'filipa', 'marina', 'nikola'] ) == 'vinko', solution(['mislav', 'stanko', 'mislav', 'ana'], ['stanko', 'ana', 'mislav']) == 'mislav' ) ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/eyabc.js ================================================ function solution (participant, completion) { participant.sort(); completion.sort(); const participant_len = participant.length; let i = 0; while(i < participant_len) { if (participant[i] !== completion[i]) return participant[i]; i++; } } const JSTestModule = require('/Users/ey/DKU/Algorithm/JSTestModule.js'); JSTestModule('/Users/ey/DKU/Algorithm/programmers/난이도별/level01.완주하지_못한_선수/test.json', solution); ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/junilhwang.py ================================================ def solution(participant, completion): vector = {} for v in participant : vector[v] = vector.get(v, 0) + 1 for v in completion : vector[v] -= 1 if vector[v] == 0 : del vector[v] for k, v in vector.items() : return k print( solution(['leo', 'kiki', 'eden'], ['eden', 'kiki'] ) == 'leo', solution(['marina', 'josipa', 'nikola', 'vinko', 'filipa'], ['josipa', 'filipa', 'marina', 'nikola'] ) == 'vinko', solution(['mislav', 'stanko', 'mislav', 'ana'], ['stanko', 'ana', 'mislav']) == 'mislav' ) ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/khw970421.js ================================================ function solution(participant, completion) { let p; completion.forEach(function k(e){ participant.splice(participant.indexOf(e),1); // participant중에 completion이랑 포함되는애 제거 }) return participant.join(); //그중 남은거 return } console.log( solution(['leo', 'kiki', 'eden'], ['eden', 'kiki'] ) == 'leo', solution(['marina', 'josipa', 'nikola', 'vinko', 'filipa'], ['josipa', 'filipa', 'marina', 'nikola'] ) == 'vinko', solution(['mislav', 'stanko', 'mislav', 'ana'], ['stanko', 'ana', 'mislav']) == 'mislav' ) // 효율성 문제 발생 function solution(participant, completion) { const participant_length=participant.length; participant.sort(); completion.sort(); for(let i=0;i map = new HashMap<>(); for (String name : completion) { map.put(name, map.getOrDefault(name, 0) + 1); // getOrDefault() : 찾는 키가 존재하면 해당 키의 값을 반환하고 없으면 기본값을 반환 } for (String name : participant) { map.put(name, map.getOrDefault(name, 0) - 1); if (map.get(name) < 0) return name; } return ""; } public static void main(String[] args) { String[] p1 = {"leo", "kiki", "eden"}; String[] c1 = {"kiki", "eden"}; String[] p2 = {"marina", "josipa", "nikola", "vinko", "filipa"}; String[] c2 = {"marina", "josipa", "nikola", "filipa"}; String[] p3 = {"mislav", "stanko", "mislav", "ana"}; String[] c3 = {"stanko", "mislav", "ana"}; System.out.println(solution(p1,c1)); // leo System.out.println(solution(p2,c2)); // vinko System.out.println(solution(p3,c3)); // mislav System.out.println(solution2(p1,c1)); // leo System.out.println(solution2(p2,c2)); // vinko System.out.println(solution2(p3,c3)); // mislav } } ================================================ FILE: programmers/난이도별/level01.완주하지_못한_선수/test.json ================================================ [ { "input": [["leo", "kiki", "eden"], ["eden", "kiki"]], "output": "leo" }, { "input": [["marina", "josipa", "nikola", "vinko", "filipa"],["josipa", "filipa", "marina", "nikola"]], "output": "vinko" }, { "input": [["mislav", "stanko", "mislav", "ana"], ["stanko", "ana", "mislav"]], "output": "mislav" } ] ================================================ FILE: programmers/난이도별/level01.음양_더하기/6047198844.py ================================================ def solution(absolutes, signs): return sum([absolute if sign else -absolute for absolute, sign in zip(absolutes, signs)]) ================================================ FILE: programmers/난이도별/level01.음양_더하기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/76501 문제 : 음양 더하기 예전에 상민오빠 코드 리뷰할 때 알게된 zip을 활용해보네요 덕분에 두개의 배열을 바로 연산하기 편하더라구요!!! ''' def solution(absolutes, signs): answer = 0 for absolute, sign in zip(absolutes, signs) : if not sign : absolute *= -1 answer += absolute return answer ================================================ FILE: programmers/난이도별/level01.음양_더하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/76501 음양 더하기 [풀이] ''' def solution(absolutes, signs): return sum([num*(2*int(sign)-1) for num, sign in zip(absolutes, signs)]) ''' ''' ================================================ FILE: programmers/난이도별/level01.이름이_있는_동물의_아이디/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT ANIMAL_ID FROM ANIMAL_INS WHERE NAME IS NOT NULL ORDER BY ANIMAL_ID ASC ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/6047198844.py ================================================ def solution(s): answer = '' idx = 0 for char in s: if char == ' ': idx = 0 answer += char continue if idx % 2 == 0: answer += str.upper(char) else: answer += str.lower(char) idx += 1 return answer # 공백이 여러개라면? ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12930 문제 : 이상한 문자 만들기 원래 s.split(" ")을 이용하여 공백을 기준으로 나눈 후, 아래와 같은 방법으로 대소문자를 구분하여 (" ").join을 사용하여 합쳐주었는데 계속 오류가 발생했습니다. 질문을 보니 공백 갯수만큼 공백을 유지해 줘야 한다 해서 아래와 같이 split으로 나누지 않고 if를 통해 공백일 경우, 아닐 경우를 판별하여 추가해주게 되었습니다. ''' def solution(s): answer = '' num = 0 for i in range(len(s)) : if s[i] == ' ' : answer += ' ' num = 0 else : if num%2 == 0 : answer += s[i].upper() num += 1 else : answer += s[i].lower() num += 1 return answer ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/HyeonJeong.py ================================================ #코드1 def solution(s): answer = "" words = s.split(" ") for i in range(len(words)): for j in range(len(words[i])): c = words[i][j] if "a" <= c <= "z" and j % 2 == 0: answer += c.upper() elif "A" <= c <= "Z" and j % 2 == 1: answer += c.lower() else: answer += c if i < len(words) - 1: answer += " " return answer #코드2 def solution(s): answer = [] words = s.lower().split(" ") for word in words: newWord = "" for i, c in enumerate(word): newWord += c.upper() if i % 2 == 0 else c answer.append(newWord) return " ".join(answer) print(solution("try hello world") == "TrY HeLlO WoRlD") ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/Jaewon0702.py ================================================ def solution(s): return " ".join([ "".join([ st.lower() if i % 2 else st.upper() for i, st in enumerate(n) ]) for n in s.split(" ")]) print(solution("try Hello world") == "TrY HeLlO WoRlD") print(solution("Hello eVeryone") == "HeLlO EvErYoNe") ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12930 * 문제 설명: 문자열 s는 한 개 이상의 단어로 구성되어 있습니다. 각 단어는 하나 이상의 공백문자로 구분되어 있습니다. 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을 리턴하는 함수, solution을 완성하세요. * 제한 사항 * 문자열 전체의 짝/홀수 인덱스가 아니라, 단어(공백을 기준)별로 짝/홀수 인덱스를 판단해야합니다. * 첫 번째 글자는 0번째 인덱스로 보아 짝수번째 알파벳으로 처리해야 합니다. * 입출력 예 s => "try hello world" return => "TrY HeLlO WoRlD" * 입출력 예 설명 "try hello world"는 세 단어 "try", "hello", "world"로 구성되어 있습니다. 각 단어의 짝수번째 문자를 대문자로, 홀수번째 문자를 소문자로 바꾸면 "TrY", "HeLlO", "WoRlD"입니다. 따라서 "TrY HeLlO WoRlD" 를 리턴합니다. ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/develop-sell.js ================================================ function solution(s) { let arr = s.split(" "); arr = arr.map((str)=> { str = str.split("") str = str.map((char, index) => { return index % 2 === 0 || index === 0 ? char.toUpperCase() : char.toLowerCase() }) str = str.join('') return str; }) return arr.join(' '); } // 변수 설명: // arr : 단어별 Array // str : 단어, string 값. (ex. try) // char : 단어의 한 글자 (ex. try의 t) // index : 단어마다 나타나는 index값 (단어마다 새로고침된다) // 문제풀이: // 배열을 공백 기준으로 나누고, map함수를 통해 각각 단어별로 접근하게 한다. // 다시 split함수로 단어를 char별로 나누고, 이를 map함수를 통해 // index가 짝수(0 포함)면 대문자, 아니면 소문자로 변환해서 return한다. // 그렇게 변환된 str를 다시 join하면 단어별 배열이 되고, // 다시 join를 ' ' 빈칸 기준으로 하면 해당 string 값이 나온다 // 어려웠던 점: // 1.처음에 단어(공백을 기준)이 무슨 말인지 잘 이해가 안 갔다..! // 2.원래는 map함수 안에서는 forEach문으로 돌려서 받으려고 했는데, // 잘못된 판단이었다. // 이 문제에서 요구한 건 배열 안의 값을 변경한 배열을 가져오는 것인데, // 이때는 무조건 map함수를 쓴다. // forEach는 배열의 요소에 접근하는 용도로만 사용할 때 쓴다. 즉 배열의 요소를 바꿀 때는 아니다. // (접근해서 해당 값들을 다른 식에 적용해야할 때 사용) // 잘 확인해둘 것! // 반드시 가져가야할 점: // map, join, split 함수를 사용할 때, 함수가 적용된 객체를 다시 받는 변수를 둬야한다. // (이것 때문에 시간 낭비를 많이 했다) // ex. str.split("") 그냥 이렇게만 하면 배열로 쪼개지지만, str이 그렇게 변경되는 것이 아니다. // 즉 str = str.split("") 이런식으로 받아주는 객체가 필요하다. // 아님 바로 return 문에 쓰던가.. // 앞으로 console 찍을 때도 반드시 console.log(str) 이렇게 말고, console.log(str.split("")) 이걸로 보자 // 헷갈리지 말자! function solution(s) { let arr = s.split(" "); arr = arr.map((str)=> { let even = false; str = Array.from(str, char => { even = !even; return even ? char.toUpperCase() : char.toLowerCase(); }).join('') return str; }) return arr.join(' '); } // 위 식의 eyabc.js님의 코드를 보고 수정해본 코드이다. ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/dkdlelk99.py ================================================ def solution(s): answer = '' count = 0 for i in range(len(s)): if s[i] == ' ': answer += ' ' count = 0 else: count += 1 answer += s[i].upper() if count % 2 == 0 else s[i].lower() return answer print(solution('Try hard') == 'TrY HaRd') print(solution('This is difficult') == 'ThIs Is DiFfIcUlT') ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12930 제한 사항 - 단어(공백을 기준)별로 짝/홀수 인덱스를 판단해야합니다. - 첫번째글자인 0번째 인덱스는 짝수번째 알파벳으로 처리 * @param s 한개 이상의 단어로 구성된 문자열. 단어는 공백 문자로 구분 됨 * @return 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을 리턴하는 함수 */ function solution1(s) { return s.split(' ') .map((string) => { let even = false; return Array.from(string, (char) => { even = !even; return even ? char.toUpperCase() : char.toLowerCase(); }).join(''); }).join(' '); } /* solution2 와 다른점은 짝수인지 홀수인지 나머지 계산을 하지 않고 짝수홀수 플래그를 두었다는 것임. 큰 차이는 없음 테스트 1 〉 통과 (0.13ms, 30MB) 테스트 2 〉 통과 (0.12ms, 30.2MB) 테스트 3 〉 통과 (0.13ms, 30.3MB) 테스트 4 〉 통과 (0.21ms, 30.1MB) 테스트 5 〉 통과 (0.15ms, 30.2MB) 테스트 6 〉 통과 (0.11ms, 30.1MB) 테스트 7 〉 통과 (0.12ms, 30.2MB) 테스트 8 〉 통과 (0.21ms, 30MB) 테스트 9 〉 통과 (0.17ms, 30MB) 테스트 10 〉 통과 (0.22ms, 30.2MB) 테스트 11 〉 통과 (0.20ms, 30MB) 테스트 12 〉 통과 (0.20ms, 30.1MB) 테스트 13 〉 통과 (0.18ms, 30.2MB) 테스트 14 〉 통과 (0.08ms, 30.1MB) 테스트 15 〉 통과 (0.17ms, 30MB) 테스트 16 〉 통과 (0.17ms, 29.9MB) */ console.log(solution('try hello world') === 'TrY HeLlO WoRlD'); function solution2(s) { return s.split(' ').map(v => Array.from(v.toUpperCase()).map((c, k) => k % 2 ? c.toLowerCase() : c).join('')).join(' '); } /* 테스트 1 〉 통과 (0.12ms, 30.3MB) 테스트 2 〉 통과 (0.09ms, 30.2MB) 테스트 3 〉 통과 (0.10ms, 30.2MB) 테스트 4 〉 통과 (0.17ms, 29.8MB) 테스트 5 〉 통과 (0.14ms, 30.2MB) 테스트 6 〉 통과 (0.10ms, 30MB) 테스트 7 〉 통과 (0.10ms, 29.9MB) 테스트 8 〉 통과 (0.17ms, 29.7MB) 테스트 9 〉 통과 (0.14ms, 29.9MB) 테스트 10 〉 통과 (0.20ms, 30MB) 테스트 11 〉 통과 (0.18ms, 30.4MB) 테스트 12 〉 통과 (0.16ms, 30.1MB) 테스트 13 〉 통과 (0.11ms, 30.1MB) 테스트 14 〉 통과 (0.10ms, 30.3MB) 테스트 15 〉 통과 (0.11ms, 30MB) 테스트 16 〉 통과 (0.14ms, 30MB) */ function solution3(s) { let even = false; return Array.from(s, (char) => { if (char === ' ') { even = false; return char; } even = !even; return even ? char.toUpperCase() : char.toLowerCase(); }).join(''); } /* 세번째 방법은 split 나 join 을 한단계 줄였다. 큰 차이는 없음 테스트 1 〉 통과 (0.11ms, 30.2MB) 테스트 2 〉 통과 (0.08ms, 30.2MB) 테스트 3 〉 통과 (0.09ms, 30.1MB) 테스트 4 〉 통과 (0.15ms, 30.1MB) 테스트 5 〉 통과 (0.13ms, 30.3MB) 테스트 6 〉 통과 (0.08ms, 30.2MB) 테스트 7 〉 통과 (0.09ms, 30MB) 테스트 8 〉 통과 (0.15ms, 30.1MB) 테스트 9 〉 통과 (0.12ms, 30.1MB) 테스트 10 〉 통과 (0.17ms, 30.2MB) 테스트 11 〉 통과 (0.15ms, 30.2MB) 테스트 12 〉 통과 (0.14ms, 30.1MB) 테스트 13 〉 통과 (0.14ms, 30.1MB) 테스트 14 〉 통과 (0.10ms, 30.3MB) 테스트 15 〉 통과 (0.11ms, 30.1MB) 테스트 16 〉 통과 (0.14ms, 30MB) */ function solution5(s) { let even = false; let newStr = ''; Array.prototype.forEach.call(s, (char) => { if (char === ' ') { even = false; newStr += ' '; return char; } even = !even; newStr += even ? char.toUpperCase() : char.toLowerCase(); }); return newStr; } function solution4(s) { let even = false; let newStr = ''; Array.prototype.forEach.call(s, (char) => { if (char === ' ') { even = false; newStr += ' '; return char; } newStr += (even = !even) ? char.toUpperCase() : char.toLowerCase(); }); return newStr; } /* 새 문자열을 만드는 방법 테스트 1 〉 통과 (0.11ms, 30.1MB) 테스트 2 〉 통과 (0.09ms, 30.2MB) 테스트 3 〉 통과 (0.09ms, 30.1MB) 테스트 4 〉 통과 (0.15ms, 30MB) 테스트 5 〉 통과 (0.10ms, 30.1MB) 테스트 6 〉 통과 (0.09ms, 30.4MB) 테스트 7 〉 통과 (0.10ms, 30.1MB) 테스트 8 〉 통과 (0.15ms, 30.2MB) 테스트 9 〉 통과 (0.11ms, 30.2MB) 테스트 10 〉 통과 (0.15ms, 30.1MB) 테스트 11 〉 통과 (0.14ms, 30.2MB) 테스트 12 〉 통과 (0.10ms, 29.9MB) 테스트 13 〉 통과 (0.13ms, 30.3MB) 테스트 14 〉 통과 (0.11ms, 29.9MB) 테스트 15 〉 통과 (0.12ms, 30.1MB) 테스트 16 〉 통과 (0.14ms, 30.1MB) */ ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/khw970421.js ================================================ function solution(s) { let h =s.split(' '); //공백에따라 분리하기 const p=[]; const q = []; const h_length=h.length; for(let i=0;ie.split('').map((q,k)=>(k%2==1)?q.toLowerCase():q).join('')).join(' ') } //map을 마치 for문으로 생각하면 map안에 map이 있으므로 이중 for문에 대해 안에서 처리하고 join 후 밖의 map에서 다시 배열을 join ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/pul8219.java ================================================ package programmers.난이도별.level01.이상한_문자_만들기; /* * 힌트 참고함 * split()함수 사용은 생각해냈으나 공백을 기준으로 문자를 자를 생각만 했지 빈 문자열로 각 문자마다 자를 생각은 못했음 * 공백을 만날시 cnt 변수를 0으로 초기화 함으로써 새로운 단어 시작을 알아차리는 방법 활용 * */ import java.util.Arrays; class Solution{ public String solution(String s){ String answer = ""; int cnt = 0; String[] word = s.split(""); // 문자마다 잘라짐 for(String ss : word){ cnt = (ss.contains(" ")) ? 0 : cnt + 1; // contains(): 대상 문자열에 특정 문자열이 포함되어 있는지 확인하는 함수. boolean을 반환한다. // 문자가 공백이면 cnt = 0으로 초기화, 공백이 아닐 경우 cnt++ // cnt 짝수이면(단어의 홀수번째라는 뜻) 소문자로, cnt 홀수이면(단어의 짝수번째) 대문자로 변환하여 answer 변수에 붙여나감 answer += (cnt % 2 == 0) ? ss.toLowerCase() : ss.toUpperCase(); } return answer; } // hwangjunil 풀이 // 람다, 스트림 공부 필수 public String solution2(String s){ int[] cnt = { 0 }; return Arrays.stream(s.split("")).reduce("", (answer, ss) -> { cnt[0] = ss.contains(" ") ? 0 : cnt[0] + 1; return answer + (cnt[0] % 2 == 0 ? ss.toLowerCase() : ss.toUpperCase()); }); } } class pul8219{ public static void main(String[] args){ Solution s = new Solution(); String sen = "try hello world"; System.out.println(s.solution(sen)); } } ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/s2uyeoii.cpp ================================================ #include #include #include #include // 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요. char* solution(const char* s) { // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요. char* answer = (char*)malloc(sizeof(char) * strlen(s) + 1); strcpy(answer, s); int cnt = 0; for(int i=0, len=strlen(s); i < len; i++) { if(answer[i] == ' ') { cnt = -1; } if(abs(cnt%2)==0) { answer[i] = toupper(s[i]); } else { answer[i] = tolower(s[i]); } cnt++; } return answer; } ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12930 이상한 문자 만들기 [풀이] 1. split, upper, lower ''' def solution(s): words = s.split(' ') answer = '' for word in words: for i, v in enumerate(word): answer += v.upper() if i % 2 == 0 else v.lower() answer += ' ' return answer[:-1] ''' 마지막에 공백을 추가하는 방법 대신 ' '.join() 을 사용할 수 있음 return ' '.join([''.join([c.upper() if i % 2 == 0 else c.lower() for i, c in enumerate(w)]) for w in s.split()]) ''' ================================================ FILE: programmers/난이도별/level01.이상한_문자_만들기/sjjyy.java ================================================ package 난이도별.level01.이상한_문자_만들기; public class sjjyy { public static String solution(String s) { StringBuilder answer = new StringBuilder(); String[] arr = s.split(""); int index = 0; for (String i : arr) { index = i.equals(" ") ? 0 : ++index; answer.append(index % 2 == 0 ? i.toLowerCase() : i.toUpperCase()); } return answer.toString(); } public static void main(String[] args) { System.out.println(solution("try hello world")); // TrY HeLlO WoRlD System.out.println(solution("sooooo hard")); // SoOoOo HaRd } } ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/6047198844.py ================================================ def solution(n): return sum(map(int,str(n))) ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12931 문제 : 자릿수 더하기 세 문제 연속으로 입력받은 자연수를 쪼개서 사용하는 문제가 나와서 절대 안 잊을 것 같아요 ''' def solution(n): return sum(list(map(int, str(n)))) ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/HyeonJeong.py ================================================ #방법1 ''' def solution(n): answer = 0 for i in range(1, 10): answer += n % 10 n = n // 10 return answer ''' #방법2(한줄) def solution(n): return sum(int(i) for i in str(n)) print( solution(123) == 6, solution(987) == 24 ) ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/Jaewon0702.py ================================================ def solution(n): return sum(map(int, str(n))) print(solution(123)) print(solution(987)) ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12931 ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/develop-sell.js ================================================ const { strict } = require("assert"); //1번째 풀이 function solution(n) { let answer = 0; (n + '').split('').forEach((num)=>{ answer += num * 1 }) return answer; } // 문제풀이: // 문제의 핵심은 형변환이다. // 숫자인 n을 자동형변환으로 string으로 만들고, // 각 char를 다시 자동형변환으로 숫자로 바꿔서 answer에 다 더한다. // string -> array 로 변환 후 forEach문으로 더함 //2번째 풀이 function solution(n) { let answer = 0; n = n + ''; let len = n.length for(let i = 0; i < len; i++){ answer += n[i] * 1 } return answer; } // 문제풀이: // string 그대로 for문을 통해 값을 더함 // 궁금한점: // 과연 저렇게 string에서 for문으로 접근하는 방법이 좋은가? #2번 방법 // 아님 split으로 배열로 char별로 나누고 forEach문으로 접근하는게 좋은가? #1번 방법 // 프로그래머스 풀이 return (n+"").split("").reduce((acc, curr) => acc + parseInt(curr), 0) // reduce 함수의 역할 // forEach : 배열의 요소를 접근하는 기능으로만 사용. 반복문 외부에 값을 조정할 때 유용. (ex. let answer 에 배열의 요소 값을 다 더해줄 때) // map: 리턴값의 배열 길이는 동일하나 배열 각각의 요소를 바꾸고 싶을 때 사용. (조건에 따라 char가 될수도, str이 될수도, 값이 더해질 수도 있는 것) // filter: 리턴값의 배열 길이가 다르다. 해당되는 요소만 filter하는 것. (이때 값을 바꾸면서도 return 가능) // reduce: 배열의 각 요소가 리듀서(reducer) 함수를 실행하고 하나의 값을 반환. 누산기가 존재한다. (함수의 값을 누적하는 기기?) // return array.reduce((acc, curr) => acc + parseInt(curr), 0) // 여기서 acc는 지금까지 누적된 값이고, curr는 현재 배열의 요소이다. 마지막의 0은 초기값을 말함. 초기 acc 값. // ex. ['1','2','3'] // [0] acc: 0 , curr: '1' // [1] acc: 1 , curr: '2' // [2] acc: 3 , curr: '3' // return 값은 6 // 배운점: // *자동형변환 // 숫자에서 문자열 : + '' 하면 된다. ex. 3424 + '' => '3424' 로 변환 // 문자열에서 숫자 : * 1 하면 된다. ex. '3424' * 1 => 3424 로 변환 // #1 풀이의 결과 // 테스트 1 〉 통과 (0.11ms, 30.1MB) // 테스트 2 〉 통과 (0.06ms, 30.2MB) // 테스트 3 〉 통과 (0.07ms, 30.3MB) // 테스트 4 〉 통과 (0.07ms, 30.1MB) // 테스트 5 〉 통과 (0.07ms, 29.7MB) // 테스트 6 〉 통과 (0.06ms, 30.1MB) // 테스트 7 〉 통과 (0.05ms, 30.2MB) // 테스트 8 〉 통과 (0.07ms, 30.1MB) // 테스트 9 〉 통과 (0.07ms, 30MB) // 테스트 10 〉 통과 (0.06ms, 30MB) // 테스트 11 〉 통과 (0.07ms, 30MB) // 테스트 12 〉 통과 (0.07ms, 30.1MB) // 테스트 13 〉 통과 (0.07ms, 30MB) // 테스트 14 〉 통과 (0.07ms, 30MB) // 테스트 15 〉 통과 (0.07ms, 30.2MB) // 테스트 16 〉 통과 (0.07ms, 30.1MB) // 테스트 17 〉 통과 (0.07ms, 30MB) // 테스트 18 〉 통과 (0.09ms, 30MB) // 테스트 19 〉 통과 (0.07ms, 30.1MB) // 테스트 20 〉 통과 (0.05ms, 30.1MB) // 테스트 21 〉 통과 (0.06ms, 30.2MB) // #2 풀이의 결과 // 테스트 1 > 통과 (0.06ms, 30MB) // 테스트 2 〉 통과 (0.06ms, 30.1MB) // 테스트 3 〉 통과 (0.05ms, 30.1MB) // 테스트 4 〉 통과 (0.04ms, 30MB) // 테스트 5 〉 통과 (0.06ms, 30MB) // 테스트 6 〉 통과 (0.06ms, 30.3MB) // 테스트 7 〉 통과 (0.06ms, 30MB) // 테스트 8 〉 통과 (0.04ms, 30.2MB) // 테스트 9 〉 통과 (0.05ms, 30.1MB) // 테스트 10 〉 통과 (0.07ms, 30.3MB) // 테스트 11 〉 통과 (0.06ms, 30.1MB) // 테스트 12 〉 통과 (0.06ms, 30MB) // 테스트 13 〉 통과 (0.06ms, 30.2MB) // 테스트 14 〉 통과 (0.06ms, 30.1MB) // 테스트 15 〉 통과 (0.06ms, 30.1MB) // 테스트 16 〉 통과 (0.04ms, 30.2MB) // 테스트 17 〉 통과 (0.06ms, 30.2MB) // 테스트 18 〉 통과 (0.04ms, 29.7MB) // 테스트 19 〉 통과 (0.11ms, 30.1MB) // 테스트 20 〉 통과 (0.06ms, 30.1MB) // 테스트 21 〉 통과 (0.04ms, 30.3MB) ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/dkdlelk99.py ================================================ def solution(n): n = str(n) s = 0 for i in n: s += int(i) return s print(solution(21) == 3) print(solution(123) == 6) ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12931 * @param n | 자연수 * @return | N의 각 자릿수의 합을 구해서 return 제한사항 N의 범위 : 100,000,000 이하의 자연수 */ function solution(n) { return Array.prototype.reduce.call(n + '', (ans, char) => ans + Number(char), 0); } /* 문자열로 바꾸어 자리수를 더하는 것보다 수를 10으로 나누어 자리수를 구분하는 것이 조금 더 빠르다. 테스트 1 〉 통과 (0.06ms, 30.2MB) 테스트 2 〉 통과 (0.07ms, 30MB) 테스트 3 〉 통과 (0.07ms, 30.3MB) 테스트 4 〉 통과 (0.06ms, 30MB) 테스트 5 〉 통과 (0.07ms, 30.1MB) 테스트 6 〉 통과 (0.08ms, 30MB) 테스트 7 〉 통과 (0.06ms, 30.2MB) 테스트 8 〉 통과 (0.07ms, 30.2MB) 테스트 9 〉 통과 (0.08ms, 30MB) 테스트 10 〉 통과 (0.06ms, 30.1MB) 테스트 11 〉 통과 (0.06ms, 30.4MB) 테스트 12 〉 통과 (0.06ms, 30.2MB) 테스트 13 〉 통과 (0.08ms, 30.4MB) 테스트 14 〉 통과 (0.07ms, 30MB) 테스트 15 〉 통과 (0.06ms, 30.2MB) 테스트 16 〉 통과 (0.07ms, 30.2MB) 테스트 17 〉 통과 (0.06ms, 30MB) 테스트 18 〉 통과 (0.06ms, 30MB) 테스트 19 〉 통과 (0.08ms, 30.1MB) 테스트 20 〉 통과 (0.07ms, 30.4MB) 테스트 21 〉 통과 (0.06ms, 30.1MB) */ console.log( solution(123) === 6, solution(987) === 24, ); // function solution2(n) { var answer = 0; while (n > 0) { answer += (n % 10); n = Math.floor(n / 10); } return answer; } /* 테스트 1 〉 통과 (0.05ms, 30.2MB) 테스트 2 〉 통과 (0.05ms, 30.1MB) 테스트 3 〉 통과 (0.05ms, 30.2MB) 테스트 4 〉 통과 (0.05ms, 30MB) 테스트 5 〉 통과 (0.05ms, 29.8MB) 테스트 6 〉 통과 (0.06ms, 30.1MB) 테스트 7 〉 통과 (0.05ms, 30.1MB) 테스트 8 〉 통과 (0.05ms, 30.1MB) 테스트 9 〉 통과 (0.03ms, 30.1MB) 테스트 10 〉 통과 (0.05ms, 30MB) 테스트 11 〉 통과 (0.05ms, 30MB) 테스트 12 〉 통과 (0.05ms, 30.1MB) 테스트 13 〉 통과 (0.05ms, 30.2MB) 테스트 14 〉 통과 (0.05ms, 30MB) 테스트 15 〉 통과 (0.05ms, 30.1MB) 테스트 16 〉 통과 (0.05ms, 30.2MB) 테스트 17 〉 통과 (0.05ms, 30.2MB) 테스트 18 〉 통과 (0.05ms, 30MB) 테스트 19 〉 통과 (0.06ms, 30.2MB) 테스트 20 〉 통과 (0.05ms, 30MB) 테스트 21 〉 통과 (0.05ms, 30.1MB) */ ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/khw970421.js ================================================ function solution(n) { let sum=0; String(n).split('').forEach(function(e){ //넣은것을 글자마다 분리하여 그때의 숫자를 더하여 계산 sum+=Number(e); }) return sum; } //내가 새로수정한 코드 function solution(n) { let sum=0; return String(n).split('').map(e=>sum+=Number(e)).pop() } //피드백 받은 코드 function solution(n) { return String(n).split('').map(Number).reduce((a, b) => a + b); } ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12931 자릿수 더하기 [풀이] 1. list(str) = str을 한글자씩 끊어서 리스트화 ''' def solution(n): return sum(list(map(int, list(str(n))))) ''' string은 list로 간주되기 때문에 굳이 list화 할 필요 없음 return sum(list(map(int, str(n)))) ''' ================================================ FILE: programmers/난이도별/level01.자릿수_더하기/sjjyy.java ================================================ package 난이도별.level01.자릿수_더하기; public class sjjyy { public static int solution(int n) { String num = String.valueOf(n); int len = num.length(); int answer = 0; for (int i = 0 ; i < len ; i++) answer += Integer.parseInt(String.valueOf(num.charAt(i))); return answer; // return IntStream.range(0, len).map(i -> Integer.parseInt(String.valueOf(num.charAt(i)))).sum(); } public static int solution2(int n) { int answer = 0; String[] arr = String.valueOf(n).split(""); for (String s : arr) answer += Integer.parseInt(s); return answer; // return Arrays.stream(arr).mapToInt(Integer::parseInt).sum(); } public static void main(String[] args) { System.out.println(solution(321)); // 6 System.out.println(solution(1234567890)); // 45 System.out.println(solution2(321)); // 6 System.out.println(solution2(1234567890)); // 45 } } ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/6047198844.py ================================================ def solution(n): return list(map(int, str(n)))[::-1] ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12932 문제 : 자연수 뒤집어 배열로 만들기 쪼개고 역순을 취하는 방법을 사용했습니다. 한 줄로 할려니까 아직은 잘 안되더라구요 다른 사람 풀이 봤더니 저는 두 개의 별개의 식을 이어붙인 느낌인데 정말 깔끔한 한줄로 했길래 기억할려구 적어봅니다 [메모메모] list(map(int, reversed(str(n)))) ''' def solution(n): return list(reversed(list(map(int, str(n))))) ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/Jaewon0702.py ================================================ def solution1(n): return list(map(int, reversed(str(n)))) def solution2(n): return [int(i) for i in reversed(str(n))] def solution3(n): return [int(i) for i in str(n)][::-1] print(solution1(12345) == [5, 4, 3, 2, 1]) print(solution2(12345) == [5, 4, 3, 2, 1]) print(solution3(12345) == [5, 4, 3, 2, 1]) ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12932 ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/develop-sell.js ================================================ //첫번째 방법 function solution(n) { let answer = []; n = n + ""; let len = n.length for(let i = 0; i < len; i++){ answer.push(n[len - i - 1] * 1); } return answer; } // 문제풀이: // 숫자를 문자로 형변환 후, char 한 글자씩 반대로 접근(len - i -1)해서 answer 배열에 추가(push)한다. //2번째 방법 function solution(n) { return n.toString().split("").reverse().map((char)=> (Number(char))) } // 알게된 점: // reverse()라는 함수가 존재하는걸 깜빡했네요!! // 배열 크기 그대로 안의 내용을 바꿀 때 (여기선 문자 -> 숫자로 변경) map() 함수를 사용하면 효율적이다. // toString == n + "" (숫자 -> 문자) // Number(char) == n * 1 (문자 -> 숫자) //eyabc.js 님 코드 확인 후 변경 function solution(n) { return n.toString() .split("") .reverse() .map((char)=> (Number(char))) } ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/dkdlelk99.py ================================================ def solution(n): s = str(n) answer = [int(i) for i in s] answer.reverse() return answer print(solution(19) == [9, 1]) print(solution(12345) == [5,4,3,2,1]) ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12932 * n이 12345이면 [5,4,3,2,1]을 리턴 제한 조건 n은 10,000,000,000이하인 자연수입니다. * @param n | 자연수 * @return n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴 */ function solution(n) { const N = n.toString(); return [...N].reduceRight((arr, num) => { arr.push(Number(num)); return arr; }, []); } /* 테스트 1 〉 통과 (0.07ms, 30.2MB) 테스트 2 〉 통과 (0.09ms, 29.8MB) 테스트 3 〉 통과 (0.07ms, 30.1MB) 테스트 4 〉 통과 (0.08ms, 30.1MB) 테스트 5 〉 통과 (0.09ms, 30.1MB) 테스트 6 〉 통과 (0.07ms, 30MB) 테스트 7 〉 통과 (0.07ms, 30MB) 테스트 8 〉 통과 (0.07ms, 30.4MB) 테스트 9 〉 통과 (0.07ms, 29.7MB) 테스트 10 〉 통과 (0.07ms, 29.9MB) 테스트 11 〉 통과 (0.07ms, 30.3MB) 테스트 12 〉 통과 (0.08ms, 30.2MB) 테스트 13 〉 통과 (0.07ms, 30.2MB) */ console.log( solution(12345) === [5, 4, 3, 2, 1], ); function solution2(n) { return n.toString() .split('') .reverse() .map((Number)); } /* 테스트 1 〉 통과 (0.07ms, 30.2MB) 테스트 2 〉 통과 (0.06ms, 29.6MB) 테스트 3 〉 통과 (0.06ms, 29.9MB) 테스트 4 〉 통과 (0.05ms, 30.1MB) 테스트 5 〉 통과 (0.06ms, 30MB) 테스트 6 〉 통과 (0.07ms, 30.1MB) 테스트 7 〉 통과 (0.06ms, 30MB) 테스트 8 〉 통과 (0.06ms, 30.1MB) 테스트 9 〉 통과 (0.08ms, 30.3MB) 테스트 10 〉 통과 (0.07ms, 30.1MB) 테스트 11 〉 통과 (0.05ms, 30.3MB) 테스트 12 〉 통과 (0.06ms, 29.9MB) 테스트 13 〉 통과 (0.06ms, 29.9MB) */ ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/khw970421.js ================================================ function solution(n) { let answer = []; let swap=0; answer.push(String(n)); let h =answer[0].split(''); //숫자를 전부 한글자씩 배열에 분리 const h_length = h.length; for(let i=0;iNumber(x)); //문자를 글자마다 분리하고 위치를 뒤집은 후 문자를 숫자로 변환후 반환 } // 더 간단히 만들기 function solution(n) { return n.toString().split('').reverse().map(x=>Number(x)); } // 더욱 간단히 function solution(n) { return n.toString().split('').reverse().map(Number); } ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/s2uyeoii.cpp ================================================ #include #include #include int* solution(long long num) { // num 최댓값 고려해 11자리 수 int* answer = (int*)malloc(sizeof(int) * 11); for (int i = 0; i < 11; i++) { answer[i] = num % 10; num /= 10; } return answer; } ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12932 자연수 뒤집어 배열로 만들기 [풀이] 1. map 사용 ''' def solution(n): return list(map(int, str(n)))[::-1] ''' ''' ================================================ FILE: programmers/난이도별/level01.자연수_뒤집어_배열로_만들기/sjjyy.java ================================================ package 난이도별.level01.자연수_뒤집어_배열로_만들기; import java.util.Arrays; public class sjjyy { public static int[] solution(long n) { String ans = String.valueOf(n); int len = ans.length(); int [] answer = new int[len]; for (int i = 0 ; i < len ; i++) answer[i] = Integer.parseInt(String.valueOf(ans.charAt(len - i -1))); return answer; } public static void main(String[] args) { System.out.println(Arrays.toString(solution(12345))); System.out.println(Arrays.toString(solution(19))); } } ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/6047198844.py ================================================ def solution(n): return int(''.join(sorted(str(n))[::-1])) ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12933 문제 : 정수 내림차순으로 배치하기 입력받은 정수를 쪼갠 후 정렬하여 다시 합쳤습니다. ''' def solution(n): n_list = list(str(n)) n_list.sort() n_list.reverse() n_list = ''.join(n_list) return int(n_list) ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/HyeonJeong.py ================================================ def solution(n): answer = list(str(n)) #answer = [c for c in str(n)] answer.sorted(reverse = True) return int("".join(answer)) #한줄로는 return int("".join(sorted(list(str(n)), reverse = True))) print(solution(118372) == 873211) ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12933 ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/develop-sell.js ================================================ function solution(n) { return Number((n + "").split('').sort((a, b) => b-a).join('')); } // 문제풀이: // 스트링으로 변환 후 => (n + "") // 한 글자씩 배열로 변환 => split('') // 큰 숫자순으로 정렬 => sort((a,b) => b-a) // 배열을 스트링으로 변환 -> join('') // 스트링으로 숫자로 변환 -> Number(num) ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/dkdlelk99.py ================================================ def solution(n): return int(''.join(sorted(list(str(n)), reverse=True))) print(solution(118372) == 873211) print(solution(12421356) == 65432211) ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12933 제한 조건 n은 1이상 8000000000 이하인 자연수입니다. * @param n , 정수 * @return n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수 * n이 118372면 873211을 리턴하면 됩니다. */ function solution(n) { return [...n.toString()] .sort((a, b) => b - a) .join('') / 1; } console.log(solution(118372) === 873211); /* 스트 1 〉 통과 (0.08ms, 30.1MB) 테스트 2 〉 통과 (0.08ms, 30.2MB) 테스트 3 〉 통과 (0.07ms, 30.2MB) 테스트 4 〉 통과 (0.07ms, 30.1MB) 테스트 5 〉 통과 (0.07ms, 30.2MB) 테스트 6 〉 통과 (0.07ms, 30MB) 테스트 7 〉 통과 (0.06ms, 30MB) 테스트 8 〉 통과 (0.07ms, 30.2MB) 테스트 9 〉 통과 (0.11ms, 30MB) 테스트 10 〉 통과 (0.07ms, 30.1MB) 테스트 11 〉 통과 (0.07ms, 30.1MB) 테스트 12 〉 통과 (0.08ms, 30.1MB) 테스트 13 〉 통과 (0.08ms, 30.1MB) 테스트 14 〉 통과 (0.08ms, 30.2MB) 테스트 15 〉 통과 (0.07ms, 30MB) 테스트 16 〉 통과 (0.06ms, 30.1MB) */ function solution2(n) { return n.toString() .split('') .sort() .reverse() .join('') / 1; } /* 테스트 1 〉 통과 (0.05ms, 30MB) 테스트 2 〉 통과 (0.06ms, 30.1MB) 테스트 3 〉 통과 (0.06ms, 30.2MB) 테스트 4 〉 통과 (0.06ms, 30MB) 테스트 5 〉 통과 (0.05ms, 29.8MB) 테스트 6 〉 통과 (0.05ms, 30.2MB) 테스트 7 〉 통과 (0.05ms, 30.3MB) 테스트 8 〉 통과 (0.06ms, 30.2MB) 테스트 9 〉 통과 (0.06ms, 30MB) 테스트 10 〉 통과 (0.06ms, 30MB) 테스트 11 〉 통과 (0.06ms, 29.8MB) 테스트 12 〉 통과 (0.05ms, 30MB) 테스트 13 〉 통과 (0.06ms, 30MB) 테스트 14 〉 통과 (0.04ms, 30.1MB) 테스트 15 〉 통과 (0.06ms, 30.1MB) 테스트 16 〉 통과 (0.04ms, 30.1MB) */ ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/khw970421.js ================================================ function solution(n) { return Number(n.toString().split('').sort((A,B)=>B-A).join('')); } //값을 문자로바꿔 분리시킨후 숫자로 변환후 정렬시키고 다시 합쳐서 Number 형태로 반환 ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12933 정수 내림차순으로 배치하기 [풀이] 0. 주어진 int의 자릿수별로 내림차순 정렬하여 int로 출력 1. map 사용 ''' def solution(n): return int(''.join(map(str, sorted(list(map(int, str(n))),reverse=True)))) ''' sorted는 string으로 이루어진 int도 정렬한다. 따로 map(int, )할 필요 없음 def solution(n): return int("".join(sorted(str(n), reverse=True))); ''' ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/sjjyy.java ================================================ package 난이도별.level01.정수_내림차순으로_배치하기; import java.util.Arrays; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.joining; public class sjjyy { public static long solution(long n) { char[] arr = Long.toString(n).toCharArray(); Arrays.sort(arr); StringBuilder stringBuilder = new StringBuilder(); for (char i : arr) { stringBuilder.append(i); } stringBuilder.reverse(); return Long.parseLong(stringBuilder.toString()); } public static long solution2(long n) { return Arrays.stream(Long.toString(n).split("")) .map(Integer::parseInt) .sorted((a, b) -> b - a) .map(String::valueOf) .collect(collectingAndThen(joining(""), Long::parseLong)); } public static void main(String[] args) { System.out.println(solution(98023214)); // 98432210 System.out.println(solution2(98023214)); // 98432210 } } ================================================ FILE: programmers/난이도별/level01.정수_내림차순으로_배치하기/정수_내림순으로_배치하기.py ================================================ def solution(n): return int("".join(sorted(list(str(n)), reverse=True))) print(solution("118372") == 873211) ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/6047198844.py ================================================ import math def solution(n): root = n ** 0.5 return math.pow(root+1,2) if root.is_integer() else -1 ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12934 문제 : 정수 제곱근 판별 for문을 전부 돌려서 제곱근을 찾는 방법을 사용했습니다. 다른 사람 풀이를 보니 반복 없이 바로 제곱근을 구하더라구요 [메모메모] sqrt = n**(1/2) if sqrt%1==0 and (sqrt+1)**2 or -1 ''' def solution(n): for x in range(n+1) : if x**2==n : return (x+1)**2 return -1 ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/HyeonJeong.py ================================================ def solution(n): for i in range(1, n + 1): if n ** 0.5 == i: # if i ** 2 == n도 가능 return (i + 1) ** 2 elif i == n: return -1 print(solution(121) == 144) ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/Jaewon0702.py ================================================ from math import * def solution(n): return -1 if sqrt(n) % 1 else int(pow((sqrt(n) + 1), 2)) print(solution(121) == 144) print(solution(3) == -1) ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12934 ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/develop-sell.js ================================================ function solution(n) { //n을 루트씌운 것이 integer인지에 따라 -1, x+1의 제곱을 리턴 const num = Math.sqrt(n) return Number.isInteger(num) ? (num+1)*(num+1) : -1 ; } // 문제풀이: // n을 루트씌운 것이 integer인지 아닌지에 따라 -1, x+1의 제곱을 리턴한다. // 사용 함수: // Math.sqrt(n) : 제곱근을 구하는 함수 // Number.isInteger(num) : 정수인지 아닌지 확인하는 함수 (return true or false) // 배운 점: // 제곱하는 함수가 생각 안 나서 위에 식처럼 풀었다. // (num) ** 2 : 제곱하는 함수 ( 숫자 ** 2 / 숫자 ** 3 이면 세제곱) ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/dkdlelk99.py ================================================ def solution(n): for i in range(n+1): if i*i == n: return (i+1)**2 return -1 print(solution(121) == 144) print(solution(3) == -1) ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12934 제한 사항 n은 1이상, 50000000000000 이하인 양의 정수입니다. * @param n , 양의 정수 * @return n이 어떤 양의 정수 x의 제곱인지 아닌지 판단 x+1의 제곱을 리턴 : n이 양의 정수 x의 제곱이라면 -1을 리턴 : n이 양의 정수 x의 제곱이 아니라면 */ function solution(n) { const sqrt = n ** 0.5; return (sqrt - ~~sqrt) === 0 ? (sqrt + 1) ** 2 : -1; } function solution2(n) { const sqrt = Math.sqrt(n); return (sqrt - ~~sqrt) === 0 ? (sqrt + 1) ** 2 : -1; } /** * 테스트 1 〉 통과 (0.04ms, 30MB) 테스트 2 〉 통과 (0.04ms, 30.1MB) 테스트 3 〉 통과 (0.04ms, 30.1MB) 테스트 4 〉 통과 (0.04ms, 30.4MB) 테스트 5 〉 통과 (0.04ms, 30.2MB) 테스트 6 〉 통과 (0.04ms, 30.1MB) 테스트 7 〉 통과 (0.06ms, 30.1MB) 테스트 8 〉 통과 (0.05ms, 29.9MB) 테스트 9 〉 통과 (0.04ms, 30MB) 테스트 10 〉 통과 (0.03ms, 30.1MB) 테스트 11 〉 통과 (0.05ms, 30.1MB) 테스트 12 〉 통과 (0.04ms, 30.3MB) 테스트 13 〉 통과 (0.03ms, 30MB) 테스트 14 〉 통과 (0.04ms, 29.9MB) 테스트 15 〉 통과 (0.06ms, 30MB) 테스트 16 〉 통과 (0.05ms, 30.1MB) 테스트 17 〉 통과 (0.05ms, 29.8MB) 테스트 18 〉 통과 (0.05ms, 29.9MB) */ console.log( solution(121) === 144, solution(3) === -1, ); function solution2(n) { let a = Math.sqrt(n); return Math.floor(a) - a < 0 ? -1 : (a + 1) * (a + 1); } ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/khw970421.js ================================================ function solution(n) { return (Number.isInteger(n**0.5))? (n ** 0.5 + 1) ** 2 : -1; } //sqrt한 값이 Integer인지 판단하고 맞으면 +1하고 제곱하고 아니면 -1리턴 ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12934 정수 제곱근 판별 [풀이] 1. ** 사용 ''' def solution(n): return (n ** 0.5 + 1) ** 2 if int(n ** 0.5) ** 2 == n else -1 ''' 참고로 math.is_integer()를 사용할 수도 있음 ''' ================================================ FILE: programmers/난이도별/level01.정수_제곱근_판별/sjjyy.java ================================================ package 난이도별.level01.정수_제곱근_판별; public class sjjyy { public static long solution(long n) { double sqrt = Math.sqrt(n); return sqrt == (int) sqrt ? (long)Math.pow(sqrt+1, 2) : -1; } public static void main(String[] args) { System.out.println(solution(121)); // 144 System.out.println(solution(3)); // -1 } } ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/6047198844.py ================================================ def solution(arr): arr.remove(min(arr)) return arr if arr else [-1] ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12935 문제 : 제일 작은 수 제거하 제일 작은수(min(arr))을 제거(remove())함. ''' def solution(arr): answer = [] if len(arr) == 0 or len(arr) == 1 : answer.append(-1) return answer arr.remove(min(arr)) return arr ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/HyeonJeong.py ================================================ def solution(arr): if len(arr) == 1: return [-1] temp = min(arr) ''' min() 없이 풀면 temp = arr[0] for x in range(len(arr)): if arr[x] < temp: temp = arr[x] ''' for x in arr: if x == temp: arr.remove(x) return arr ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/Jaewon0702.py ================================================ def solution(arr): arr.remove(min(arr)) return arr if len(arr) else [-1] print(solution([4, 3, 2, 1]) == [4, 3, 2]) print(solution([10]) == [-1]) ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/JunilHwang.java ================================================ package programmers.난이도별.level01.제일_작은_수_제거하기; import java.util.ArrayList; import java.util.Arrays; public class JunilHwang { public static int[] solution(int[] arr) { if (arr.length < 2) return new int[]{-1}; int min = Arrays.stream(arr).reduce(Integer.MAX_VALUE, Math::min); return Arrays.stream(arr) .boxed() .filter(v -> v != min) .mapToInt(v -> v).toArray(); } public static void main(String[] args) { int[] arr = {1, 2, 3, 4}; int[] arr2 = {10}; System.out.println(Arrays.toString(solution(arr))); // [2, 3, 4] System.out.println(Arrays.toString(solution(arr2))); // [-1] } } ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12935 ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/develop-sell.js ================================================ function solution(arr) { let answer = []; let len = arr.length let min = Number.MAX_VALUE; let index = 0; arr.forEach(function(e, i){ if(min > e){ min = e; index = i; } }) arr.splice(index, 1) return len === 1 ? [-1] : arr; } // 문제풀이: // 예전에 처음 프로그래밍 배울 때 풀던 문제 같다 // min값을 갖고 있는 index를 구하고, // 그 위치의 요소를 찾아 없애는 방식이다. // 한줄 풀이: // arr.splice(arr.indexOf(Math.min(...arr)),1); // Math.min 이라는 함수로 최소값을 구할 수 있고, // 이때 배열을 ... 로 빼낸 다음 실행해야 가능하다. // indexOf 함수로 해당 값을 찾아서 splice로 값을 없애준다. (min에 해당되는 index를 구하는 작업이 불필요) ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/dkdlelk99.py ================================================ def solution(arr): if len(arr) == 1: return [-1] arr.remove(min(arr)) return arr print(solution([10]) == [-1]) print(solution([10,4,5,2,1]) ==[10, 4, 5, 2]) ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/khw970421.js ================================================ function solution(arr) { arr.splice(arr.indexOf(Math.min.apply(null,arr)),1); //가장 작은 값을 가진 위치에 있는 값을 없앤다. return (arr.length==0)?[-1]:arr; // 없앤후 값이 아예없으면 [-1]리턴 그게아니라면 arr리턴 } ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/rockmiin.py ================================================ def solution(arr): tmp=sorted(arr)[0] if len(arr)>1: arr.remove(tmp) return arr return [-1] print( solution([4, 1, 2, 3])==[4, 2, 3] ) ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12935 제일 작은 수 제거하기 [풀이] 1. remove, sorted 사용 ''' def solution(arr): arr and arr.remove(sorted(arr)[0]) return arr or [-1] ''' sorted = NlonN min = N 이니 최소값(최대값)을 이용할 것 ''' ================================================ FILE: programmers/난이도별/level01.제일_작은_수_제거하기/sjjyy.java ================================================ package 난이도별.level01.제일_작은_수_제거하기; import java.util.ArrayList; import java.util.Arrays; public class sjjyy { public static int[] solution(int[] arr) { int[] answer = new int[arr.length-1]; if (arr.length < 2) return new int[]{-1}; ArrayList arr2 = new ArrayList<>(); for (int i : arr) arr2.add(i); int min = arr[0]; for (int i = 1; i < arr.length; i++) min = Math.min(arr[i], min); arr2.remove((Integer) min); for (int i = 0 ; i < arr2.size() ; i++) answer[i] = arr2.get(i); return answer; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4}; int[] arr2 = {10}; System.out.println(Arrays.toString(solution(arr))); // [2, 3, 4] System.out.println(Arrays.toString(solution(arr2))); // [-1] } } ================================================ FILE: programmers/난이도별/level01.직사각혁_별찍기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12969 문제 : 직사각형 별찍기 중첩 for문을 이용하여 *을 찍었습니다. 다른 사람들의 코드를 참고하니 한 줄로도 가능하더라구요 메모메모 : print(("*"*a + "\n")*b) ''' a, b = map(int, input().strip().split(' ')) for i in range(0,b) : for j in range(0,a) : print('*', end='') print() ================================================ FILE: programmers/난이도별/level01.직사각형_별찍기/6047198844.py ================================================ a, b = map(int, input().strip().split(' ')) for _ in range(b): print('*' * int(a)) ================================================ FILE: programmers/난이도별/level01.직사각형_별찍기/HyeonJeong.py ================================================ a, b = map(int, input().strip().split(' ')) for x in range(b): for y in range(a): print('*', end = '') print('', end = "\n") ================================================ FILE: programmers/난이도별/level01.직사각형_별찍기/Jaewon0702.py ================================================ a, b = map(int, input().strip().split(' ')) print(('*' * a + '\n') * b) ================================================ FILE: programmers/난이도별/level01.직사각형_별찍기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12969 ================================================ FILE: programmers/난이도별/level01.직사각형_별찍기/dkdlelk99.py ================================================ a, b = map(int, input().strip().split(' ')) for i in range(b): print('*'*a) ================================================ FILE: programmers/난이도별/level01.직사각형_별찍기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12969 직사각형 별찍기 [풀이] 1. 반복문으로 생성된 list를 join. 이를 중첩 ''' a, b = map(int, input().strip().split(' ')) print(('*'*a +'\n')*b) ''' ''' ================================================ FILE: programmers/난이도별/level01.직사각형_별찍기/sjjyy.java ================================================ package 난이도별.level01.직사각혁_별찍기; import java.util.Scanner; public class sjjyy { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); for (int i = 0 ; i < b ; i++) { for (int j = 0 ; j < a ; j++) System.out.print("*"); System.out.println(); } } } ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/6047198844.py ================================================ def solution(num): return "Even" if num % 2 == 0 else "Odd" ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12937 문제 : 짝수와 홀수 2로 나눈 나머지로 짝수, 홀수 판별 ''' def solution(num): if num%2 == 0 : return 'Even' else : return 'Odd' ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/Jaewon0702.py ================================================ def solution(num): return "Odd" if num % 2 else "Even" print(solution(3) == "Odd") print(solution(4) == "Even") ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12937 ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/develop-sell.js ================================================ function solution(num) { return num % 2 != 0 ? "Odd" : "Even"; } // 문제풀이: // 2로 나눠지면 짝수, 아니면 홀수 ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/dkdlelk99.py ================================================ def solution(num): if num % 2 == 1: return "Odd" else: return "Even" print(solution(66) == "Even") print(solution(11) == "Odd") ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/khw970421.js ================================================ function solution(num) { return (num%2!=0) ? "Odd" : "Even" } ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/rockmiin.py ================================================ def solution(num): if num%2==0: return "Even" return "Odd" ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12937 짝수와 홀수 [풀이] 1. %2 ''' def solution(num): return num % 2 and "Odd" or "Even" ''' %2 대신 비트 연산자로 & 1 로 짝홀수 구분 가능 ''' ================================================ FILE: programmers/난이도별/level01.짝수와_홀수/sjjyy.java ================================================ package 난이도별.level01.짝수와_홀수; public class sjjyy { public static String solution(int num) { return num % 2 == 0 ? "Even" : "Odd"; } public static void main(String[] args) { System.out.println(solution(3)); // Odd System.out.println(solution(4)); // Even } } ================================================ FILE: programmers/난이도별/level01.체육복/HyeonJeong.py ================================================ def solution(n, lost, reserve): n_lost = set(lost) - set(reserve) n_reserve = set(reserve) - set(lost) for p in n_reserve: if (p - 1) in n_lost: n_lost.remove(p - 1) elif (p + 1) in n_lost: n_lost.remove(p + 1) return n - len(n_lost) print( solution(5,[2,4],[1,3,5]) == 5, solution(5,[2,4],[3]) == 4, solution(3,[3],[1]) == 2 ) ================================================ FILE: programmers/난이도별/level01.체육복/Jaewon0702.py ================================================ def solution(n, lost, reserve): inter=set(lost)&set(reserve); lost=set(lost)-inter; reserve=set(reserve)-inter for res in reserve: if res-1 in lost : lost.remove(res-1) elif res+1 in lost : lost.remove(res+1) return n-len(lost) #100점 print(solution(5,[2,4],[1,3,5])==5) print(solution(5,[2,4],[3])==4) ================================================ FILE: programmers/난이도별/level01.체육복/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42862 ================================================ FILE: programmers/난이도별/level01.체육복/develop-sell.js ================================================ function solution(n, lost, reserve) { let answer = 0; let arr = []; lost.sort((a,b) => a-b); reserve.sort((a,b) => a-b); let lost_num = 0; for(let i =0; i < n; i++){ if(lost[lost_num] === i+1){ arr[i] = 0; lost_num++; } else{ arr[i] = 1; } } for(let i =0; i i >= 1)).length; } // 문제풀이: // 우선 탐욕법이라는 알고리즘을 모르고 도전을 해봤다. (미루면 끝이 없을 것 같아서) // 처음엔 왼쪽이나, 오른쪽이나 주기만 하면 된다고 생각해서 // 왼쪽 사람부터 주고, 이미 있으면 오른쪽 사람을 주도록 코드를 짰다. // 먼저 for문을 한번 돌면서 없는 사람은 0, 있는 사람은 1인 배열로 만들었다. (ex. [1,0,1,0,1]) // 그 후 여벌 옷을 가진 사람의 리스트인 reserve를 돌면서 // 왼쪽사람(reserve[i] - 2), 오른쪽사람(reserve[i])의 값이 0인 사람은 1로 바꿔주게 했다.a // 문제점 1 // - 맨 왼쪽(1), 맨 오른쪽(n)은 각각 한쪽씩만 옷을 줄 수 있다 // - 그래서 앞에 if문을 추가했다. // - ex. reserve[i] !== 1 , reserve[i] !== n // 문제점 2 // - 잃어버린 사람의 배열과 여벌옷 가진 사람의 배열이 순서대로가 아닐 수 있다 // - 따라서 하기 전에 먼저 두 배열을 숫자에 맞게 sort해줬다 // 문제점 3 // - 여벌옷을 가진 사람도 뺏길 수 있다는 걸 알게되었다. // - 즉, reserve에도, lost에도 둘 다에 있는 번호가 존재할 수 있다. // - 이 경우 다른 사람에게 옷을 못 주고 자신이 입는다고 했다. // - 5 [2,3] [1,2] 4 이렇게 예시를 넣으면 알 수 있다 // - 자기 자신에게 여벌옷을 주는 경우를 생각 못하면 이 경우에서 답이 5가 나온다. // - (1이 2를 주고, 2가 3을 주게 되어서, 사실 2는 자신에게 주고 1이 3을 줄 수 없는 경우가 된다) // 문제점 4 // - 그걸 같은 for문에서 돌릴려고 하니까 문제가 되어서 // - 따로 for문을 돌려 여벌옷 있는 자기 자신이 0이면 자기 자신을 1로 만들고 // - 사용한 여벌옷 값을 0으로 바꿔준다. // - 이 후 밑에 for문에서는 0이면 이미 자기 자신에게 사용한 사람이니 넘어간다. // 다른 사람 코드 리뷰(junilhwang.js) // const arr = [-1] // for (let i = 1; i <= n; i++) arr[i] = 1 // lost.forEach(v => arr[v] -= 1) // reserve.forEach(v => arr[v] += 1) // for (let i = 1; i <= n; i++) { // if (arr[i] === 2 && arr[i - 1] === 0) arr[i - 1] = arr[i] = 1 // if (arr[i] === 2 && arr[i + 1] === 0) arr[i + 1] = arr[i] = 1 // } // return arr.filter(v => v >= 1).length; // 먼저 n까지 모두 1로 만들고, lost에 해당되는 index의 값을 0으로 바꿔준다 // 그리고 reserve에 해당되는 index의 값에 1을 더해준다. // 이로써 0,1,2 값을 가진 배열이 생긴다. (0은 없는 사람, 1은 있는 사람, 2는 여벌옷 있는 사람) // 이러면 위에서 자기자신에게 주는 사람의 케이스를 생각 안해도 된다! 굿 // 다음 마지막으로 for문을 돌리면서 2인 사람만 왼쪽 혹은 오른쪽에게 값을 나눠준다. // 그리고 맨 마지막 filter를 통해 1보다 큰 값을 가진 요소만 뽑아 길이를 return 한다. // 배운점: // 탐욕법, 처음 해보는 풀이었다. // 여러 조건을 주고 최적화, 최적의 방법을 찾는 것이 탐욕법이다. // 좀 더 공부할 필요성을 느꼈고, 조건대로 해보는 것이 좋다는 생각이 들었다. ================================================ FILE: programmers/난이도별/level01.체육복/dkdlelk99.py ================================================ def solution(n, lost, reserve): lost_set = set(lost) - set(reserve) reserve_set = set(reserve) - set(lost) for i in reserve_set: if i-1 in lost_set: lost_set.remove(i-1) elif i+1 in lost_set: lost_set.remove(i+1) return n - len(lost_set) print(solution(6, [1,2,3,4,5,6], [1,3]) == 2) print(solution(5, [2, 4], [1, 3, 5]) == 5) ================================================ FILE: programmers/난이도별/level01.체육복/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42862 function solution(n, lost, reserve) { const arr = [-1] for (let i = 1; i <= n; i++) arr[i] = 1 lost.forEach(v => arr[v] -= 1) reserve.forEach(v => arr[v] += 1) for (let i = 1; i <= n; i++) { if (arr[i] === 2 && arr[i - 1] === 0) arr[i - 1] = arr[i] = 1 if (arr[i] === 2 && arr[i + 1] === 0) arr[i + 1] = arr[i] = 1 } return arr.filter(v => v >= 1).length; } console.log(solution(5, [2, 4], [1, 3, 5]), 5) console.log(solution(5, [2, 4], [3]), 4) console.log(solution(3, [3], [1]), 2) console.log(solution(2, [1], [2]), 2) ================================================ FILE: programmers/난이도별/level01.체육복/khw970421.js ================================================ function solution(n, lost, reserve) { let rest = n-lost.length; //rest는 처음 인원에서 잃어버리지 않은 인원들 let new_lost=[]; for(let i=0;i 0: # Euclidean Algorithm m, n = n, m % n return [m, int(p / m)] print(solution(2, 5) == [1, 10]) print(solution(3, 12) == [3, 12]) ================================================ FILE: programmers/난이도별/level01.최대공약수와_최소공배수/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12940 ================================================ FILE: programmers/난이도별/level01.최대공약수와_최소공배수/dkdlelk99.py ================================================ def solution(n, m): a, b = max(n,m), min(n,m) for i in range(1, b+1): if n%i == 0 and m%i == 0: a1 = i return [a1,a*b//a1] print(solution(2,5) == [1,10]) print(solution(3,12) == [3,12]) print(solution(12,15) == [3,60]) ================================================ FILE: programmers/난이도별/level01.최대공약수와_최소공배수/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12940 * @param n * @param m * @return 두 수를 입력받아 두수의 [최대 공약수, 최소 공배수] * 두 수는 1이상 1000000이하의 자연수입니다. * 유클리드 호제법 https://ko.wikipedia.org/wiki/%EC%9C%A0%ED%81%B4%EB%A6%AC%EB%93%9C_%ED%98%B8%EC%A0%9C%EB%B2%95 * 2개의 자연수의 최대공약수를 구하는 알고리즘의 하나이다. * 호제법이란 말은 두 수가 서로(互) 상대방 수를 나누어(除)서 결국 원하는 수를 얻는 알고리즘을 나타낸다. * 2개의 자연수 a, b에 대해서 a를 b로 나눈 나머지를 r이라 하면(단, a > b), * a와 b의 최대공약수는 b와 r의 최대공약수와 같다. 이 성질에 따라, * b를 r로 나눈 나머지 r'를 구하고, 다시 r을 r'로 나눈 나머지를 구하는 과정을 반복하여 나머지가 0이 되었을 때 나누는 수가 a와 b의 최대공약수이다. */ const getGCD = (n, m) => { let [q, r] = n > m ? [n, m] : [m, n]; while (true) { const [newQ, newR] = [r, (q % r)]; if (newR === 0) return r; [r, q] = [newR, newQ]; } }; const getLCD = (n, m, gcd) => n * m / gcd; function solution(n, m) { if (n === m) return [n, m]; const gcd = getGCD(n, m); const lcd = getLCD(n, m, gcd); return [gcd, lcd]; }; console.log(solution(3, 12), [3, 12]); console.log(solution(2, 5), [1, 10]); console.log(solution(104, 1000000), [1, 2]); console.log(solution(78696, 19332), [36, 2]); // 옛날에 푼 것 function solution2(n, m) { let i = 2, max = 1; if (n === m) { return [n, n]; } while (i < n + m) { (n % i === 0) && (m % i === 0) ? max = i : ''; i++; } let min = n * m / max; return [max, min]; } ================================================ FILE: programmers/난이도별/level01.최대공약수와_최소공배수/khw970421.js ================================================ function solution(n, m) { let r,a,b; a=Math.max(n,m); b=Math.min(n,m); do{ r=a%b; //큰값에서 작은값을 나눈 나머지를 r에 저장 a=b; //a를 b로 변환 b=r; //b를 r로 변환 } while(r!==0) return [a].concat([m*n/a]) // a%b가 0이되었을때의 나누는수 b는 a=b로 인해 a이므로 최대공약수는 a 최소공배수는 m*n/a이다. } // 문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12940 //최소공배수 최대공배수 관련내용 //2개의 자연수 a, b에 대해서 a를 b로 나눈 나머지를 r이라 하면 (단 a>b), // a와 b의 최대공약수는 b와 r의 최대공약수와 같다. 이 성질에 따라, b를 r로 나눈 나머지 r0를 구하고, // 다시 r을 r0로 나눈 나머지를 구하는 과정을 반복하여 나머지가 0이 되었을 때 나누는 수가 a와 b의 최대공약수이다. // 이는 명시적으로 기술된 가장 오래된 알고리즘으로서도 알려져 있으며, 기원전 300년경에 쓰인 유클리드의 <원론> 제7권, 명제 1부터 3까지에 해당한다. //출처 : https://myjamong.tistory.com/138 ================================================ FILE: programmers/난이도별/level01.최대공약수와_최소공배수/rockmiin.py ================================================ def solution (n, m): answer=[] k=0 for i in range(1, min(n, m)+1): if n % i ==0 and m % i ==0: k=i answer.append(k) for i in range (max(n, m), n*m+1): if i % n ==0 and i % m==0: answer.append(i); break; return answer solution(3, 12) ================================================ FILE: programmers/난이도별/level01.최대공약수와_최소공배수/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12940 최대공약수와 최소공배수 [풀이] 1. math.gcd ''' from math import gcd def solution(n, m): g = gcd(n, m) return [g, n*m//g] ''' 다음은 유클리드 호제법 def gcdlcm(a, b): c, d = max(a, b), min(a, b) t = 1 while t > 0: t = c % d c, d = d, t answer = [c, int(a*b/c)] return answer ''' ================================================ FILE: programmers/난이도별/level01.최대공약수와_최소공배수/sjjyy.java ================================================ package 난이도별.level01.최대공약수와_최소공배수; import java.util.Arrays; public class sjjyy { public static int[] solution(int n, int m) { int[] answer = new int[2]; int tmp; if (n < m) { tmp = m; m = n; n = tmp; } for (int i = 1; i < n; i++) { if (n % i == 0 && m % i == 0) { answer[0] = i; answer[1] = (n * m) / i; } } return answer; } public static void main(String[] args) { System.out.println(Arrays.toString(solution(3, 12))); // [3, 12] System.out.println(Arrays.toString(solution(2, 5))); // [1, 10] } } ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/6047198844.py ================================================ def solution(num): for cnt in range(501): if num == 1: return cnt if num % 2 == 0: num /= 2 else: num = num * 3 + 1 return -1 ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12943 문제 : 콜라츠 추측 1이 되지 않으면 계속 반복하는 while문을 사용하여 짝수일때와 홀수일때 사용해야 하는 식을 적었습니다. answer 값이 500이 되면 return 하도록 했습니다. ''' def solution(num): answer = 0 while num != 1 : if num %2 == 0 : num /= 2 else : num = num*3+1 if answer == 500 : return -1 answer += 1 return answer ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/HyeonJeong.py ================================================ def solution(num): tries = 0 while num != 1: num = num // 2 if num % 2 == 0 else num * 3 + 1 tries += 1 if tries == 500: return -1 return tries ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/Jaewon0702.py ================================================ def solution(num): n = 0 while num > 1: num = num * 3 + 1 if num % 2 else num / 2 n += 1 if n == 500: return -1 return n print(solution(6) == 8) print(solution(16) == 4) print(solution(626331) == -1) ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12943 ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/develop-sell.js ================================================ function solution(num) { let answer = 0; while(1){ if(answer == 500) return -1; if(num == 1) break; num % 2 == 0 ? num /= 2 : num = (num * 3) + 1 answer++; } return answer; } // 문제풀이: // 짝수면 나누기 2, 홀수면 3 곱하고 + 1 해준다. // 언제까지? 숫자가 1이 되거나, 돌린 횟수가 500번이 되는 경우(return -1) // 아쉬운점: // eyabc.js님 코드 확인 후 무한루프가 아니라, // num != 1로 돌리면 한 줄 더 줄일 수 있음을 알게 되었다. //변경 된 코드 // while(num != 1){ // if(answer == 500) // return -1; // num % 2 == 0 ? num /= 2 : num = (num * 3) + 1 // answer++; // } // 프로세스를 이렇게 함수로 명칭해서 보니까 눈으로 보기 좋음을 알게 되었습니다. // 앞으론 네이밍도 한번 도전해보겠습니다. // const process = (num) => isEven(num) ? num / 2 : num * 3 + 1; ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/dkdlelk99.py ================================================ def solution(num): count = 0 while num != 1: if num%2 == 0: num = num/2 count += 1 else: num = num*3 + 1 count += 1 if count > 500: return -1 return count print(solution(6) == 8) print(solution(16) == 4) print(solution(626331) == -1) ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12943 * 주어진 수가 1이 될때까지 다음 작업을 반복하면, 모든 수를 1로 만들 수 있다는 추측입니다. * 1-1. 입력된 수가 짝수라면 2로 나눕니다. 1-2. 입력된 수가 홀수라면 3을 곱하고 1을 더합니다. 2. 결과로 나온 수에 같은 작업을 1이 될 때까지 반복합니다. * @param num , 1 이상 8000000 미만인 정수 * @return num 을 위 작업을 몇 번 반복해야 1로 만들 수 있는지 횟수를 반환함. * 작업을 500번을 반복해도 1이 되지 않는다면 –1을 반환 */ const isEven = (num) => num % 2 === 0; // 1-1. 입력된 수가 짝수라면 2로 나눕니다. // 1-2. 입력된 수가 홀수라면 3을 곱하고 1을 더합니다. const process = (num) => isEven(num) ? num / 2 : num * 3 + 1; function solution(num) { let [cnt, number] = [0, num]; // 2. 결과로 나온 수에 같은 작업을 1이 될 때까지 반복합니다. while (number !== 1) { number = process(number); // 작업을 500번을 반복해도 1이 되지 않는다면 –1을 반환 if (cnt++ === 500) return -1; } return cnt; } console.log(solution(6) === 8); console.log(solution(16) === 4); console.log(solution(626331) === -1); // 옛날에 푼것 function solution2(num) { let times = 0; while (num !== 1) { num = num % 2 ? num * 3 + 1 : num / 2; times++; if (times === 500) return -1; } return times; } ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/khw970421.js ================================================ function solution(num) { let a=0; if(num===1) return 0; do { num=(num%2===0)?(num/2):(num*3+1); a++; } while(num!==1) return (500>a)?a:-1; } // 출처 : https://programmers.co.kr/learn/courses/30/lessons/12943 ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/rockmiin.py ================================================ def solution(num): for i in range(500): if num == 1: return i elif(num%2==0): num=num/2 else: num=3*num+1 return -1 print( solution(6) ) ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/s2uyeoii.cpp ================================================ #include #include #include int solution(long long num) { //마지막 테스트 케이스가 int범위 초과 for(int answer=0; answer<500; answer++) { if(num==1) return answer; else num = (num%2==0) ? (num/2) : (num*3+1); } return -1; } ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12943 콜라츠 추측 [풀이] 1. 주어진 알고리즘 그대로 풀이 ''' def solution(num): for i in range(500): if num == 1: return i num = num * 3 + 1 if num & 1 else num // 2 return -1 ''' ''' ================================================ FILE: programmers/난이도별/level01.콜라츠_추측/sjjyy.java ================================================ package 난이도별.level01.콜라츠_추측; public class sjjyy { public static int solution(long num) { int answer = 0; while (num != 1) { if (num % 2 == 0) num /= 2; else num = num * 3 + 1; answer++; if (answer == 500) { return -1; } } return answer; } public static void main(String[] args) { System.out.println(solution(6)); // 8 System.out.println(solution(16)); // 4 System.out.println(solution(626331)); // -1 } } ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/6047198844.cpp ================================================ #include #include #include using namespace std; int solution(vector> board, vector moves) { stack st[30]; int row_size = board.size(); int column_size = board[0].size(); for (int x = 0; x < column_size; x++) { for (int y = row_size - 1; y >= 0; y--) { if (board[y][x]) st[x].push(board[y][x]); else break; } } stack res; int cnt = 0; for (int x : moves) { if (!st[x - 1].empty()) { int pick_num = st[x - 1].top(); st[x - 1].pop(); if (!res.empty() && res.top() == pick_num) { res.pop(); cnt += 2; } else { res.push(pick_num); } } } return cnt; } ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/64061 문제 : 크레인 인형뽑기 게임 마침 어제 코드리뷰하면서 본 defaultdict와 deque를 이용할 수 있겠다 싶어서 바로 적용해본 문제 근데 만들고나니 popleft() 쓸 일이 없어 불필요해 보이긴 하네요 :| ''' from collections import defaultdict, deque def solution(board, moves): answer = 0 dolls = defaultdict(list) # board의 인형을 위치별로 리스트로 묶었습니다. for i in board[::-1] : for j in range(len(board)) : if i[j] != 0 : dolls[j].append(i[j]) # 바구니에 인형을 넣고, dolls에서 없애는 과정 bucket = deque([-1]) for i in moves : if dolls[i-1] : if bucket[-1] == dolls[i-1][-1] : bucket.pop() dolls[i-1].pop() answer += 2 else : bucket.append(dolls[i-1].pop()) return answer ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/HyeonJeong.py ================================================ def solution(board, moves): answer = 0 slist = [] length = len(board) for m in moves: if board[length-1][m-1] == 0: continue for i in range(length): if board[i][m - 1] == 0: continue if len(slist) > 0 and slist[-1] == board[i][m - 1]: answer += 2 slist.pop(-1) else: slist.append(board[i][m - 1]) board[i][m - 1] = 0 break return answer print(solution([[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]], [1,5,3,5,1,2,1,4])) #4 ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/64061 ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/dkdlelk99.py ================================================ def solution(board, moves): answer = 0 basket = [] new_board = [] for i in range(len(board)): row = [] for j in range(len(board)): if board[j][i] != 0: row.append(board[j][i]) new_board.append(row) for i in moves: if new_board[i-1] == []: continue else: if basket == []: basket.append(new_board[i-1].pop(0)) continue element = new_board[i-1].pop(0) if basket[-1] != element: basket.append(element) elif basket[-1] == element: answer += 2 basket.pop() return answer board = [[0, 0, 0, 0, 0], [0, 0, 1, 0, 3], [0, 2, 5, 0, 1], [4, 2, 4, 4, 2], [3, 5, 1, 3, 1]] moves = [1, 5, 3, 5, 1, 2, 1, 4] print(solution(board, moves) == 4) ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/eyabc.js ================================================ // row 를 column 으로 바꿈 const transRow2Col = (arr, row) => { row.forEach((item, idx) => { if (!arr[idx]) arr.push([]); arr[idx].push(item); }); }; // 행과 열을 바꾼다. const newMachine = (board) => { return board.reduce((arr, row) => { transRow2Col(arr, row); return arr; }, []); }; function solution (board, moves) { const machine = newMachine(board); return moves.reduce(({ basket, deleteCnt }, move) => { const pick = move - 1; // 해당 열에서 가장 먼저 나오는 인형을 pick 한다. machine[pick].find((dol, idx) => { const result = dol !== 0; // 해당 열에서 인형이 존재하면 if (!result) return result; // 바구니 최상위의 인형과 동일한 종류일 때, deleteCnt 을 추가해 준다. if (basket[basket.length - 1] === dol) { deleteCnt += 2; machine[pick][idx] = 0; basket.pop(); return true; } basket.push(dol); machine[pick][idx] = 0; }); return { basket, deleteCnt }; }, { basket: [], deleteCnt: 0 }).deleteCnt; } console.log( solution([[0, 0, 0, 0, 0], [0, 0, 1, 0, 3], [0, 2, 5, 0, 1], [4, 2, 4, 4, 2], [3, 5, 1, 3, 1]], [1, 5, 3, 5, 1, 2, 1, 4]) === 4, ); ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/rockmiin.py ================================================ def solution(board, moves): basket= [] n= len(board) cnt= 0 for pick in moves: tmp= 0 for idx in range(n): if board[idx][pick-1]!= 0: tmp= board[idx][pick-1] board[idx][pick-1]= 0 break if tmp==0: continue if len(basket)>=1 and basket[-1]== tmp: basket.pop(-1); cnt+=2; continue basket.append(tmp) return cnt solution([[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]], [1,5,3,5,1,2,1,4]) ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/64061 크레이 인형뽑기 게임 [풀이] 1. 각 열마다 있는 인형 개수 조사 2. movee에 대해 반복문 => 뽑을 인형이 없으면 continue => 뽑을 인형이 있으면 bucket에 담고 top과 같은지 비교 => 같으면 bomb 추가 3. 뽑은 인형은 bucket에 닮기고 top을 bucket에 마지막 원소로 지정 ''' def solution(board, moves): numLine = [0 for i in range(len(board))] for i in board: for idx, val in enumerate(i): numLine[idx] += 1 if val != 0 else 0 gameSize = len(numLine) numLine.insert(0,0) #print(numLine, moves) bucket = [] top = bomb = 0 for i in moves: #print("i : ", i, ", numLine[i] : ", numLine[i]) if numLine[i] == 0: continue #print("top : ", top, ", board[gameSize-numLine[i]][i-1] : ", board[gameSize-numLine[i]][i-1]) if top != board[gameSize-numLine[i]][i-1]: bucket.append(top) top = board[gameSize-numLine[i]][i-1] numLine[i] -= 1 #print("bucket + top : ", bucket, top) continue top = bucket.pop() numLine[i] -= 1 bomb += 1 #print("bucket + top : ", bucket, top, ", bomb : ", bomb) return 2 * bomb ''' ''' ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/sjjyy.java ================================================ package 난이도별.level01.크레인_인형뽑기_게임; import java.util.Stack; public class sjjyy { public static int solution(int[][] board, int[] moves) { int answer = 0; Stack stack = new Stack<>(); for (int i : moves) { for (int j = 0; j < board.length; j++) { if (board[j][i - 1] != 0) { if (stack.empty()) // 바구니가 비었으면 인형을 넣음 stack.push(board[j][i - 1]); else { if (stack.peek() == board[j][i - 1]) // 바구니 맨 위쪽 인형과 넣은 인형이 같다면 제거 { stack.pop(); answer += 2; } else stack.push(board[j][i - 1]); // 다르다면 인형을 넣음 } board[j][i - 1] = 0; // 뽑기 기계 칸을 비움 break; } } } return answer; } public static void main(String[] args) { int[][] board = new int[][]{ {0, 0, 0, 0, 0}, {0, 0, 1, 0, 3}, {0, 2, 5, 0, 1}, {4, 2, 4, 4, 2}, {3, 5, 1, 3, 1}}; int[] moves = new int[]{1, 5, 3, 5, 1, 2, 1, 4}; System.out.println(solution(board, moves)); // 4 } } ================================================ FILE: programmers/난이도별/level01.크레인_인형뽑기_게임/turquoiseluv.py ================================================ board = [[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]] moves = [1,5,3,5,1,2,1,4] def solution(board, moves): basket = [] board = [list(x) for x in zip(*board)] for move in moves: for idx in range(len(board[move-1])): if board[move-1][idx] != 0: basket.append(board[move-1][idx]) board[move-1][idx] = 0 break result = 0 while(True): match = False for idx in range(len(basket)-1): if basket[idx] == basket[idx+1]: result += 1 basket[idx] = 0 basket[idx+1] = 0 basket = basket[:idx] + basket[idx+2:] match = True break if not match: return result*2 print(solution(board, moves)) ================================================ FILE: programmers/난이도별/level01.키패드_누르기/6047198844.cpp ================================================ #include #include #include using namespace std; string answer = ""; void left(int ¤t_left,string &answer,int click){ current_left = click; answer += 'L'; } void right(int ¤t_right,string &answer,int click){ current_right = click; answer += 'R'; } string solution(vector numbers, string hand) { int current_left = 10; int current_right = 12; for (auto click : numbers) { if (!click) click = 11; if (click % 3 == 1) { left(current_left,answer,click); } else if (click % 3 == 0) { right(current_right,answer,click); } else { int left_distance = abs(current_left - click) / 3 + abs(current_left - click) % 3; int right_distance = abs(current_right - click) / 3 + abs(current_right - click) % 3; if (left_distance < right_distance) left(current_left,answer,click); else if (left_distance > right_distance) right(current_right,answer,click); else{ if (hand == "left") left(current_left,answer,click); else right(current_right,answer,click); } } } return answer; } int main() { solution({ 1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5 }, "right"); } ================================================ FILE: programmers/난이도별/level01.키패드_누르기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/67256 문제 : 키패드 누르기 ''' def solution(numbers, hand): answer = '' left = 10 # 키패드 *:10, 0:11, #:12로 지정 right = 12 distance = { # value : 키패드 숫자 차이, key : 거리 1 : [1,3], 2 : [2,4,6], 3 : [5,7,9], 4 : [8,10] } for i in numbers : if i in [1,4,7] : # 누를 키패드가 1,4,7인 경우 왼손 사용 answer += 'L' left = i elif i in [3,6,9] : # 누를 키패드가 3,6,9인 경우 오른손 사용 answer += 'R' right = i else : if i==0 : i = 11 l_dist = abs(left-i) # 현재 손위치의 숫자와 누를 키패드 숫자의 차 r_dist = abs(right-i) for key, val in distance.items() : # distance의 value에 해당하는 key 값(거리) 가져옴 if l_dist in val : l_dist = key if r_dist in val : r_dist = key if l_dist == r_dist : # 왼손, 오른손 거리가 같으면 hand로 결정 if hand=='right' : answer += 'R' right = i else : answer += 'L' left = i elif l_dist <= r_dist : # 왼손 거리가 더 짧으면 왼손 사용 answer += 'L' left = i else : # 오른손 거리가 더 짧으면 오른손 사용 answer += 'R' right = i return answer ================================================ FILE: programmers/난이도별/level01.키패드_누르기/eyabc.js ================================================ // 폰 배열을 dictionary 로 생성 const phoneObj = (() => { const phone = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ['*', 0, '#'], ]; return phone.reduce((obj = {} , numbers, x) => { numbers.forEach((number, y) => obj[number] = [x, y]); return obj; }, {}); })(); // 'right' -> 'R', 'left' -> 'L 로 바꿔주는 함수 const handToShort = (hand) => hand === 'left' ? 'L' : 'R'; // 왼쪽키패드, 오른쪽키패드 인지 아니면 중간키패드인지 구분해주는 함수 const getHand = (number) => { if ([1, 4, 7].includes(number)) return 'L'; if ([3, 6, 9].includes(number)) return 'R'; return false; }; // 중간 키패드일때, 중간키패드와 왼손 혹은 오른손 키패드와의 간격을 계산하는 함수 const distanceOf2Points = ([x1, y1], [x2, y2]) => Math.abs(x1 - x2) + Math.abs(y1 - y2); // 중간 키패드일 때, 왼손이 가까운지 오른손이 가까운지 구한다. const getCloseHand = (number, leftCurr, rightCurr, hand) => { // 중간키패드, 좌 우 키패드의 location 배열을 가져온다. const numberLocation = phoneObj[number]; const leftLocation = phoneObj[leftCurr]; const rightLocation = phoneObj[rightCurr]; // 중간키패드 - 좌 키패드, 중간키패드 - 우 키패드 각각 얼마나 떨어져있는지 구한다. const diffFromLeft = distanceOf2Points(numberLocation, leftLocation); const diffFromRight = distanceOf2Points(numberLocation, rightLocation); const diff = diffFromLeft - diffFromRight; // 차이가 같을떄는 거리가 같으므로, hand (R, L) 를 리턴하고, 좌키패드가 더 멀면 오른손을, 우키패드가 더 멀면 왼손을 리턴한다. if (diff === 0) return hand; if (diff > 0) return 'R'; if (diff < 0) return 'L'; }; function solution (numbers, hand) { // 손의 움직임을 저장하는 변수 let leftCurr = '*'; let rightCurr = '#'; // hand 를 움직인다. const changeLocation = (H, number) => { if (H === 'L') leftCurr = number; if (H === 'R') rightCurr = number; }; // hand 인자를 'R', 'L' 으로 바꿔준다. const shortHand = handToShort(hand); // 각 숫자를 누른키가 어떤 손인지 반환하는 map 메서드 return numbers.map(number => { // 키패드를 왼손으로 누를수 있는지 오른손으로 누를 수 있는지 혹은 중간키패드여서 계산이 필요한지 리턴하는함수. let result = getHand(number); // 중간 키패드여서 왼손인지 오른손으로 눌러야 하는지 결정해야 함수를 부른다. if (!result) result = getCloseHand(number, leftCurr, rightCurr, shortHand); // 키보드를 눌러 현재 손의 위치를 변경한다. changeLocation(result, number); // 'R' 혹은 'L' 를 리턴한다. return result; }).join(''); // 문자열로 만든다. } const assert = require('assert').strict; require('./test.json').forEach(({ input, output }) => { assert.deepEqual(solution(...input), output); }); ================================================ FILE: programmers/난이도별/level01.키패드_누르기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/67256 키패드 누르기 [풀이] 1. 키패드를 1을 중심으로 (0,0)~(3,2)로 설정, 해당 좌표로부터의 거리를 기준으로 조건문 ''' def solution(numbers, hand): answer = '' l, r = (3, 0), (3, 2) for i in numbers: if i and i % 3 == 1: answer += "L" l = (i // 3, 0) elif i and i % 3 == 0: answer += "R" r = (i // 4, 2) else: n = (i // 4, 1) if i else (3, 1) which = abs(n[1] - l[1]) + abs(n[0] - l[0]) - abs(n[1] - r[1]) - abs(n[0] - r[0]) if which < 0: l = n answer += "L" elif which > 0: r = n answer += "R" else: if hand == "left": l = n answer += "L" else: r = n answer += "R" return answer ''' ''' ================================================ FILE: programmers/난이도별/level01.평균_구하기/6047198844.py ================================================ def solution(arr): return sum(arr) / len(arr) ================================================ FILE: programmers/난이도별/level01.평균_구하기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12944 문제 : 평균 구하기 하샤드 수 문제를 풀 때 한 줄의 코드로 덧셈을 하는 것을 보고 이를 따라해봤습니다. 그런데 여기서는 list라 훨씬 쉽게 하는 방법이 있어 메모합니다. [메모메모] sum(arr) / len(arr) ''' def solution(arr): answer = sum([x for x in arr]) / len(arr) return answer ================================================ FILE: programmers/난이도별/level01.평균_구하기/HyeonJeong.java ================================================ package 난이도별.level01.평균_구하기; public class HyeonJeong { class Solution { public double solution(int[] arr) { double average; double total = 0; for(int i = 0; i < arr.length; i++) total += arr [i]; average = total / arr.length; return average; } } } ================================================ FILE: programmers/난이도별/level01.평균_구하기/Jaewon0702.py ================================================ import numpy def solution1(arr): return numpy.mean(arr) def solution2(arr): return sum(arr) / len(arr) print(solution1([1, 2, 3, 4])) print(solution1([5, 5])) print(solution2([1, 2, 3, 4]) == 2.5) print(solution2([5, 5]) == 5) ================================================ FILE: programmers/난이도별/level01.평균_구하기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12944 ================================================ FILE: programmers/난이도별/level01.평균_구하기/develop-sell.js ================================================ function solution(arr) { return arr.reduce((result, present) => (result + present)) / arr.length; } // 문제풀이: // 지난 번에 배웠던 reduce 함수를 통해 값을 구할 수 있었다. // reduce의 맨 앞 값(result)은 함수 적용된 후의 함수이고, // present는 현재 값이다. // 결과에 현재값을 다 더하고, array의 길이 만큼 나누면 평균값이 나온다. ================================================ FILE: programmers/난이도별/level01.평균_구하기/dkdlelk99.py ================================================ def solution(arr): answer = 0 for i in arr: answer += i return answer/len(arr) print(solution([1,2,3,4]) == 2.5) print(solution([1,4,7,9]) == 5.25) ================================================ FILE: programmers/난이도별/level01.평균_구하기/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12944 * * @param arr, 정수를 담고 있는 배열 * @return 배열 arr의 평균값 * arr은 길이 1 이상, 100 이하인 배열입니다. arr의 원소는 -10,000 이상 10,000 이하인 정수입니다. */ console.log(solution([1, 2, 3, 4]) === 2.5); console.log(solution([5, 5]) === 5); function solution(arr) { return arr.reduce((sum, num) => sum + num) / arr.length; } // 옛날에 푼 것 function solution2(arr) { var answer = 0; arr.forEach(e => { answer += e; }); return answer / arr.length; } ================================================ FILE: programmers/난이도별/level01.평균_구하기/khw970421.js ================================================ function solution(arr) { return arr.reduce((a,b)=>a+b)/arr.length; } //출처 : https://programmers.co.kr/learn/courses/30/lessons/12944 ================================================ FILE: programmers/난이도별/level01.평균_구하기/rockmiin.py ================================================ def solution(arr): return sum(arr)/len(arr) print( solution([1, 2, 3, 4])==2.5 ) ================================================ FILE: programmers/난이도별/level01.평균_구하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12944 평균 구하기 [풀이] 1. sum / len ''' def solution(arr): return sum(arr)/len(arr) ''' ''' ================================================ FILE: programmers/난이도별/level01.평균_구하기/sjjyy.java ================================================ package 난이도별.level01.평균_구하기; import java.util.Arrays; public class sjjyy { public static double solution(int[] arr) { double answer = 0; for (int i : arr) { answer += i; } answer /= arr.length; return answer; } public static double solution2(int[] arr) { return Arrays.stream(arr).average().getAsDouble(); } public static void main(String[] args) { int[] arr = {1, 2, 3, 4}; int[] arr2 = {5, 5}; System.out.println(solution(arr)); // 2.5 System.out.println(solution(arr2)); // 5 System.out.println(solution2(arr)); // 2.5 System.out.println(solution2(arr2)); // 5 } } ================================================ FILE: programmers/난이도별/level01.폰켓몬/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/1845 폰켓몬 [풀이] 1. set 사용 ''' def solution(nums): return min(len(nums)//2, len(set(nums))) ''' ''' ================================================ FILE: programmers/난이도별/level01.하샤드_수/6047198844.py ================================================ def solution(x): return x % sum(map(int,str(x))) == 0 ================================================ FILE: programmers/난이도별/level01.하샤드_수/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12947 문제 : 하샤드 10으로 나눈 나머지를 계속 더함으로써 각 자리수의 합을 구했습니다. 다른 사람 풀이를 보니 한 줄만으로도 자릿수의 합을 구할 수 있었습니다. [메모메모] x % sum([int(c) for c in str(x)]) ''' def solution(x): answer = True sum = 0 num = x for i in range(len(str(x))) : sum += num%10 num //= 10 if x%sum != 0 : answer = False return answer ================================================ FILE: programmers/난이도별/level01.하샤드_수/HyeonJeong.py ================================================ def solution(x): total = 0 num = x for i in str(x): if num > 0: total += num % 10 num = num // 10 return x % total == 0 ================================================ FILE: programmers/난이도별/level01.하샤드_수/Jaewon0702.py ================================================ def solution(x): return not (x % sum(map(int, str(x)))) print(solution(10) == True) print(solution(12) == True) print(solution(11) == False) print(solution(13) == False) ================================================ FILE: programmers/난이도별/level01.하샤드_수/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12947 ================================================ FILE: programmers/난이도별/level01.하샤드_수/develop-sell.js ================================================ function solution(x) { let num = (x + '') .split('') .reduce((ans, cur) => (ans * 1 + cur * 1)); if (x % num !== 0) return false; return true; } // 문제풀이: // 먼저 숫자를 str로 변환 후, // split으로 한 글자씩 arr에 저장한다. // 그 후 reduce함수를 통해 각 한 글자씩 더한 값을 구한다. (== num) // 만약 주어진 x가 num으로 나눠지지 않으면 false, 나눠지면 true이다. // 한 줄 코드: // return !(n % (n + "").split("").reduce((a, b) => +b + +a )); // js에서 0이면 false, 아니면 true로 인식하니까, // 앞에 !(부정)으로 반환해주면 아래 if문을 한 줄 더 줄일 수 있다. ================================================ FILE: programmers/난이도별/level01.하샤드_수/dkdlelk99.py ================================================ def solution(x): s= str(x) sum = 0 for i in s: sum += int(i) return True if x % sum == 0 else False print(solution(10) == True) print(solution(12) == True) print(solution(11) == False) print(solution(13) == False) ================================================ FILE: programmers/난이도별/level01.하샤드_수/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12947 * 하샤드 수: x의 자릿수의 합으로 x가 나누어져야 합니다. * @param x, 1 ~ 10000 정수 * @return 자연수 x를 입력받아 x가 하샤드 수인지 boolean */ // 자리수의 합을 구하는 함수 const positionSum = (num) => [...String(num)].reduce((sum, num) => sum + Number(num), 0); function solution(x) { return x % positionSum(x) === 0; } console.log(solution(10) === true); console.log(solution(12) === true); console.log(solution(11) === false); console.log(solution(13) === false); // 옛날에 푼 것 function solution2(x) { return x % ((x + '').split('').reduce((a, b) => +a + +b)) === 0; } ================================================ FILE: programmers/난이도별/level01.하샤드_수/khw970421.js ================================================ function solution(x) { return (x%String(x).split('').reduce((a,b)=>Number(a)+Number(b))==0)?(true):false; } // 출처 : https://programmers.co.kr/learn/courses/30/lessons/12947 //수정한 코드 (가독성 높이기위해) function solution(x) { return (x%number_Of_Digits(x)==0)?(true):false; } function number_Of_Digits(x){ //자릿수에 따라 더한값을 return return String(x).split('').reduce((a,b)=>Number(a)+Number(b)); } ================================================ FILE: programmers/난이도별/level01.하샤드_수/rockmiin.py ================================================ def solution(x): answer=True sum=0 for i in str(x): sum+=int(i) if x%sum!=0: answer=False return answer print( solution(12)==True ) ================================================ FILE: programmers/난이도별/level01.하샤드_수/s2uyeoii.cpp ================================================ #include #include #include bool solution(int x) { int sum = 0; int x1 = x; while(x>=1 || x1 != 0) { sum += x1 % 10; x1 /= 10; } return x % sum == 0; } ================================================ FILE: programmers/난이도별/level01.하샤드_수/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12947 하샤드 수 [풀이] 1. list화 하여 sum ''' def solution(x): return not x % sum(list(map(int, str(x)))) ''' ''' ================================================ FILE: programmers/난이도별/level01.하샤드_수/sjjyy.java ================================================ package 난이도별.level01.하샤드_수; import java.util.Arrays; public class sjjyy { public static boolean solution(int x) { String str = Integer.toString(x); String [] arr = str.split(""); /* int sum = 0; for(String i : arr) sum += Integer.parseInt(i); */ int sum = Arrays.stream(arr).map(Integer::parseInt).reduce(0, Integer::sum); return x % sum == 0; } public static void main(String[] args) { int x = 10; int z = 11; System.out.println(solution(x)); System.out.println(solution(z)); } } ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/6047198844.py ================================================ def solution(phone_number): N = len(phone_number) return '*' * (N-4) + phone_number[-4:] ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12948 문제 : 핸드폰 번호 가리기 뒤 4글자를 제외한 나머지 *을 for문으로 넣은 후, 뒤 네글자 추가하여 각각 나누어진 문자열을 하나로 합쳤습니다. 다른 사람 코드를 보니 문자열 곱셈을 하면 되는데 바보처럼 했네요 ㅠ [메모메모] '*'*(len(phone_number)-4)+phone_number[-4:] ''' def solution(phone_number): answer = '' answer = ['*' for x in range(len(phone_number)-4)] back = phone_number[-4:] answer += back answer = ''.join(answer) return answer ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/HyeonJeong.py ================================================ def solution(phone_number): return phone_number.replace(phone_number[:-4],'*'*len(phone_number[:-4])) # return (len(phone_number) - 4) * "*" + phone_number[-4:] print(solution("01033334444") == "*******4444") print(solution("027778888") == "*****8888") ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/Jaewon0702.py ================================================ def solution(phone_number): return "*" * (len(phone_number) - 4) + phone_number[-4:] print(solution("01033334444") == "*******4444") print(solution("027778888") == "*****8888") ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12948 ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/develop-sell.js ================================================ function solution(phone_number) { let len = phone_number.length; return phone_number.split('') .map((value, index) => (len - index <= 4 ? value : "*")) .join(''); } // 문제풀이: // phone_number str를 한 글자씩 split하고, // 같은 사이즈의 배열의 조건에 따라 요소 값만 변하니까 map함수를 사용했다. // 그래서 배열의 전체 사이즈에서 인덱스("index")를 뺀 값이 4 이하인 경우만 // 실제 값("value")를, 아니면 "*"를 반환하도록 했다. // 마지막으로 join('')으로 배열을 다시 str로 만들어준다. // 프로그래머스 풀이: // //1 정규식 // return s.replace(/\d(?=\d{4})/g, "*"); // 참고: https://beomy.tistory.com/21 // //2 repeat // var result = "*".repeat(s.length - 4) + s.slice(-4); // 맨 뒤 4자리 빼고 앞 부분 : (s.length - 4) // 만큼은 repeat 함수를 통해 "*"를 반복해서 str를 만들어준다. // 그 다음 뒤에 slice 함수를 통해, 맨 뒤 4자리를 짤라서 붙인다. // slice는 '음수'가 지원되니 slice를 쓰는 것을 추천한다 (즉, 뒤에서부터 index하는 것도 가능) <=> substr ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/dkdlelk99.py ================================================ def solution(phone_number): answer = phone_number.replace(phone_number[0:-4],'*'*len(phone_number[0:-4])) return answer print(solution('0222925077') == '******5077') print(solution('01092295169') == '*******5169') ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/12948 * * @param phone_number, 전화번호 문자열 , 길이 4 ~ 20 * @return 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열 */ function solution(phone_number) { const len = phone_number.length; if (len === 4) return phone_number; const standard = len - 4; return ''.padEnd(standard, '*') + phone_number.slice(standard, len); } // 프로그래머스 정규식 function hide_numbers(s) { return s.replace(/\d(?=\d{4})/g, "*"); } // 프로그래머스 repeat function hide_numbers(s){ return "*".repeat(s.length - 4) + s.slice(-4); } console.log(solution('01033334444') === '*******4444'); console.log(solution('027778888') === '*****8888'); console.log(solution('2777') === '2777'); // 옛날에 푼 것 function solution2(phone_number) { let len = phone_number.length; return Array(len - 3).join('*') + phone_number.slice(len - 4, len); } ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/khw970421.js ================================================ function solution(phone_number) { let answer = '',a=[]; answer = phone_number.split('').splice(phone_number.length-4,4,'*') for(let i=0;i #include using namespace std; string solution(string phone_number) { for(int i = 0, len = phone_number.length(); i < len - 4; i++) { phone_number[i] = '*'; } return phone_number; } ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/s2uyeoii_c.cpp ================================================ #include #include #include #include // 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요. char* solution(const char* phone_number) { // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요. char* answer = (char*)malloc(1); //char size 할당 strcpy(answer, phone_number); for(int i = 0, len = strlen(phone_number); i < len - 4; i++) answer[i] = '*'; return answer; } ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12948 핸드폰 번호 가리기 [풀이] 1. join, for 사용 ''' def solution(phone_number): return ''.join(['*' for i in phone_number[:-4]]) + phone_number[-4:] ''' 사실, 길이곱이 더 간단하다는 걸 생각하지 못했다니 return "*"*(len(s)-4) + s[-4:] ''' ================================================ FILE: programmers/난이도별/level01.핸드폰_번호_가리기/sjjyy.java ================================================ package 난이도별.level01.핸드폰_번호_가리기; public class sjjyy { public static String solution(String phone_number) { StringBuilder answer = new StringBuilder(); for (int i = 0 ; i < phone_number.length(); i++) { if (i < phone_number.length() - 4) answer.append("*"); else answer.append(phone_number.charAt(i)); } return answer.toString(); } public static void main(String [] args) { System.out.println(solution("01012345678")); // *******5678 System.out.println(solution("026081128")); // *****1128 } } ================================================ FILE: programmers/난이도별/level01.행렬의_덧셈/6047198844.py ================================================ def solution(arr1, arr2): return [[a+b for a, b in zip(a_1, a_2)] for a_1, a_2 in zip(arr1, arr2)] ================================================ FILE: programmers/난이도별/level01.행렬의_덧셈/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12950 문제 : 행렬의 덧셈 중첩 for문을 이용하여 리스트 원소 값을 하나하나 더하였습니다. 다른 사람 풀이에 numpy를 이용하여 간단하게 더하는 탐나는 방법이 있어 메모 [메모메모] import numpy as np A = np.array(arr1) B = np.array(arr2) answer = A+B return answer.tolist() ''' def solution(arr1, arr2): answer = [[] for x in range(len(arr1))] for i in range(len(arr1)) : for j in range(len(arr1[i])) : answer[i].append(arr1[i][j] + arr2[i][j]) return answer ================================================ FILE: programmers/난이도별/level01.행렬의_덧셈/HyeonJeong.py ================================================ def solution(arr1, arr2): answer = arr1 for i, x in enumerate(arr2): for j, y in enumerate(x): answer[i][j] += y return answer print( solution([[1,2],[2,3]], [[3,4],[5,6]]) == [[4,6],[7,9]], solution([[1],[2]], [[3],[4]]) == [[4],[6]] ) ================================================ FILE: programmers/난이도별/level01.행렬의_덧셈/Jaewon0702.py ================================================ def solution1(arr1, arr2): return [ [arr1[i][j] + arr2[i][j] for j in range(len(arr1[0]))] for i in range(len(arr1)) ] import numpy as np def solution2(arr1, arr2): return (np.array(arr1) + np.array(arr2)).tolist() print(solution1([[1, 2], [2, 3]], [[3, 4], [5, 6]]) == [[4, 6], [7, 9]]) print(solution2([[1, 2], [2, 3]], [[3, 4], [5, 6]]) == [[4, 6], [7, 9]]) ================================================ FILE: programmers/난이도별/level01.행렬의_덧셈/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12950 ================================================ FILE: programmers/난이도별/level01.행렬의_덧셈/develop-sell.js ================================================ function solution(arr1, arr2) { let out_len = arr1.length; let in_len = arr1[0].length; let array = []; for(let i = 0; i < out_len; i ++){ let temp = [] for(let j = 0; j < in_len; j++){ temp.push(arr1[i][j] + arr2[i][j]); } array.push(temp) } return array; } // 문제풀이: // 빈 배열에 더한 값을 temp 변수에 넣고, temp를 // 다시 배열에 push하는 방식으로 구현함. // 해결 안된 점: // 맨 처음에는 temp에 push하지 않고, array[i]에 바로 push하도록 했는데, // 값이 이상하게 들어가서 못 풀었습니다. // let array = Array(out_len).fill([]); // for(let i = 0; i < out_len; i ++){ // for(let j = 0; j < in_len; j++){ // array[i].push(arr1[i][j] + arr2[i][j]); // } // } // 혹시 위 방식이 왜 안되는지 알 수 있을까요?? // 한줄 풀이: // return A.map((a,i) => a.map((b, j) => b + B[i][j])); // 여기선 A부터 map으로 접근하고, 그 후에 또 다시 나온 값 a 배열의 map을 // 또 걸어서 그 값인 b에 B배열의 i,j 인덱스에 해당되는 값을 더한 배열을 return하도록 했다. ================================================ FILE: programmers/난이도별/level01.행렬의_덧셈/dkdlelk99.py ================================================ def solution(arr1, arr2): answer = [] for i in range(len(arr1)): temp = [] for j in range(len(arr1[0])): temp.append(arr1[i][j]+arr2[i][j]) answer.append(temp) return answer print(solution( [[1, 2], [2, 3]], [[3, 4], [5, 6]]) == [[4, 6], [7, 9]]) print(solution( [[1], [2]], [[3], [4]]) == [[4], [6]]) ================================================ FILE: programmers/난이도별/level01.행렬의_덧셈/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12950 행렬의 덧셈 [풀이] 1. shape이 같은 리스트 더하기 2. zip 이용 ''' def solution(arr1, arr2): answer = [] for i in range(len(arr1)): answer += [[j+k for j, k in zip(arr1[i], arr2[i])]] return answer ''' 실제로 구성해보고 싶던 코드는 def solution(arr1, arr2): return [[a + b for a, b in zip(c, d)] for c, d in zip(arr1, arr2)] ''' ================================================ FILE: programmers/난이도별/level01.행렬의_덧셈/sjjyy.java ================================================ package 난이도별.level01.행렬의_덧셈; import java.util.Arrays; public class sjjyy { public static int[][] solution(int[][] arr1, int[][] arr2) { int[][] answer = new int[arr1.length][arr1[0].length]; for (int i = 0 ; i < arr1.length ; i++) { for (int j = 0 ; j < arr1[0].length ; j++) answer[i][j] = arr1[i][j] + arr2[i][j]; } return answer; } public static void main(String [] args) { int[][] arr1 = { { 1, 2 }, { 2, 3 } }; int[][] arr2 = { { 3, 4 }, { 5, 6 } }; System.out.println(Arrays.deepToString(solution(arr1, arr2))); // [[4, 6], [7, 9]] } } ================================================ FILE: programmers/난이도별/level02.124_나라의_숫자/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12899 ================================================ FILE: programmers/난이도별/level02.124_나라의_숫자/dkdlelk99.py ================================================ def solution(n): answer = "" while n > 0: n -= 1 answer = '124'[n%3] + answer n //= 3 return answer print(solution(1), solution(1) == '1') print(solution(2), solution(2) == '2') print(solution(3), solution(1) == '4') print(solution(4), solution(1) == '11') ================================================ FILE: programmers/난이도별/level02.124_나라의_숫자/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42583 124 나라의 숫자 [풀이] 1. 1 2 4의 3진법으로 10진수 표현하기 2. 나머지에 대하여 역순으로 4, 1, 2 매칭하기. => 이 때, 3의 배수에 대해서는 인덱스를 1씩 줄여줄 것. ''' def solution(n): numbers = ['4', '1', '2'] answer = '' while n: answer = numbers[n % 3] + answer n = n // 3 - (n % 3 == 0) return answer ''' ''' ================================================ FILE: programmers/난이도별/level02.124_나라의_숫자/sjjyy.java ================================================ package programmers.난이도별.level02.prefix_124_나라의_숫자; public class sjjyy { // 3진법 활용, 몫 + 나머지 public static String solution(int n) { String answer = ""; while (n > 0) { int num = n % 3; n /= 3; if (num == 0) { num = 4; n--; } answer = num + answer; } return answer; } public static String solution2(int n) { // 다른 사람 풀이 String[] num = {"4", "1", "2"}; String answer = ""; while (n > 0) { answer = num[n % 3] + answer; n = (n - 1) / 3; } return answer; } public static void main(String[] args) { int a = 19; System.out.println(solution(a)); // 141 System.out.println(solution2(a)); // 141 System.out.println(solution(1)); // 1 System.out.println(solution(2)); // 2 System.out.println(solution(3)); // 4 System.out.println(solution(4)); // 11 System.out.println(solution(5)); // 12 System.out.println(solution(6)); // 14 System.out.println(solution(7)); // 21 System.out.println(solution(8)); // 22 System.out.println(solution(9)); // 24 System.out.println(solution(10)); // 41 } } ================================================ FILE: programmers/난이도별/level02.124_나라의_숫자/turquoiseluv.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12899 124로만 구성된 나라이므로, 1->1 2->2 3->4(예시에 나옴)으로 대체 가능하기 때문에, 123으로 변환을 한 뒤 규칙을 찾는 방법을 선택했다. 여기서 해당 규칙이 0이 없는 3진법이라는 것을 발견하여, 1) 3개의 숫자로 구성하기 위해 3진법으로 숫자를 변환 2) 첫자리를 제외하고 0이 없을 때까지 자리 내림으로 while 루프 3) 해당 수를 [1, 2, 3]에서 [1, 2, 4]로 대체 4) join한 값 반환 수학적으로 접근하여 나머지+몫을 이용한 수식화로 바로 푸는 방법도 있다. def change124(n): num = ['1','2','4'] answer = "" while n > 0: n -= 1 answer = num[n % 3] + answer n //= 3 return answer ''' n = 4 def convert(n, base): T = "0123456789ABCDEF" q, r = divmod(n, base) if q == 0: return T[r] return convert(q, base) + T[r] def solution(n): x = convert(n, 3) x = list(map(int, x)) while 0 in x[1:]: for i in range(1, len(x)): if x[i] == 0: x[i-1] -= 1 x[i] += 3 if x[0] == 0: x = x[1:] for i in range(len(x)): if x[i] == 3: x[i] = '4' return ''.join(map(str,x)) print(solution(n)) ================================================ FILE: programmers/난이도별/level02.2개_이하로_다른_비트/6047198844.py ================================================ def solution(numbers): answer = [] for number in numbers: #0이 위치하는 자리수. zero_digit = 0 #0을 발견할때까지. while number & (1 << zero_digit) != 0: zero_digit += 1 res = number #0의 자리수를 1로 변경한다. res |= 1 << zero_digit #1의 자리수를 0으로 변경한다. if zero_digit != 0: res ^= 1 << (zero_digit - 1) answer.append(res) return answer ================================================ FILE: programmers/난이도별/level02.2개_이하로_다른_비트/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/77885 2개 이하로 다른 비트 [풀이] 1. 비트 조작 ''' def solution(numbers): result = [] for number in numbers: if number % 2 == 0: result.append(number + 1) continue bit = '0' + format(number, 'b') for idx, val in enumerate(bit[::-1], 1): if val == "0": break idx = len(bit) - idx bit = bit[:idx] + bit[idx + 1] + bit[idx] + bit[idx + 2:] result.append(int(bit, 2)) return result ''' 짝수일 경우는 바로 +1 한 수가 되고 홀수일 경우는 1. 제일 오른쪽 자리부터 2. 1이 연속으로 나오다 끝난 자리를 찾고 3. 이 자리와 그 왼쪽에 있는 0을 바꾼 수가 된다. 10진수를 2진수로 변환 : format(num, 'b') 2진수를 10진수로 변환 : int(str, 2) 처음에는 아래 코드처럼 접근했는데, 테스트 10, 11에서 시간초과. 컴퓨터 식 풀이가 아니라 규칙을 찾아야 되는 문제라고 생각이 드는 시점 def solution(numbers): result = [] for number in numbers: n = number number_str = format(number, 'b') while True: n += 1 n_str = format(n, 'b') if len(n_str) > len(number_str): number_str = '0'*(len(n_str)-len(number_str)) + number_str if [int(a!=b) for a, b in zip(n_str, number_str)].count(1) <= 2: result.append(n) break return result 다음 코드는 보수를 이용한 코드. 2의 보수와 2를 xor하면 1이 연속되다가 끊기는 부분의 인덱스를 얻을 수 있는 것 같다 def solution(numbers): answer = [] for idx, val in enumerate(numbers): answer.append(((val ^ (val+1)) >> 2) +val +1) return answer ''' ================================================ FILE: programmers/난이도별/level02.H-Index/HyeonJeong.py ================================================ def solution(citations): list = [] cit = sorted(citations, reverse = True) for m in range(len(cit)+1): max = 0 for n in cit: if n < m: break max += 1 if max >= m: list += [m] list.sort() return list[-1] print(solution([3, 0, 6, 1, 5]) == 3) ================================================ FILE: programmers/난이도별/level02.H-Index/Jaewon0702.py ================================================ def solution(citations): citations.sort(reverse=True) for h in range(max(citations),-1,-1) : for cite in range(len(citations)) : if (citations[cite]>=h) : if (cite+1>=h) : return h break #100점 ================================================ FILE: programmers/난이도별/level02.H-Index/README.md ================================================ #출처 https://programmers.co.kr/learn/courses/30/lessons/42747 ================================================ FILE: programmers/난이도별/level02.H-Index/dkdlelk99.py ================================================ def solution(citations): a = [] for h in range(max(citations)): cnt = 0 # 논문 개수 for nonmun in citations: if nonmun >= h: cnt += 1 a.append(h) if cnt < h: return a[h - 1] return 0 print(solution([3, 0, 6, 1, 5]), solution([3, 0, 6, 1, 5]) == 3) ================================================ FILE: programmers/난이도별/level02.H-Index/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42747?language=javascript function solution(citations) { for (let h = Math.max(...citations); h > -1 ; h--) if (citations.filter(v => v >= h).length >= h) return h return 0 } console.log(solution([3, 0, 6, 1, 5]), 3) console.log(solution([22, 42]), 2) ================================================ FILE: programmers/난이도별/level02.H-Index/khw970421.js ================================================ //성공은 했으나 코드 좀 부족 function solution(citations) { var answer = 0; let a = []; let b = []; citations.sort((A, B) => A - B); for (let i = citations.length; i > 0; i--) { for (let j = 0; j < citations.length; j++) { if (citations[j] >= i) { a = citations.slice(0, j); b = citations.slice(j, citations.length); if (a.length <= i && b.length >= i) { return i; } } } } return 0; } //다른사람 코드 function solution(citations) { citations = citations.sort(sorting); var i = 0; while (i + 1 <= citations[i]) { i++; } return i; function sorting(a, b) { return b - a; } } /* 개인적으로 문제가 조금 이상하다고 느낀다. 예를 들어 [10,9,8,7,6,5,4,3,2,1,1,1,1]이 주어진다면 실행한 결과값이 5가 나오지만 '어떤 과학자가 발표한 논문 n편 중, h번 이상 인용된 논문이 h편 이상이고 나머지 논문이 h번 이하 인용되었다면 h의 최댓값이 이 과학자의 H-Index입니다.' 라고 주어진 문제에서 이 부분에서 5번 이하로 인용이 되지않으므로 위에서 제시한 코드들이 문제가 될거라 생각이된다. 아마 1,1,1,1 이러한 것이 없이 서로 다른 인용횟수 라고 정해진다면 문제가 없을거라 생각한다. */ //출처 : https://programmers.co.kr/learn/courses/30/lessons/42747# ================================================ FILE: programmers/난이도별/level02.H-Index/rockmiin.py ================================================ def solution(citations): citations.sort(reverse=True) for i, j in enumerate(citations): if i>=j: return i return len(citations) print( solution([10, 50, 100, 100])==4 ) ================================================ FILE: programmers/난이도별/level02.H-Index/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42747# H-Index 1. 문제 설명대로 비교. 1000편 이하이므로 2중 반복문 사용 가능. 2. all을 사용해서 i <=j 와 j >= i를 모두 만족하면 return ''' def solution(citations): citations.sort(reverse=True) for i in range(len(citations), 0, -1): if all([j >= i for j in citations[:i]]) and all([j <= i for j in citations[i:]]): return i return 0 ''' 세상에 고수는 많다.. 1) 이중 반복문을 안써도 되는 비교 def solution(citations): citations = sorted(citations) l = len(citations) for i in range(l): if citations[i] >= l-i: return l-i return 0 2) ㄹㅇ 고인물. 응용력이 말도 안됨 def solution(citations): citations.sort(reverse=True) answer = max(map(min, enumerate(citations, start=1))) return answer ''' ================================================ FILE: programmers/난이도별/level02.H-Index/sjjyy.java ================================================ package programmers.난이도별.level02.H_Index; import java.util.Arrays; public class sjjyy { public static int solution(int[] citations) { int answer = 0; int len = citations.length; Arrays.sort(citations); for (int i = 0; i < len; i++) { int h = len - i; answer = Math.max(answer, Math.min(citations[i], h)); /* if ( h <= citations[i]) { answer = h; break; } */ } return answer; } public static int solution2(int[] citations) { int answer = 0; int len = citations.length; Arrays.sort(citations); for (int i = 0; i < len; i++) { int h = len - i; answer = Math.max(answer, Math.min(citations[i], h)); /* if ( h <= citations[i]) { answer = h; break; } */ } return answer; } public static void main(String[] args) { int[] citations = {3, 0, 6, 1, 5}; System.out.println(solution(citations)); // 3 System.out.println(solution2(citations)); // 3 } } ================================================ FILE: programmers/난이도별/level02.JadenCase_문자열_만들기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12951# 문제 : JadenCase 문자열 만들기 처음에는 s = [x[0].upper()+x[1:] for x in s]로 풀었는데 공백이 여러개일 때 에러가 발생해서 try, except 문을 사용해줬습니다. 예전에 level01에서도 공백 때문에 성가신 문제가 있었는데 여러 케이스를 잘 고려해야 되겠네요 ''' def solution(s): s = s.lower().split(' ') for i in range(len(s)) : try : s[i] = s[i][0].upper()+s[i][1:] except : continue return ' '.join(s) ================================================ FILE: programmers/난이도별/level02.JadenCase_문자열_만들기/HyeonJeong.py ================================================ def solution(s): tmp = 0 answer = "" list = [] for i, c in enumerate(s.lower()): if c == ' ': tmp = i+1 answer += c.upper() if tmp == i and c.isalpha() == 1 else c return answer print( solution("3people unFollowed me") == "3people Unfollowed Me", solution("for the last week") == "For The Last Week" ) ================================================ FILE: programmers/난이도별/level02.JadenCase_문자열_만들기/README.md ================================================ #출처 https://programmers.co.kr/learn/courses/30/lessons/12951 ================================================ FILE: programmers/난이도별/level02.JadenCase_문자열_만들기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12951 JadenCase 문자열 만들기 [풀이] 1. RE 사용 ''' import re def solution(s): idx = [i.span()[1]-1 for i in re.finditer('\s\w', s)] s = list(s[0].upper()+s[1:].lower()) for i in idx: s[i] = s[i].upper() return ''.join(s) ''' 처음에는 아래처럼 풀었는데, 공백의 크기도 고려해야 해서 결국 split을 사용하지 못했다. def solution(s): return ''.join(map(lambda x : str(x[0]).upper()+x[1:].lower()+' ', s.split()))[:-1] 정규식을 안쓰더라도 다음과 같이 간단하게 할 수 있었을 것 같긴하다. 라이브러리 의존도가 높아진 느낌 def solution(s): line = s[0].upper() for idx, c in enumerate(s[1:]): if s[idx-1] == " ": line += s[idx].upper() else: line += s[idx].lower() return line ''' ================================================ FILE: programmers/난이도별/level02.N개의_최소공배수/6047198844.cpp ================================================ #include #include #include #include #include using namespace std; bool prime[101]; // false면 소수 void Sieve() { memset(prime, false, sizeof(bool) * 101); prime[0] = prime[1] = true; for (int i = 2; i <= 100; i++) { if (!prime[i]) { for (int j = i+i; j <= 100; j += i) prime[j] = true; } } } int solution(vector arr) { int answer = 1; Sieve(); map mp; for (int num : arr) { map tmp_mp; for (int i = 1; num!=1; i++) { if (!prime[i]) { while (!(num % i)) { tmp_mp[i]++; num /= i; } } } for (auto m : tmp_mp) { mp[m.first] = mp[m.first] > m.second ? mp[m.first] : m.second; } } for (auto m : mp) answer *= pow(m.first, m.second); return answer; } ================================================ FILE: programmers/난이도별/level02.N개의_최소공배수/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12953 문제 : N개의 최소공배수 예전에 리뷰에서 최소공배수는 (두 수의 곱 // 최대공약수)라고 알려줬었는데 새까맣게 잊어버리고 뻘짓 했습니다..ㆆ_ㆆ 다른 사람들 풀이를 보니 gcd로 바로 약수를 구할수도 있더라구요!!! [메모메모] 1. from math import gcd 2. a*b // gcd(a,b) 앞으로 최소공배수는 더 편하게 풀수 있도록 연습해야겠어요 ''' def solution(arr): for i in range(len(arr)-1) : temp_lcm = lcm(arr[i],arr[i+1]) arr[i+1] = temp_lcm return arr[-1] def lcm(a,b) : if b%a==0 : return b gcd = 1 for i in range(min(a,b),0,-1) : if a%i==0 and b%i==0 : gcd = i break return gcd*(a//gcd)*(b//gcd) ================================================ FILE: programmers/난이도별/level02.N개의_최소공배수/rockmiin.py ================================================ def minimize(x, y): for i in range(y, (x+1) * y, y): if i % x == 0: return i def solution(arr): answer=1 arr= sorted(arr) for i in range(len(arr)): answer= minimize(answer, arr[i]) return answer solution([2, 6, 8, 14]) ================================================ FILE: programmers/난이도별/level02.N개의_최소공배수/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12953 N개의 최소공배수 [풀이] 1. GCD 사용 ''' from math import gcd def solution(arr): a = arr[0] for b in arr[1:]: a = a * b // gcd(a, b) return a ''' ''' ================================================ FILE: programmers/난이도별/level02.[1차]_프렌즈4블록/6047198844.cpp ================================================ #include #include #include using namespace std; //세로로 string 배열에 넣는다. //우 , 하, 좌하를 check한다. size체크가 중요할듯. //없앨것이 있다면 해당 주변을 먼저 체크한뒤 한번에 없앤다. //없앨것이 없다면 (m*n) - string 배열 크기의 합을 반환한다. int alpha_x[4] = { 0, 1,0,1 }; int alpha_y[4] = { 0, 0,1,1 }; int del_board(int m, int n, vector < string > &board) { //지우기 체크 bool check_board[30][30]; memset(check_board, false, sizeof(bool) * 30 * 30); bool check = false; for (int x = 0; x < n - 1; x++) { for (int y = 0; y < m - 1; y++) { bool equal_check = true; for (int i = 1; i < 4; i++) if (board[x][y]==' '||board[x][y] != board[x + alpha_x[i]][y + alpha_y[i]]) { equal_check = false; break; } if (equal_check) { check = true; for (int i = 0; i < 4; i++) check_board[x + alpha_x[i]][y + alpha_y[i]] = true; } } } //지운것이 없다면 지운 누적값을 반환한다. if (!check) { int cnt = 0; for (int y = 0; y < m; y++) { for (int x = 0; x < n; x++) { if (board[x][y] == ' ') cnt++; } } return cnt; } //내린다. //check_board의 true값을 모두 ' '으로 변환한다. for (int y = m - 1; y >= 0; y--) for (int x = 0; x < n; x++) if (board[x][y]!=' '&&check_board[x][y]) { board[x].erase(y, 1); board[x].push_back(' '); } return del_board(m, n, board); } int solution(int m, int n, vector board) { int answer = 0; vector col_board; for (int x = 0; x < n; x++) { string temp; for (int y = m - 1; y >= 0; y--) { temp += board[y][x]; } col_board.push_back(temp); } answer = del_board(m, n, col_board); return answer; } int main() { solution(4, 5, { "AAAAA", "AUUUA", "AUUAA", "AAAAA" }); } ================================================ FILE: programmers/난이도별/level02.[3차]_방금_그곡/6047198844.cpp ================================================ #include #include #include #include #include using namespace std; /* musicinfors[i] = 음악의 재생시간,음악의 종료시간,실제음 끝까지 하나의 연속이라도 없으면 탈출 #가 있는지 판단 */ bool compare(pair, string>& a, pair, string>& b) { //running_time / 들어온 순서 / 반환값 if (a.first.first != b.first.first) return a.first.first > b.first.first; return a.first.second < b.first.second; } string solution(string m, vector musicinfos) { vector , string> > res_string; int musicinfos_size = musicinfos.size(); //모든 음악정보를 탐색한다. for (int i = 0; i < musicinfos_size; i++) { vector token_string; char temp[5000]; strcpy(temp, musicinfos[i].c_str()); char* tok; tok = strtok(temp, ","); while (tok) { string temp; temp += tok; token_string.push_back(temp); tok = strtok(NULL, ","); } int hour = stoi(token_string[1].substr(0, 2)) - stoi(token_string[0].substr(0, 2)); int minute = stoi(token_string[1].substr(3, 2)) - stoi(token_string[0].substr(3, 2)); int running_time = hour * 60 + minute; //C#는 / D# / F# / G# / A#를 치환한다. string current_music; string memory_music; int memory_size = m.size(); for (int i = 0; i < memory_size - 1; i++) { if (m[i + 1] == '#') memory_music += (m[i++] + 30); else memory_music += m[i]; } if (m[memory_size - 1] != '#') memory_music += m[memory_size - 1]; int current_size = token_string[3].size(); for (int i = 0; i < current_size - 1; i++) { if (token_string[3][i + 1] == '#') current_music += (token_string[3][i++] + 30); else current_music += token_string[3][i]; } if (token_string[3][current_size - 1] != '#') current_music += token_string[3][current_size - 1]; bool check = false; int current_music_idx = 0; int memory_music_idx = 0; int current_music_size = current_music.size(); int memory_music_size = memory_music.size(); int temp_current_music_idx = 0; for (; current_music_idx < running_time; current_music_idx++) { if (current_music[current_music_idx % current_music_size] == memory_music[memory_music_idx]) { memory_music_idx++; if (memory_music_idx == memory_music_size) { check = true; break; } } else { memory_music_idx = 0; current_music_idx = temp_current_music_idx++; } } if (check) res_string.push_back({ { running_time,i }, token_string[2] }); } if (!res_string.size()) return "(None)"; sort(res_string.begin(), res_string.end(), compare); return res_string[0].second; } int main() { cout << solution("ABC", { "12:00,12:14,cdcdf,cdcdcdf", "12:00,12:15,CORRECT,CDEFGAB","12:00,12:14,HELLO,CDEFGAB","12:00,12:14,HELLO,CDEFGAB" }); } ================================================ FILE: programmers/난이도별/level02.[3차]_방금_그곡/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17683 방금그곡 [풀이] 1. replace로 대문자#을 소문자로 변경. ''' def solution(m, musicinfos): m = m.replace('C#', 'c') .replace('D#','d') .replace('F#','f') .replace('G#','g') .replace('A#','a') answer = [] for i in musicinfos: start, end, title, score = i.split(',') time = (int(end[:2])-int(start[:2])) * 60 + int(end[3:])-int(start[3:]) score = score.replace('C#', 'c').replace('D#','d').replace('F#','f').replace('G#','g').replace('A#','a') score = score * (time // len(score)) + score[:time%len(score)] if score.find(m) != -1: answer.append([title,time]) return sorted(answer, key=lambda x : -x[1])[0][0] if answer else "(None)" ''' replace를 계속 쓰는게 맘에 안들었는데, 다른 사람들도 별 방법이 없었나보다. 억지로 re를 쓰거나 함수를 만드는 것보다는 깔끔한 듯 싶다. ''' ================================================ FILE: programmers/난이도별/level02.[3차]_압축/6047198844.cpp ================================================ #include #include #include #include using namespace std; //to_string은 int를 string으로. vector solution(string msg) { vector answer; map mp; for (char i = 'A'; i <= 'Z'; i++) { string alpha; alpha += i; mp[alpha] = i - 'A' + 1; } int cnt = 27; //끝에 도달할때까지, 끝에 도달하면 그냥 출력한다.(등록X) int msg_size = msg.size(); string res; for (int idx = 0; idx < msg_size; idx++) { res += msg[idx]; if (mp.find(res) != mp.end()) continue; mp[res] = cnt++; answer.push_back(mp[res.substr(0, res.size() - 1)]); res = ""; idx--; } answer.push_back(mp[res]); return answer; } int main() { solution("TOBEORNOTTOBEORTOBEORNOT"); } ================================================ FILE: programmers/난이도별/level02.[3차]_압축/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17684 압축 [풀이] 1. 가장 긴 문자열부터 확인한다. dict 사용. ''' def solution(msg): dic = {chr(i + 65): i + 1 for i in range(26)} length = len(msg) num = 27 answer = [] idx = 0 while idx < length: for i in range(length, idx, -1): if msg[idx:i] in dic.keys(): answer.append(dic[msg[idx:i]]) dic[msg[idx:i + 1]] = num num += 1 idx = i break return answer ''' ''' ================================================ FILE: programmers/난이도별/level02.[3차]파일명_정렬/6047198844.cpp ================================================ #include #include #include using namespace std; bool compare(pair, string> a, pair, string> b) { if (a.first.first != b.first.first) return a.first.first < b.first.first; return a.first.second < b.first.second; } vector solution(vector files) { vector answer; //HEAD , NUMBER , 해당 string으로 저장한다. vector ,string> > res; //대문자는 소문자로 변경한다. int cnt = 0; for (string s : files) { int idx = 0; string head; for (; ('0' > s[idx] || s[idx] > '9'); idx++) { head += 'A' <= s[idx] && s[idx] <= 'Z' ? s[idx] - 'A' + 'a' : s[idx]; } string number; for (; '0' <= s[idx] && s[idx] <= '9';idx++) { number += s[idx]; } res.push_back({ {head,stoi(number)},s }); } stable_sort(res.begin(), res.end(), compare); for (auto temp : res) answer.push_back(temp.second); return answer; } int main() { solution({ "img1.png", "IMG01.GIF", "img02.png", "img2.JPG", "img10.png", "img12.png" }); } ================================================ FILE: programmers/난이도별/level02.[3차]파일명_정렬/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17686 파일명 정렬 [풀이] 1. 정규식 사용. 이후 3개의 부분으로 분리 후 정렬. 공백도 문자라는 것을 주의 ''' import re def solution(files): head = re.compile('[-. a-zA-z]+') number = re.compile('[0-9]+') newfiles = [] for file in files: _, h = re.search(head, file).span() _, n = re.search(number, file).span() newfiles.append([file[:h], file[h:n], file[n:]]) return [''.join(i) for i in sorted(newfiles, key=lambda f: (f[0].lower(), int(f[1])))] ''' re.search 대신 findall을 사용할 수 있음 [-. a-zA-z]대신 \d를 사용할 수 있음 ''' ================================================ FILE: programmers/난이도별/level02.n진수_게임/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/17687# 문제 : [3차] n진수 게임 ''' def solution(n, t, m, p): num = [x for x in range(1,t*m)] # n진수 만들 개수(그냥 for문에서 범위 지정해도 됐었네요) over = ['A','B','C','D','E','F'] # 10 이상일 때 알파벳으로 바꿔주기 rule = '0' for i in num : temp = '' while i>0 : # n진수로 만들기 if i%n >= 10 : temp += over[(i%n)%10] # 나머지가 10 이상일 때는 over 리스트 이용해서 알파벳으로 변환 else : temp += str(i%n) # 나머지가 10 미만일 때는 그대로 += i //= n rule += temp[::-1] # 반대로 뒤집어서 합쳐줍니다 return rule[p-1:t*m:m] # 다른 사람들 풀이 : rule[p-1::m][:t] ================================================ FILE: programmers/난이도별/level02.n진수_게임/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17687 N진수 게임: 수학벌레들의 미친게임 미리 진수를 모두 구해놓은 뒤 해당 리스트에서 적절한 인덱스만 고른다. ''' from itertools import product def solution(n, t, m, p): size = 2 txt = [i for i in range(n)] while len(txt) < t * m: tmp = [i for i in product(range(n), repeat = size)][n**(size-1):] txt.extend([j for i in tmp for j in i]) size += 1 order = 0 dic = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'][:n] answer = ''.join(map(str, [dic[txt[i*m+p-1]%n] for i in range(t)])) return answer ''' 나도 이 함수 쓰고 싶었는데, 시간 초과 났다. def convert(n, base): T = "0123456789ABCDEF" q, r = divmod(n, base) if q == 0: return T[r] else: return convert(q, base) + T[r] 다른 사람들은 다 쓰네. 억울하다! 아마도 모든 수에대해 사용하는 것이 아니라, 자릿수가 바뀌기 전까지 사용해야 됐던 것 같다. 또는 내가 풀었듯이 미리 구해 놓는게 하나의 방법이었던 것 같다. 다음은 convert를 사용해서 미리 구해놓고 풀이 def convert(m,n): total = "0123456789ABCDEF" i,j = divmod(m,n) if i ==0: return total[j] return convert(i,n)+total[j] def solution(n, t, m, p): total = '' answer='' total = sum([convert(i,n) for i in range(t*m)]) for i in range(t): idx = p-1 + i*m answer +=total[idx] return answer ''' ================================================ FILE: programmers/난이도별/level02.가장_큰_수/6047198844.cpp ================================================ #include #include #include #include #include #include using namespace std; bool compare(string a, string b) { return (a + b) > (b + a); } string solution(vector numbers) { vector s_numbers; string answer = ""; for (auto i : numbers) s_numbers.push_back(to_string(i)); sort(s_numbers.begin(), s_numbers.end(), compare); for (auto i : s_numbers) answer += i; return answer = answer[0]!='0' ? answer : "0"; } int main() { solution({ 6,10,2 }); } ================================================ FILE: programmers/난이도별/level02.가장_큰_수/Jaewon0702.py ================================================ def solution(numbers) : biggest='' sorted_v=[] sorted_v = sorted([ str(v) * 3 for v in numbers ], reverse=True) sorted_v.sort(reverse=True) for v in sorted_v : biggest+=v[:int(len(v)/3)] if biggest[0]=='0' : return '0' return biggest #kdlelk99님의 코드를 참고하였다. #100점 ================================================ FILE: programmers/난이도별/level02.가장_큰_수/JeongShin.js ================================================ function solution(numbers) { const answer = numbers.map(c => c.toString()).sort((a, b) => (b + a) - (a + b)).join(''); return answer[0] === '0' ? '0' : answer; } ================================================ FILE: programmers/난이도별/level02.가장_큰_수/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42746 ================================================ FILE: programmers/난이도별/level02.가장_큰_수/dkdlelk99.py ================================================ def solution(numbers): answer = "" sorted_num = [] for num in numbers: sorted_num.append(str(num)*3) sorted_num = sorted(sorted_num, reverse=True) for num in sorted_num: answer += num[:int(len(num)/3)] if answer[0] == '0': return '0' return answer print(solution([6,10,2]) == '6210') print(solution([21,212]) == '21221') print(solution([999,9,998]) == '9999998') ================================================ FILE: programmers/난이도별/level02.가장_큰_수/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42746?language=javascript function solution(numbers) { const a = numbers.sort((a, b) => `${a}${b}` < `${b}${a}` ? 1 : -1).join('') return a[0] == "0" ? "0" : a; } console.log(solution([6, 10, 2]), 6210) console.log(solution([3, 30, 34, 5, 9]), 9534330) ================================================ FILE: programmers/난이도별/level02.가장_큰_수/rockmiin_가장큰수.py ================================================ def solution(num): num= list(map(str, num)) slen= len(num) for i in range(slen): num[i]*=3 # print(num) num.sort(reverse=True) for i in range(slen): num[i]=num[i][:len(num[i])//3] if num[0]=='0': return '0' return ''.join(num) print( solution([6, 2, 10]) ) ================================================ FILE: programmers/난이도별/level02.가장_큰_수/s2uyeoii.cpp ================================================ #include #include #include //주어진 원소 숫자 비교 int str_compare(int* num1, int* num2) { char num_cmp1[10] = ""; //0~10까지 char num_cmp2[10] = ""; sprintf(num_cmp1, "%d%d", *num1, *num2); //주어진 문자 문자열 저장 sprintf(num_cmp2, "%d%d", *num2, *num1); if (strcmp(num_cmp1, num_cmp2) < 0) return 1; if (strcmp(num_cmp1, num_cmp2) == 0) return 0; return -1; } // numbers_len은 배열 numbers의 길이입니다. char* solution(int numbers[], size_t numbers_len) { // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요. char nums[5] = ""; int len = 0; bool isZeroCheck = false; qsort(numbers, numbers_len, sizeof(int), str_compare); //위 비교함수대로 정렬 for (int i=0; i String [] String [] arr = new String[len]; for (int i = 0 ; i < len ; i++) arr[i] = String.valueOf(numbers[i]); // 내림차순 정렬 Arrays.sort(arr, new Comparator() { @Override public int compare(String s, String t1) { return (t1+s).compareTo(s+t1); } }); // 람다식 // Arrays.sort(arr, (s, t1) -> (t1+s).compareTo(s+t1)); // 예외처리 if (arr[0].equals("0")) return "0"; // 이어붙이기 for (String s : arr) answer += s; return answer; } public static void main(String [] args) { int[] num1 = {6, 10, 2}; int[] num2 = {3, 30, 34, 5, 9}; System.out.println(solution(num1)); // 6210 System.out.println(solution(num2)); // 9534330 } } ================================================ FILE: programmers/난이도별/level02.가장_큰_정사각형_찾기/6047198844.cpp ================================================ /* 완전탐색 방식 -> 시간 초과 -> 중복된 연산을 계속하고 있음 #include #include #include using namespace std; //정사각형인지 아닌지 탐험하는 함수 bool square(vector>& board, int y, int x, int size) { for (int check_y = y; check_y < y + size; check_y++) for (int check_x = x; check_x < x + size; check_x++) if (!board[check_y][check_x]) return false; return true; } int solution(vector> board) { int width = board[0].size(); int height = board.size(); int square_size = width > height ? height : width; while (square_size) { for (int y = 0; y <= height - square_size; y++)for (int x = 0; x <= width - square_size; x++) { if (square(board, y, x, square_size)) return square_size * square_size; } --square_size; } }*/ #include #include #include #include using namespace std; int bottom_up(vector>& board, int y_range, int x_range) { int memo[1000][1000]; memset(memo, 0, 1000 * 1000); // width (0,x_range) height (0,y_range) for (int y = 0; y <= y_range; y++) for (int x = 0; x <= x_range; x++) { if (!board[y][x]) memo[y][x] = 0; else { if (y-1 >= 0 && x-1 >= 0) { memo[y][x] = min(min(memo[y - 1][x], memo[y - 1][x - 1]), memo[y][x - 1]) + 1; } else { memo[y][x] = 1; } } } int answer = 0; for (int y = 0; y <= y_range; y++) for (int x = 0; x <= x_range; x++) if (answer < memo[y][x]) answer = memo[y][x]; return answer * answer; } int solution(vector > board) { int width = board[0].size() - 1; int height = board.size() - 1; return bottom_up(board, height, width); } ================================================ FILE: programmers/난이도별/level02.가장_큰_정사각형_찾기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12905# 문제 : 가장 큰 정사각형 찾기 진짜 엄청나게 헤맨 문제다. 사실 어떻게 풀어야 하는지 거의 외운 수준 같다. 왜 왼쪽이랑 위쪽이랑 대각선이랑 비교해서 min 값을 사용하는지 모르겠어서 설명하는 사이트를 많이 찾아봤지만 다들 푸는 방법만 알려주고 설명은 안해주고..ㄒ︿ㄒ 매번 DP 문제는 시간 오래걸리고 이해하기 어려운 듯.. DP 문제에 익숙해져야 겠다. ''' def solution(board): answer = -1 for i in range(1,len(board)) : for j in range(1,len(board[0])) : if board[i][j] == 1 : board[i][j] = min(board[i-1][j], board[i][j-1], board[i-1][j-1])+1 answer = max(answer, board[i][j]) return answer**2 if answer !=-1 else board[0][0] ================================================ FILE: programmers/난이도별/level02.가장_큰_정사각형_찾기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12905 가장 큰 정사각형 찾기 [풀이] 1. https://github.com/DKU-STUDY/Algorithm/pull/997 설명 참조 ''' def solution(board): for i in range(1, len(board)): for j in range(1, len(board[0])): if board[i][j] == 1: board[i][j] = min(board[i-1][j], board[i][j-1], board[i-1][j-1]) + 1 return max(board[i][j] for j in range(len(board[0])) for i in range(len(board))) ** 2 ''' ''' ================================================ FILE: programmers/난이도별/level02.거리두기_확인하기/6047198844.py ================================================ import collections def bfs(table): for y in range(0,5): for x in range(0,5): #bfs시작 if table[y][x] == 'P': Q = collections.deque([(y,x)]) discovered = set() discovered.add((y,x)) #조심 cnt = 0 while Q: cnt += 1 for _ in range(len(Q)): yy, xx = Q.popleft() for dy, dx in (-1,0), (+1,0), (0,-1),(0,+1): ny = yy + dy nx = xx + dx if 0 <= ny < 5 and 0 <= nx < 5 and (ny,nx) not in discovered: discovered.add((ny,nx)) if table[ny][nx] == 'O': Q.append((ny,nx)) elif table[ny][nx] == 'P' and cnt <= 2: return 0 return 1 def solution(places): answer = [] for place in places: answer.append(bfs(place)) return answer ================================================ FILE: programmers/난이도별/level02.거리두기_확인하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/81302 거리두기 확인하기 [풀이] 1. 각 places 마다 답을 내야함 => y,x = (4, 4)가 되기 이전에 반복문을 탈출하면 문제가 있는 것으로 판단 => 여기서는 break를 위해 y와 x에 대한 이중 포문보다 while을 사용했다 => for문을 사용하면 x에 대한 포문, y에 대한 포문을 계속 탈출해야함 => while문으로 하나의 반복문만 탈출하도록 함 => 함수를 선언하는 것이 좀 더 깔끔하다고 생각이 됨 (반복문은 break를 함수는 return이 가능하므로) 2. 각 좌표를 기준으로, 오른쪽과 아래 그리고 오른쪽 위와 오른쪽 아래를 살피도록 함 2-1. 오른쪽과 아래의 경우 => 바로 옆에 P가 존재 => 바로 옆에 O가 존재하고 그 옆에 P가 존재 => 위 두 경우에 대해서만 항상 거리두기에 실패한다 2-2. 오른쪽 위와 오른쪽 아래의 경우 => 대각선으로 P가 존재하는데 가로와 세로로 파티션이 존재하지 않음 => 이 한 경우에 대해서만 항상 거리두기에 실패한다 ''' def solution(places): result = [] for p in places: y = x = -1 while True: x = (x + 1) % 5 y = y + 1 if x == 0 else y if y * x >= 16: break if p[y][x] != "P": continue if x + 1 < 5: if p[y][x + 1] == "P": break elif p[y][x + 1] == "O" and x + 2 < 5 and p[y][x + 2] == "P": break if y + 1 < 5: if p[y + 1][x] == "P": break elif p[y + 1][x] == "O" and y + 2 < 5 and p[y + 2][x] == "P": break if x + 1 < 5 and y - 1 >= 0: if p[y - 1][x + 1] == "P": if p[y][x + 1] == "O" or p[y - 1][x] == "O": break if x + 1 < 5 and y + 1 < 5: if p[y + 1][x + 1] == "P": if p[y][x + 1] == "O" or p[y + 1][x] == "O": break result.append(1 if y * x >= 16 else 0) return result ''' ''' ================================================ FILE: programmers/난이도별/level02.게임_맵_최단거리/6047198844.py ================================================ import collections def solution(maps): answer = 1 n = len(maps) - 1 m = len(maps[0]) - 1 #바로 도착인 경우 if n == 0 and m == 0: return answer discovered = set() Q = collections.deque() discovered.add((0, 0)) Q.append((0, 0)) while Q: answer += 1 for _ in range(len(Q)): y, x = Q.popleft() for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny = y + dy nx = x + dx #딥 if ny == n and nx == m: return answer #범위 / 벽 / 발견 X if 0 <= ny <= n and 0 <= nx <= m and maps[ny][nx] != 0 and (ny, nx) not in discovered: discovered.add((ny, nx)) Q.append((ny, nx)) return -1 #deque.rotate(num) ================================================ FILE: programmers/난이도별/level02.게임_맵_최단거리/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/1844 게임 맵 최단거리 [풀이] 1. BFS 사용 ''' def solution(maps): n = len(maps) m = len(maps[0]) stack = [(0, 0, 1)] # 현재 있는곳도 카운트 save = [] move = [(1, 0), (-1, 0), (0, 1), (0, -1)] while True: if not stack: if not save: return -1 stack, save = save, stack y, x, cost = stack.pop() for dy, dx in move: ny, nx = y + dy, x + dx if 0 <= ny < n and 0 <= nx < m: if maps[ny][nx] == 1 or maps[ny][nx] > cost + 1: # 첫 방문 또는 현재 방문이 저비용 maps[ny][nx] = cost + 1 if ny == n - 1 and nx == m - 1: return cost + 1 save.append((ny, nx, cost + 1)) ''' from collections import deque 다음에는 컬렉션 디큐... 를 써봐야 겠다. 매일 stack, save가 습관이 되버려서.. 또, visited를 쓸 수 있지만 map 자체에 마킹을 해서 최단거리를 가는 방법도 많이 써봐야 겠다 bfs 방식이라 가능한 것 같다. ''' ================================================ FILE: programmers/난이도별/level02.고양이와_개는_몇_마리_있을까/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT ANIMAL_TYPE, COUNT(*) FROM ANIMAL_INS GROUP BY ANIMAL_TYPE ORDER BY 1 ================================================ FILE: programmers/난이도별/level02.괄호_회전하기/6047198844.py ================================================ import collections table = { '{' : '}', '[' : ']', '(' : ')' } def is_valid(word): stack = [] for char in word: if char == '[' or char == '(' or char == '{': stack.append(char) else: #stack이 비엇거나. 짝이 아닐경우. if not stack or char != table[stack.pop()]: return False if stack: return False else: return True def solution(s): answer = 0 #홀수이면 올바른 괄호 문자열이 아니다. if len(s) % 2 == 1: return answer Q = collections.deque(s) for _ in range(len(s)): answer += is_valid(''.join(Q)) Q.rotate(1) return answer ================================================ FILE: programmers/난이도별/level02.괄호_회전하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/76502 괄호 회전하기 [풀이] 1. 문자열 함수 replace 사용 ''' def solution(s): answer = 0 for i in range(len(s)): brt = s[i:] + s[:i] temp = '' while temp != brt: temp = brt brt = brt.replace('[]','').replace('{}','').replace('()','') if len(brt) == 0: answer += 1 return answer ''' 완벽하게 푼듯 하다 ''' ================================================ FILE: programmers/난이도별/level02.괄호변환/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/60058 ================================================ FILE: programmers/난이도별/level02.괄호변환/eyabc.js ================================================ const JSTestModule = require('/Users/ey/DKU/Algorithm/JSTestModule.js'); const isRightStr = (p) => { const stack = [p.charAt(0)], len = p.length; let pos = 1; while (pos < len) { const currChar = p.charAt(pos); const beforeChar = stack[stack.length - 1]; (beforeChar === '(' && currChar === ')') ? stack.pop() : stack.push(currChar); pos++; } return !!(stack.length === 0); }; const getUV = (equalStr) => { let uObj = { '(': 0, ')': 0, }; let pos = 0; do { uObj[equalStr[pos]] += 1; pos++; } while (uObj['('] !== uObj[')']); const uLen = uObj['('] * 2; return [equalStr.slice(0, uLen), equalStr.slice(uLen, equalStr.length)]; }; const divideStr = (equalStr) => { // 2. 문자열 w를 두 "균형잡힌 괄호 문자열" u, v로 분리합니다. 단, u는 "균형잡힌 괄호 문자열"로 더 이상 분리할 수 없어야 하며, v는 빈 문자열이 될 수 있습니다. const [u, v] = getUV(equalStr); // 나뉜 두 파트가 올바른 str 인지, 균형잡힌 str 인지 판별. const [isURight, isVRight] = [isRightStr(u), isRightStr(v)]; let newV = '', newU = ''; // 문자열 u가 "올바른 괄호 문자열" 이라면 문자열 v에 대해 1단계부터 다시 수행합니다. if (isURight && !isVRight) newV = solution(v); if (!isURight) { const slicedU = [...u.slice(1, u.length - 1)].map(v => v === '(' ? ')' : '(').join(''); newU = '(' + solution(v) + ')' + slicedU; return newU; } return (isURight ? u : newU) + (isVRight ? v : newV); }; function solution (p) { // 1. 입력이 빈 문자열인 경우, 빈 문자열을 반환합니다. return (p.length === 0) ? '' : divideStr(p); } JSTestModule('/Users/ey/DKU/Algorithm/programmers/카카오/괄호변환/test.json', solution); ================================================ FILE: programmers/난이도별/level02.괄호변환/junilhwang.js ================================================ // 1. 입력이 빈 문자열인 경우, 빈 문자열을 반환합니다. // 2. 문자열 w를 두 "균형잡힌 괄호 문자열" u, v로 분리합니다.단, u는 "균형잡힌 괄호 문자열"로 더 이상 분리할 수 없어야 하며, v는 빈 문자열이 될 수 있습니다. // 3. 문자열 u가 "올바른 괄호 문자열" 이라면 문자열 v에 대해 1단계부터 다시 수행합니다. // 3 - 1. 수행한 결과 문자열을 u에 이어 붙인 후 반환합니다. // 4. 문자열 u가 "올바른 괄호 문자열"이 아니라면 아래 과정을 수행합니다. // 4 - 1. 빈 문자열에 첫 번째 문자로 '('를 붙입니다. // 4 - 2. 문자열 v에 대해 1단계부터 재귀적으로 수행한 결과 문자열을 이어 붙입니다. // 4 - 3. ')'를 다시 붙입니다. // 4 - 4. u의 첫 번째와 마지막 문자를 제거하고, 나머지 문자열의 괄호 방향을 뒤집어서 뒤에 붙입니다. // 4 - 5. 생성된 문자열을 반환합니다. function solution(p) { const chk = s => { let before = s let after = before.replace(/\(\)/gi, '') while (after.length > 0) { if (before === after) return false before = after after = before.replace(/\(\)/gi, '') } return true } if (chk(p)) return p const change = (str) => { let temp = '' for (let i = 1, len = str.length; i < len - 1; i++) { temp += str[i] === '(' ? ')' : '(' } return temp } const f = str => { const len = str.length if (len === 0) return '' let u = str.substr(0, 2), v = str.substr(2), i = 0 do { if (chk(u.substr(-2)) || chk(v.substr(0, 2))) break u += v.substr(0, 2), v = v.substr(2) i += 2 } while (i < len) v = f(v) if (!chk(u)) { u = `(${v})${change(u)}` v = '' } return [u, v].join('') } return f(p) } // console.log(solution(""), "") // console.log(solution("(()())()"), "(()())()") // console.log(solution(")("), "()") console.log(solution("()))((()"), "()(())()") ================================================ FILE: programmers/난이도별/level02.괄호변환/sangmandu.py ================================================ ''' 괄호 변환 https://programmers.co.kr/learn/courses/30/lessons/60058 [풀이] 1. 문제에서 제시한 대로 풀이 ''' def bracket(p): if len(p) == 0: return '' u = v = "" bal = 0 for i in p: bal += 1 if i == "(" else -1 u += i if bal == 0: break v += p[len(u):] cnt = 0 for i in u: cnt += 1 if i == "(" else -1 if cnt < 0: break if cnt == 0: return u + bracket(v) string = "" if cnt < 0 : string += "(" + bracket(v) + ")" for i in u[1:-1]: string += "(" if i == ")" else ")" return string def solution(p): return bracket(p) ''' ''' ================================================ FILE: programmers/난이도별/level02.구명보트/6047198844.cpp ================================================ #include #include #include #include using namespace std; int solution(vector people, int limit) { int answer = 0; int p_size = people.size(); sort(people.begin(), people.end(), greater()); int min_element = p_size - 1; for (int i = 0; i <= min_element; i++) { answer++; if(people[i]+people[min_element] <= limit) { min_element--; } } return answer; } ================================================ FILE: programmers/난이도별/level02.구명보트/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42885 ### 문제 설명 무인도에 갇힌 사람들을 구명보트를 이용하여 구출하려고 합니다. 구명보트는 작아서 한 번에 최대 2명씩 밖에 탈 수 없고, 무게 제한도 있습니다. 예를 들어, 사람들의 몸무게가 [70kg, 50kg, 80kg, 50kg]이고 구명보트의 무게 제한이 100kg이라면 2번째 사람과 4번째 사람은 같이 탈 수 있지만 1번째 사람과 3번째 사람의 무게의 합은 150kg이므로 구명보트의 무게 제한을 초과하여 같이 탈 수 없습니다. 구명보트를 최대한 적게 사용하여 모든 사람을 구출하려고 합니다. 사람들의 몸무게를 담은 배열 people과 구명보트의 무게 제한 limit가 매개변수로 주어질 때, 모든 사람을 구출하기 위해 필요한 구명보트 개수의 최솟값을 return 하도록 solution 함수를 작성해주세요. ### 제한사항 무인도에 갇힌 사람은 1명 이상 50,000명 이하입니다. 각 사람의 몸무게는 40kg 이상 240kg 이하입니다. 구명보트의 무게 제한은 40kg 이상 240kg 이하입니다. 구명보트의 무게 제한은 항상 사람들의 몸무게 중 최댓값보다 크게 주어지므로 사람들을 구출할 수 없는 경우는 없습니다. ================================================ FILE: programmers/난이도별/level02.구명보트/dkdlelk99.py ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42885 # input people : 사람들의 몸무게가 담긴 배열, limit : 구명보트의 무게 제한 # output 구명보트의 최소 갯수 # 보트의 최대 수용 인원은 2명 # 구명보트 무게 제한은 언제나 사람 무게와 같거나 크다. (구출할 수 없는 경우는 없음) def solution(people, limit): answer, start, end = 0, 0, len(people) people = sorted(people) while start < end: end -= 1 answer += 1 if people[end] + people[start] <= limit: start += 1 return answer print(solution([70, 50, 80], 100) == 3, solution([70, 50, 80], 100)) print(solution([70, 50, 50, 80], 100) == 3, solution([70, 50, 50, 80], 100)) print(solution([70, 50, 80, 20, 90], 100) == 4, solution([70, 50, 80, 20, 90], 100)) print(solution([70, 10, 20, 20, 90, 50, 90, 80], 100) == 5, solution([70, 10, 20, 20, 90, 50, 90, 80], 100)) ================================================ FILE: programmers/난이도별/level02.구명보트/junilhwang.js ================================================ // 구명보트 : https://programmers.co.kr/learn/courses/30/lessons/42885?language=javascript function solution(people, limit) { const nums = people.sort((a, b) => a - b) const len = nums.length, chk = nums.map(v => 0) let cnt = 0, j = len - 1 loop: for (let i = 0; i < len; i++) { if (chk[i]) continue chk[i] = 1 for (; j > i; j--) { if (chk[j]) continue if (nums[i] + nums[j] === limit) { cnt += 1, chk[j] = 1; continue loop } if (nums[i] + nums[j] < limit) { cnt += 1, chk[j] = 1; continue loop } } cnt += 1 } return cnt; } console.log(solution([70, 50, 80, 50], 100), 3) console.log(solution([70, 80, 50], 100), 3) console.log(solution([50, 50, 60, 70], 100), 3) ================================================ FILE: programmers/난이도별/level02.구명보트/rockmiin_구명보트.py ================================================ def solution(people, limit): answer=0 people.sort(reverse=True) rear=len(people)-1 for i in range(len(people)): if people[i]+people[rear]<=limit: rear-=1; answer+=1 if i >= rear: break; return answer print( solution([70, 50, 80, 50], 100), solution([70, 80, 50], 100) ) ================================================ FILE: programmers/난이도별/level02.구명보트/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42885# 구명보트 [풀이] 1. case가 50000 이라 반복문 중첩은 어지간 하면 시간초과. => 따라서 반복문 내에 remove, del, pop은 거의 사용 불가 2. indexing 비교만으로 count => 핵심은 가장 무게가 많은 사람을 가장 무게가 적은 사람이 커버하지 못하면 어떤 사람도 커버하지 못한다는 것. => 따라서 가장 무게가 많은 사람 + 가장 무게가 적은 사람이 limit을 초과하면 무게가 많은 사람만 보트에 태운다. ''' def solution(people, limit): people.sort(reverse=True) cnt = 0 i, j = 0, len(people)-1 while i <= j: if people[i] + people[j] <= limit: j -= 1 i += 1 cnt += 1 return cnt ''' ''' ================================================ FILE: programmers/난이도별/level02.구명보트/sjjyy.java ================================================ package 난이도별.level02.구명보트; import java.util.Arrays; public class sjjyy { public static int solution(int[] people, int limit) { int answer = people.length; Arrays.sort(people); int i = 0, j = people.length - 1; while (i < j) { if (people[i] + people[j] <= limit) { answer--; i++; } j--; } return answer; } public static void main(String[] args) { int[] p1 = {70, 50, 80, 50}; int[] p2 = {70, 50, 80}; int[] p3 = {70, 10, 80, 20}; System.out.println(solution(p1, 100)); // 3 System.out.println(solution(p2, 100)); // 3 System.out.println(solution(p3, 100)); // 2 } } ================================================ FILE: programmers/난이도별/level02.기능개발/6047198844.cpp ================================================ #include #include #include using namespace std; // 100*100 = 10000 < 1억 따라서 부르트포스 vector solution(vector progresses, vector speeds) { //결과값을 저장 vector answer; //idx는 움직이면서 size에 도달하게 되면 멈춘다. int idx = 0; while (idx < progresses.size()) { for (int i = 0; i < progresses.size(); i++) progresses[i] += speeds[i]; int cnt = 0; //idx가 넘어갈경우를 고려해야함 while (idx < progresses.size()&&progresses[idx] >= 100) { cout << cnt << " "<= list[j]: list[j] = 0 answer[-1] += 1 else: break return answer print( solution([93, 30, 55], [1, 30, 5]) == [2, 1], solution([95, 90, 99, 99, 80, 99], [1, 1, 1, 1, 1, 1]) == [1, 3, 2] ) ================================================ FILE: programmers/난이도별/level02.기능개발/Jaewon0702.py ================================================ def solution(progresses, speeds): days=0; days_list=[]; publish=[] for i,p in enumerate(progresses) : #대신 speeds를 사용해도 된다. while (p+speeds[i]*days<100) : days+=1 days_list.append(days); days=0 long=days_list[0]; length=len(days_list) for i,d in enumerate(days_list) : #이 이후로 dkdlelk99님의 코드를 참고하였다. if long= 100: Q.append(count) count = 1 first = Q.popleft() for i in range(len(Q)): compare = Q.popleft() if first >= compare: count += 1 else: answer.append(count) count = 1 first = compare if Q ==[]: break answer.append(count) return answer print(solution([93,30,55], [1,30,5]), solution([93,30,55], [1,30,5]) == [2,1]) print(solution([95,90,99,99,80,99], [1,1,1,1,1,1]),\ solution([95,90,99,99,80,99], [1,1,1,1,1,1]) == [1,3,2]) ================================================ FILE: programmers/난이도별/level02.기능개발/eyabc.js ================================================ const COMPLETE = 100; const deploy = (speeds) => ({ cnt, deployDay, result }, item, k) => { const remain = COMPLETE - item; const days = Math.ceil(remain / speeds[k]); // 시작 if (k === 0) { deployDay = days; cnt += 1; } else if (days <= deployDay) { cnt += 1; } else if (days > deployDay) { result.push(cnt); cnt = 1; deployDay = days; } // 끝 if (k === speeds.length - 1) { result.push(cnt); } return { cnt, deployDay, result }; }; function solution (progresses, speeds) { const init = { cnt: 0, deployDay: 0, result: [], }; return progresses.reduce(deploy(speeds), init).result; } console.log(solution([93, 30, 55], [1, 30, 5]) === [2, 1]); console.log(solution([95, 90, 99, 99, 80, 99], [1, 1, 1, 1, 1, 1]) === [1, 3, 2]); // 옛날에 푼 것 function solution2 (progresses, speeds) { var answer = []; while (speeds.length > 0) { // 개발 for (let i in speeds) { if (progresses[i] < 100) { progresses[i] += speeds[i]; } } // 배포 let deploy_count = 0; while (progresses[0] >= 100) { progresses.shift(); speeds.shift(); deploy_count++; } if (deploy_count > 0) { answer.push(deploy_count); } } return answer; } ================================================ FILE: programmers/난이도별/level02.기능개발/junilhwang.js ================================================ /* 여러 개의 쇠막대기를 레이저로 절단하려고 합니다. 효율적인 작업을 위해서 쇠막대기를 아래에서 위로 겹쳐 놓고, 레이저를 위에서 수직으로 발사하여 쇠막대기들을 자릅니다. 쇠막대기와 레이저의 배치는 다음 조건을 만족합니다. - 쇠막대기는 자신보다 긴 쇠막대기 위에만 놓일 수 있습니다. - 쇠막대기를 다른 쇠막대기 위에 놓는 경우 완전히 포함되도록 놓되, 끝점은 겹치지 않도록 놓습니다. - 각 쇠막대기를 자르는 레이저는 적어도 하나 존재합니다. - 레이저는 어떤 쇠막대기의 양 끝점과도 겹치지 않습니다. */ function solution(arrangement) { const str = arrangement.replace(/\(\)/gi, 'l') const stack = [] let num = 0 for (let i = 0, len = str.length; i < len; i++) { const c = str.charAt(i) switch (c) { case '(' : stack.push('bar'); break; case ')' : stack.pop(), num += 1; break; case 'l' : num += stack.length; break; } } return num; } console.log(solution("()(((()())(())()))(())")) ================================================ FILE: programmers/난이도별/level02.기능개발/rockmiin.py ================================================ import math def solution(prograsses, speeds): slen=len(prograsses) days=[] cnt=[0] * slen answer=[] for i in range(slen): days.append(math.ceil((100-prograsses[i])/speeds[i])) for i in range(slen): tmp=sum(cnt) for j in range(i, slen): if days[i] < days[j]: break; cnt[j]=1 if sum(cnt)-tmp!=0: answer.append(sum(cnt)-tmp) return answer print( solution([93, 30, 55], [1, 30, 5]), solution([93, 30, 55], [1, 30, 5])==[2, 1] ) ================================================ FILE: programmers/난이도별/level02.기능개발/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42586 기능 개발 [풀이] 1. 선순위 큐의 모든 원소들에 동일한 값이 더해질 때 조건부 팝 2. 각 작업이 같은 날 팝 되면 같은 dict에서 카운트되도록 함 ''' def solution(progresses, speeds): day = 1 comp = {} for p, s in zip(progresses, speeds): while p + s * day < 100: day += 1 comp.setdefault(day, 0) comp[day] += 1 return list(map(lambda x: x[1], sorted(comp.items(), key=lambda x: x[0]))) ''' ''' ================================================ FILE: programmers/난이도별/level02.기능개발/sjjyy.java ================================================ package programmers.난이도별.level02.기능개발; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; public class sjjyy { public static int[] solution(int[] progresses, int[] speeds) { int len = progresses.length; Queue queue = new LinkedList<>(); int index = 0, count = 0; while (index < len) { for (int i = 0; i < len; i++) progresses[i] += speeds[i]; // 하루 작업 진도 if (progresses[index] >= 100) // 작업 배포가 가능할 때 continue; while (index < len && progresses[index] >= 100) // 같이 배포가 가능한 개수 { count++; index++; } queue.offer(count); // 배포된 개수 저장 count = 0; } int[] answer = new int[queue.size()]; for (int i = 0; i < answer.length; i++) answer[i] = queue.poll(); return answer; // 실패 // Queue queue = new LinkedList<>(); // ArrayList answerList = new ArrayList<>(); // // for (int i = 0 ; i < progresses.length ; i++) // { // int day = 0; // while (progresses[i] < 100) { // progresses[i] += speeds[i]; // day++; // } // // queue.add(day); // } // // int rest; // for (int i = 0; i < progresses.length; i++) { // rest = 100 - progresses[i]; // if(rest % speeds[i] == 0) queue.add(rest / speeds[i]); // else queue.add(rest / speeds[i] + 1); // } // // while (!queue.isEmpty()) { // int j = queue.peek(); // int count = 0; // // while (queue.peek() <= j) { // count++; // queue.poll(); // if (queue.isEmpty()) // break; // } // // answerList.add(count); // } // // int[] answer = new int[answerList.size()]; // for (int i = 0 ; i < answerList.size() ; i++) // answer[i] = answerList.get(i); // // return answer; } public static void main(String[] args) { int[] p1 = {93, 30, 55}, s1 = {1, 30, 5}; int[] p2 = {95, 90, 99, 99, 80, 99}, s2 = {1, 1, 1, 1, 1, 1}; System.out.println(Arrays.toString(solution(p1, s1))); // [2, 1] System.out.println(Arrays.toString(solution(p2, s2))); // [1, 3, 2] } } ================================================ FILE: programmers/난이도별/level02.뉴스_클러스터링/6047198844.cpp ================================================ #include #include using namespace std; int solution(string str1, string str2) { //소문자 -> 대문자 int str1_size = str1.size(); int str2_size = str2.size(); for (int i = 0; i < str1_size; i++) if (str1[i] >= 'a' && str1[i] <= 'z') str1[i] = str1[i] - 'a' + 'A'; for (int i = 0; i < str2_size; i++) if (str2[i] >= 'a' && str2[i] <= 'z') str2[i] = str2[i] - 'a' + 'A'; //두글자씩 쪼갠다. 공백이나 숫자. 특수문자가 있는지 체크. 글자쌍 버림 map mp1; map mp2; for (int i = 0; i < str1_size - 1; i++) { string s1 = ""; if ((str1[i] >= 'A' && str1[i] <= 'Z') && (str1[i + 1] >= 'A' && str1[i + 1] <= 'Z')) { s1 = s1 + str1[i] + str1[i + 1]; mp1[s1]++; } } for (int i = 0; i < str2_size - 1; i++) { string s2 = ""; if ((str2[i] >= 'A' && str2[i] <= 'Z') && (str2[i + 1] >= 'A' && str2[i + 1] <= 'Z')) { s2 = s2 + str2[i] + str2[i + 1]; mp2[s2]++; } } int connection = 0; for (auto s : mp2) { if (mp1[s.first]) { if (mp1[s.first] > s.second) { connection += s.second; } else { connection += mp1[s.first]; mp1[s.first] = s.second; } } else { mp1[s.first] = s.second; } } int total = 0; for (auto s : mp1) { total += s.second; } if(total) return (double)connection / (double)total * 65536; else return 65536; } int main() { solution("aa1+aa2", "AAAA12"); } ================================================ FILE: programmers/난이도별/level02.뉴스_클러스터링/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17677 뉴스 클러스터링 [풀이] 1. 두 글자씩 끊고 lower와 isalpha 검사. 이후, union, intersection 구하기 ''' def solution(str1, str2): str1, str2 = [str1[i] + str1[i + 1] for i in range(len(str1) - 1)], [str2[i] + str2[i + 1] for i in range(len(str2) - 1)] str1, str2 = [i.lower() for i in str1 if i.isalpha()], [i.lower() for i in str2 if i.isalpha()] union = str1 + str2 intersection = [] for i in str1: if i in str2: intersection.append(i) str2.remove(i) for i in intersection: if i in union: union.remove(i) return int(len(intersection) / len(union) * 65536) if len(union) else 65536 ''' ''' ================================================ FILE: programmers/난이도별/level02.다리를_지나는_트럭/6047198844.cpp ================================================ #include #include #include #include #include using namespace std; int solution(int bridge_length, int weight, vector truck_weights) { int answer = 0; queue wait_q; int truck_weights_size = truck_weights.size(); for (int i = 0; i < truck_weights_size; i++) { wait_q.push(truck_weights[i]); } deque > on_deq; int on_weight = 0; int sec = 0; do { sec++; if (wait_q.size()&&(weight >= on_weight + wait_q.front())) { on_deq.push_back({ wait_q.front(),0 }); wait_q.pop(); on_weight += on_deq.back().first; } for (int i = 0; i < on_deq.size(); i++) on_deq[i].second++; if (on_deq.front().second == bridge_length) { on_weight -= on_deq.front().first; on_deq.pop_front(); } } while (on_deq.size() || wait_q.size()); answer = ++sec; return answer; } int main() { cout << solution(2, 10, {7,4,5,6}); } ================================================ FILE: programmers/난이도별/level02.다리를_지나는_트럭/Jaewon0702.py ================================================ def solution(bridge_length, weight, truck_weights): count=len(truck_weights) time=[0]*count ; passed=[]; passing=[] i=0 ; j=-1 truck_weights=truck_weights[::-1] while(len(passed)0) and (sum(passing)+truck_weights[-1]) <= weight : passing.append(truck_weights.pop()) j+=1 time[:j+1] = [time[v]+1 for v in range(j+1)] #각 트럭이 다리에 오르고 몇 초가 지났는지 알 수 있다. if time[i]==bridge_length : passed.append(passing.pop(0)) #Ln : 17 i+=1 return time[0]+1 '''Ln : 17= passed.append(passing[0]) passing = passing[1:] 과 같이 바꿀 수 있다.''' #https://leedakyeong.tistory.com/entry/프로그래머스-다리를-지나는-트럭-in-python를 참고하였다. ================================================ FILE: programmers/난이도별/level02.다리를_지나는_트럭/README.md ================================================ # 출처 http://programmers.co.kr/learn/courses/30/lessons/42583 ================================================ FILE: programmers/난이도별/level02.다리를_지나는_트럭/dkdlelk99.py ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42583 # 풀이 by github id : dkdlelk99, dkdlelk99@gmail.com # 목표 트럭이 다리를 걸리는데 필요한 최소시간 알아내기 # 조건 트럭은 1초에 거리 1씩 이동, 다리위의 트럭의 무게는 weight를 초과할 수 없음, 모든 트럭의 무게는 1 이상 weight 이하 # bridge_length = 다리의 길이(int), weight = 버티는 최대 무게(int), truck_weights = 건너야 할 트럭의 무게(int)들이 담긴 리스트 def solution(bridge_length, weight, truck_weights): sec = 0 on_the_bridge = [0] * bridge_length #FIFO while 1: sec += 1 on_the_bridge.pop(0) # 대기 트럭 인덱스 에러 때문에 비어있으면 값 0이라고 해버림 next_truck = truck_weights[0] if truck_weights != [] else 0 if sum(on_the_bridge) + next_truck <= weight: #다음 트럭 올라올수 있을때 if truck_weights: on_the_bridge.append(truck_weights.pop(0)) else:#마지막일때 실행 sec += bridge_length - 1 break #다음 트럭 못올라올때 else: on_the_bridge.append(0) return sec print(solution(2,10,[7,4,5,6]), solution(2,10,[7,4,5,6]) == 8) print(solution(100,100,[10]), solution(100,100,[10]) == 101) print(solution(100,100,[10]*10), solution(100,100,[10]*10) == 110) print(solution(5,6,[1,2,3,1,2]), solution(5,6,[1,2,3,1,2]) == 12) #my test case # 예시 # 초 / 다리를 건넌 트럭 / 다리 위 트럭 / 대기 트럭 # 0 [] [] [7,4,5,6] # 1~2 [] [7] [4,5,6] # 3 [7] [4] [5,6] # 4 [7] [4,5] [6] # 5 [7,4] [5] [6] # 6~7 [7,4,5] [6] [] # 8 [7,4,5,6] [] [] ================================================ FILE: programmers/난이도별/level02.다리를_지나는_트럭/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/42583?language=javascript * @param bridge_length 다리의 길이 * @param weight 다리가 견딜 수 있는 무게 * @param truck_weights 트럭의 무게를 담은 배열 * @return 모든 트럭이 다리를 건너기 위해 걸리는 최소 시간 * 다리는 1초에 한칸씩 이동할 수 있다. * bridge_length는 1 이상 10,000 이하입니다. weight는 1 이상 10,000 이하입니다. truck_weights의 길이는 1 이상 10,000 이하입니다. 모든 트럭의 무게는 1 이상 weight 이하입니다. */ /* * solution2 에서 * const targetTruck = standing[0]; standing.shift(); 와 반대로 * const targetTruck = standing[standing.length - 1]; standing.pop(); 거꾸로 순회해도 거의 비슷한 시간과 정답을 보였다. * */ function solution(bridge_length, weight, truck_weights) { if (bridge_length === 1) return truck_weights.length + 1; // 마지막 truck 이 건널 때 소요되는 시간으로 초기화를 해준다. let time = bridge_length; // 대기중인 트럭의 배열 const standing = [...truck_weights]; // 다리위의 트럭의 배열 const bridge = []; // 다리 위의 트럭의 총 무게 let bridgeWeight = 0; // 대기 중인 트럭이 모두 다리위에 올라갈 때 까지 반복한다 while (standing.length !== 0) { const targetTruck = standing[0]; // bridge 가 꽉찬 시점에서 pop 을 실행한다는 점이 solution2 와 다르다. if (bridge.length === bridge_length) { bridgeWeight -= bridge.pop(); } let put = 0; // 다리 위에 올라갈 수 있다면 다리위의 무게에 합산하고, 대기중인 트럭 배열에서 해당 트럭을 제거한다. if (bridgeWeight + targetTruck <= weight) { put = targetTruck; standing.shift(); } // 다리위에 트럭을 올린다. bridge.unshift(put); bridgeWeight += put; time += 1; } return time; } /* solution 2 보다 살짝 빠르다. 테스트 1 〉 통과 (0.72ms, 29.9MB) 테스트 2 〉 통과 (33.79ms, 32.4MB) 테스트 3 〉 통과 (0.08ms, 30MB) 테스트 4 〉 통과 (9.19ms, 32.7MB) 테스트 5 〉 통과 (222.68ms, 32.8MB) 테스트 6 〉 통과 (33.44ms, 32.4MB) 테스트 7 〉 통과 (0.67ms, 29.9MB) 테스트 8 〉 통과 (0.11ms, 29.8MB) 테스트 9 〉 통과 (3.43ms, 32.6MB) 테스트 10 〉 통과 (0.22ms, 30.1MB) 테스트 11 〉 통과 (0.10ms, 30.1MB) 테스트 12 〉 통과 (0.32ms, 30MB) 테스트 13 〉 통과 (0.82ms, 30.1MB) 테스트 14 〉 통과 (0.09ms, 30MB) */ function solution2(bridge_length, weight, truck_weights) { if (bridge_length === 1) return truck_weights.length + 1; let time = 0; const standing = [...truck_weights]; const bridge = new Array(bridge_length).fill(0); let bridgeWeight = 0; while (standing.length !== 0) { const targetTruck = standing[0]; const pop = bridge.pop(); bridgeWeight -= pop; let put = 0; if (bridgeWeight + targetTruck <= weight) { put = targetTruck; standing.shift(); } bridge.unshift(put); bridgeWeight += put; time += 1; } return time + bridge_length; } /* 테스트 1 〉 통과 (0.72ms, 30MB) 테스트 2 〉 통과 (37.70ms, 32.7MB) 테스트 3 〉 통과 (0.07ms, 30MB) 테스트 4 〉 통과 (9.02ms, 32.8MB) 테스트 5 〉 통과 (223.29ms, 32.7MB) 테스트 6 〉 통과 (31.52ms, 32.6MB) 테스트 7 〉 통과 (0.69ms, 29.9MB) 테스트 8 〉 통과 (0.21ms, 30MB) 테스트 9 〉 통과 (3.40ms, 32.4MB) 테스트 10 〉 통과 (0.24ms, 30MB) 테스트 11 〉 통과 (0.09ms, 29.9MB) 테스트 12 〉 통과 (0.30ms, 30.1MB) 테스트 13 〉 통과 (1.02ms, 29.7MB) 테스트 14 〉 통과 (0.09ms, 29.9MB) * */ console.log(solution(2, 10, [7, 4, 5, 6]) === 8); console.log(solution(2, 10, [10, 4, 5, 6]) === 8); console.log(solution(2, 10, [7]) === 3); console.log(solution(100, 100, [10]) === 101); console.log(solution(100, 100, [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]) === 110); console.log(solution(5, 6, [1, 2, 3, 1, 2]) == 12); console.log(solution(1, 2, [1, 1, 1]) === 4); console.log(solution(1, 1, [1, 1, 1]) === 4); console.log(solution(4, 2, [1, 1, 1, 1]) === 10); console.log(solution(3, 3, [1, 1, 1]) === 6); console.log(solution(3, 1, [1, 1, 1]) === 10); console.log(solution(5, 5, [1, 1, 1, 1, 1, 2, 2]) === 14); console.log(solution(7, 7, [1, 1, 1, 1, 1, 3, 3]) === 18); console.log(solution(5, 5, [1, 1, 1, 1, 1, 2, 2, 2, 2]) === 19); console.log(solution(5, 5, [2, 2, 2, 2, 1, 1, 1, 1, 1]) === 19); // 옛날에 푼 것 function solution2(bridge_length, weight, truck_weights) { let cnt = 0, cur_weight = 0; let bridge_in_truck = [...new Array(bridge_length)].fill(0); while (truck_weights.length) { let J = truck_weights.shift(); let flag = false; while (cur_weight + J > weight) { let p = bridge_in_truck.pop(); cur_weight = cur_weight - p; if (cur_weight < weight) { bridge_in_truck.unshift(J); cnt++; flag = true; continue; } else { bridge_in_truck.unshift(0); cnt++; } cnt++; }// 다리에 건널 수 있나 판별? if (flag === false) { let p = bridge_in_truck.pop(); bridge_in_truck.unshift(J); cur_weight = cur_weight - p + J; cnt++; } } return cnt + bridge_length; } ================================================ FILE: programmers/난이도별/level02.다리를_지나는_트럭/junilhwang.js ================================================ /* 수평 직선에 탑 N대를 세웠습니다. 모든 탑의 꼭대기에는 신호를 송/수신하는 장치를 설치했습니다. 발사한 신호는 신호를 보낸 탑보다 높은 탑에서만 수신합니다. 또한, 한 번 수신된 신호는 다른 탑으로 송신되지 않습니다. 예를 들어 높이가 6, 9, 5, 7, 4인 다섯 탑이 왼쪽으로 동시에 레이저 신호를 발사합니다. 그러면, 탑은 다음과 같이 신호를 주고받습니다. 높이가 4인 다섯 번째 탑에서 발사한 신호는 높이가 7인 네 번째 탑이 수신하고, 높이가 7인 네 번째 탑의 신호는 높이가 9인 두 번째 탑이, 높이가 5인 세 번째 탑의 신호도 높이가 9인 두 번째 탑이 수신합니다. 높이가 9인 두 번째 탑과 높이가 6인 첫 번째 탑이 보낸 레이저 신호는 어떤 탑에서도 수신할 수 없습니다. */ function solution(h) { var a = []; while (h.length) { const target = h.pop() let r = 0 for (let i = h.length - 1; i >= 0; i--) { if (h[i] > target) { r = i + 1 break; } } a.unshift(r) } return a; } console.log(solution([6,9,5,7,4])) console.log(solution([3,9,9,3,5,7,2])) console.log(solution([1,5,3,6,7,6,5])) console.log(solution([5,1,3,6,7,6,5])) ================================================ FILE: programmers/난이도별/level02.다리를_지나는_트럭/rockmiin.py ================================================ def solution(bridge_length, weight, truck_weight): on_bridge=[] cnt=[0]* len(truck_weight) total_time=1 pass_truck_count=0 while truck_weight!=[]: if sum(on_bridge)+truck_weight[0]<=weight: on_bridge.append(truck_weight.pop(0)) for i in range(pass_truck_count, pass_truck_count+len(on_bridge)): cnt[i]+=1 if bridge_length==cnt[i]: on_bridge.pop(0); pass_truck_count+=1 total_time += 1 return total_time+bridge_length-1 print( solution(2, 10, [7, 4, 5, 6])==8 ) ================================================ FILE: programmers/난이도별/level02.다리를_지나는_트럭/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42583 다리를 지나는 트럭 : 다리의 길이와 트럭의 무게 다리의 하중을 고려하여 모든 트럭이 지나는 시간 구하기 다리를 지나는 시간은 이전 트럭이 출발한 시점부터 자신이 출발한 시점까지의 대기 시간을 모두 합 + 다리 길이 + 1 이다. ''' from collections import deque def solution(bridge_length, weight, truck_weights): b, w, t = bridge_length, weight, truck_weights time = deque([1]) wsum = deque([t[0]]) sec = 0 for v, i in enumerate(t[1:]): if i <= weight - sum(wsum): time.append(1) wsum.append(i) if sum(time) - time[0] == b: sec += time.popleft() wsum.popleft() continue if i <= weight - sum(wsum) + wsum[0]: sec += time.popleft() wsum.popleft() time.append(b - sum(time)) wsum.append(i) continue while i > weight - sum(wsum): sec += time.popleft() wsum.popleft() time.append(b - sum(time)) wsum.append(i) return sum(time) + b ''' 100%의 모든 사람들이 1초에 대해서 반복문을 설정한데 비해 트럭의 순서에 대해서 반복문을 돌리려고 했음 => 실제 1초에 대해서 구현한 대부분 코드는 1000.00ms가 넘는다. => 다음과 같이 0.1ms가 걸리지 않아 결과적으로 엄청나게 빠른 코드 생성 => 실전에서 다음과 같이 풀었으면 스포트라이트를 받을 것 같다. 제한 시간 내에는 불가능 할 듯. 테스트 1 〉 통과 (0.01ms, 10.4MB) 테스트 2 〉 통과 (0.02ms, 10.3MB) 테스트 3 〉 통과 (0.01ms, 10.3MB) 테스트 4 〉 통과 (0.40ms, 10.3MB) 테스트 5 〉 통과 (0.90ms, 10.3MB) 테스트 6 〉 통과 (0.79ms, 10.3MB) 테스트 7 〉 통과 (0.01ms, 10.3MB) 테스트 8 〉 통과 (0.02ms, 10.3MB) 테스트 9 〉 통과 (0.48ms, 10.4MB) 테스트 10 〉 통과 (0.02ms, 10.2MB) 테스트 11 〉 통과 (0.02ms, 10.3MB) 테스트 12 〉 통과 (0.07ms, 10.2MB) 테스트 13 〉 통과 (0.07ms, 10.3MB) 테스트 14 〉 통과 (0.01ms, 10.3MB) ''' ================================================ FILE: programmers/난이도별/level02.다리를_지나는_트럭/sjjyy.java ================================================ import java.awt.*; import java.util.LinkedList; import java.util.Queue; public class sjjyy { // public static int solution(int bridge_length, int weight, int[] truck_weights) { // int answer = 0, max = 0; // Queue queue = new LinkedList<>(); // // for (int i : truck_weights) // { // while (true) // { // if (queue.isEmpty()) { // 큐가 비었을 때 트럭의 무게 삽입 // queue.offer(i); // max += i; // answer++; // break; // } else if (queue.size() == bridge_length) // 트럭이 다리를 다 건너면 큐에서 꺼내 최대 무게에서 뺌 // max -= queue.poll(); // else { // 큐가 비어있지 않을 때 // if (max + i > weight) { // 무게가 초과되면 0 삽입 // queue.offer(0); // answer++; // } else { // 무게가 초과되지 않으면 트럭의 무게 삽입 // queue.offer(i); // max += i; // answer++; // break; // } // // } // } // } // // return answer + bridge_length; // } public static int solution(int bridge_length, int weight, int[] truck_weights) { int time = 0; Queue truck = new LinkedList(); Queue bridge = new LinkedList(); for (int truck_weight : truck_weights) truck.add(truck_weight); int total = 0; while (!truck.isEmpty() || !bridge.isEmpty()) { // 모든 트럭이 다리를 다 건널 때까지 time++; if (!bridge.isEmpty()) { // 다리에 트럭이 올라왔을 때 Point p = bridge.peek(); if (time - p.y >= bridge_length) { total -= p.x; bridge.poll(); } } if (!truck.isEmpty()) { // 더 올릴 트럭이 남아있을 때 if (total + truck.peek() <= weight) { // 총 무게를 넘지 않을 때만 int tmp = truck.poll(); total += tmp; bridge.offer(new Point(tmp, time)); } } } return time; } public static void main(String[] args) { int[] w1 = {7, 4, 5, 6}; int[] w2 = {10}; int[] w3 = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10}; System.out.println(solution(2, 10, w1)); // 8 System.out.println(solution(100, 100, w2)); // 101 System.out.println(solution(100, 100, w3)); // 110 } } ================================================ FILE: programmers/난이도별/level02.다음_큰_숫자/6047198844.cpp ================================================ #include #include #include #include using namespace std; string detobi(int n) { string s = ""; while (n) { s = to_string(n % 2) + s; n = n / 2; } return s; } int bitode(string n) { int res = 0; int end_index = n.size() - 1; for (int i = 0, j = 1; i <= end_index; i++,j*=2) { res += (n[end_index - i] - '0') * j; } return res; } int solution(int n) { int answer = 0; string res = detobi(n); if (find(res.begin(), res.end(), '0') == res.end()) res.insert(1, "0"); else next_permutation(res.begin(), res.end()); if (res[0] == '0') { next_permutation(res.begin(), res.end()); res.insert(1, "0"); } answer = bitode(res); return answer; } int main() { solution(6); } ================================================ FILE: programmers/난이도별/level02.다음_큰_숫자/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12911 문제 : 다음 큰 숫자 값을 이진수로 바꾼 후 한글자씩 나눠 정수형으로 바꾼 후 1을 count 하였습니다. 다른 사람들 풀이를 보니 정수형으로 바꾸지 않아도 바로 count로 1을 판별할 수 있더라구요. [메모] n1 = bin(n).count('1') ''' def solution(n): n1 = list(map(int,bin(n)[2:])).count(1) a, a1 = n+1, -1 while n1 != a1 : a1 = list(map(int, bin(a)[2:])).count(1) a += 1 return a-1 ================================================ FILE: programmers/난이도별/level02.다음_큰_숫자/HyeonJeong.py ================================================ def solution(n): binary_n = bin(n) num_1 = binary_n.count('1') for i in range(1, 1000001-n): #n은 1000000이하의 자연수 이므로 if bin(n + i).count('1') == num_1: return int(n+i) print(solution(78)==83, solution(15)==23) ================================================ FILE: programmers/난이도별/level02.다음_큰_숫자/README.md ================================================ ##출처 https://programmers.co.kr/learn/courses/30/lessons/12911 ================================================ FILE: programmers/난이도별/level02.다음_큰_숫자/rockmiin.py ================================================ def solution(n): def bin(n): answer = [] while True: answer.append(n%2) n=n//2 if n==1: answer.append(1); break; return sum(answer) count= bin(n) for i in range(n+1, 1000001): if bin(i)==count: return i print(solution(78)) ================================================ FILE: programmers/난이도별/level02.다음_큰_숫자/rockmiin_다음큰숫자.py ================================================ def solution(n): def bin(n): answer = [] while True: answer.append(n%2) n=n//2 if n==1: answer.append(1); break; return sum(answer) count= bin(n) for i in range(n+1, 1000001): if bin(i)==count: return i print(solution(78)) ================================================ FILE: programmers/난이도별/level02.다음_큰_숫자/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12911 다음 큰 숫자 [풀이] 1. format 사용 ''' def solution(n): one = format(n, 'b').count('1') while True: n += 1 if one == format(n, 'b').count('1'): return n ''' ''' ================================================ FILE: programmers/난이도별/level02.다음_큰_숫자/sjjyy.java ================================================ public class sjjyy { /* 조건 1. n의 다음 큰 숫자는 n보다 큰 자연수 입니다. 조건 2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때 1의 갯수가 같습니다. 조건 3. n의 다음 큰 숫자는 조건 1, 2를 만족하는 수 중 가장 작은 수 입니다. */ public static int solution(int n) { String nToBinary = Integer.toBinaryString(n); int nCount = 0; // 입력된 값을 이진수로 변환 후 1 개수 카운트 for(int i=0; i #include #include #include #include using namespace std; // 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요. bool check(int real_interval, char sign,int want_interval) { if (sign == '=') return real_interval == want_interval; else if (sign == '>') return real_interval > want_interval; else return real_interval < want_interval; } int solution(int n, vector data) { string line = "ACFJMNRT"; int answer = 0; do { bool flag = true; for (string a : data) { char front_kakao = a[0]; char back_kakao = a[2]; char sign = a[3]; int want_interval = a[4] - '0'; int real_interval = abs((int)line.find(front_kakao) - (int)line.find(back_kakao)) - 1; if (!check(real_interval, sign, want_interval)) { flag = false; break; } } if (flag) answer++; } while (next_permutation(line.begin(), line.end())); return answer; } int main() { cout << solution(2, { "N~F=0", "R~T>2" }); } ///참고 : https://velog.io/@woga1999/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%8B%A8%EC%B2%B4%EC%82%AC%EC%A7%84-%EC%B0%8D%EA%B8%B0 ================================================ FILE: programmers/난이도별/level02.더_맵게/6047198844.cpp ================================================ #include #include #include #include #include #include using namespace std; int solution(vector scoville, int K) { int answer = 0; priority_queue, greater > pq(scoville.begin(), scoville.end()); int check = pq.top(); while (check < K) { if (pq.size() == 1) return -1; int first = pq.top(); pq.pop(); int second = pq.top(); pq.pop(); int mix = first + (second * 2); pq.push(mix); answer++; check = pq.top(); } return answer; } ================================================ FILE: programmers/난이도별/level02.더_맵게/HyeonJeong.py ================================================ # 실패 -> 정답을 분석한 것 import heapq #이진트리 기반 최소 힙(원소가 항상 정렬된 상태에서 추가, 삭제) 자료구조 제공 def solution(s, K): a = 0 # 섞은 횟수가 추가될 변수 heapq.heapify(s) if s[0] >= K : return 0 # 가장 작은 원소가 K이상이면 반환 while len(s) > 1 : heapq.heappush(s, heapq.heappop(s) + heapq.heappop(s) * 2) # heappush()는 두 번째 인자를 첫 번째 인자인 리스트에 추가, O(logN)의 시간복잡도를 가짐 # heappop()은 대상 리스트에서 가장 작은 원소 삭제후 값 리턴 a += 1 # 섞은 횟수 추가 if s[0] >= K : return a # 가장 작은 원소가 K이상이면 섞은 횟수 반환 return -1 # 다 섞었는데도 K미만인 경우 print(solution([1, 2, 3, 9, 10, 12], 7) == 2) ================================================ FILE: programmers/난이도별/level02.더_맵게/Jaewon0702.py ================================================ import heapq def solution(scoville, K): heapq.heapify(scoville) n=0 while(len(scoville)>1) : if not scoville[0]= K: return answer most_not_spicy = heapq.heappop(heap) if heap != []: heapq.heappush(heap, most_not_spicy + (2 * heapq.heappop(heap) )) answer += 1 return -1 if heap == [] else answer print(solution([1, 2, 3, 9, 10, 12], 7), solution([1, 2, 3, 9, 10, 12], 7) == 2) ================================================ FILE: programmers/난이도별/level02.더_맵게/junilhwang-01.py ================================================ # https://programmers.co.kr/learn/courses/30/lessons/42626 # 섞은 음식의 스코빌 지수 = 가장 맵지 않은 음식의 스코빌 지수 + (두 번째로 맵지 않은 음식의 스코빌 지수 * 2) def solution(s, K): h = [] for v in s : insert(h, v) if h[0] >= K : return 0 for i in range(1, len(h)) : insert(h, delete(h) + delete(h) * 2) if h[0] >= K : return i return -1 def insert (h, n) : i = len(h) h.append(n) while i > 0 and n < h[int(i/2)] : h[i], i = h[int(i/2)], int(i/2) h[i] = n def delete (h) : n, h[0] = h[0], h[-1] hlen = len(h) i = 0 while i * 2 + 1 < hlen : next = i * 2 if i != 0 else 1 if next + 1 < hlen and h[next] > h[next + 1] : next += 1 h[next], h[i], i = h[i], h[next], next del h[-1] return n print(solution([1, 2, 3, 9, 10, 12], 100)) print(solution([1, 2], 7)) print(solution([1], 2)) print(solution([5], 5)) print(solution([1,2,7], 5)) print(solution([2,3,7], 7)) print(solution([0], 0)) ================================================ FILE: programmers/난이도별/level02.더_맵게/junilhwang-02.py ================================================ import heapq def solution(s, K): heapq.heapify(s) a = 0 if s[0] >= K : return 0 while len(s) > 1 : heapq.heappush(s, heapq.heappop(s) + heapq.heappop(s) * 2) a += 1 if s[0] >= K : return a return -1 print(solution([1, 2, 3, 9, 10, 12], 100)) print(solution([1, 2], 7)) print(solution([1], 2)) print(solution([5], 5)) print(solution([1,2,7], 5)) print(solution([2,3,7], 7)) print(solution([0], 0)) ================================================ FILE: programmers/난이도별/level02.더_맵게/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42626 더 맵게 [풀이] 1. 가장 작은 2개의 원소에 대해 특정 연산 후 조건 확인 2. heapq 사용으로 매번 작은 수를 얻음 ''' import heapq as h def solution(scoville, K): s = scoville[:] h.heapify(s) m1, m2 = h.heappop(s), h.heappop(s) if m1 == m2 == 0: return -1 while True: h.heappush(s, m1+2*m2) if s[0] >= K: break if len(s) < 2: return -1 m1, m2 = h.heappop(s), h.heappop(s) return len(scoville) - len(s) ''' ''' ================================================ FILE: programmers/난이도별/level02.더_맵게/sjjyy.java ================================================ import java.util.PriorityQueue; public class sjjyy { /* 섞은 음식의 스코빌 지수 = 가장 맵지 않은 음식의 스코빌 지수 + (두 번째로 맵지 않은 음식의 스코빌 지수 * 2) */ public static int solution(int[] scoville, int K) { PriorityQueue queue = new PriorityQueue<>(); int answer = 0; for (int i : scoville) queue.add(i); while (queue.peek() <= K) { if (queue.size() <= 1) { // 예외처리 answer = -1; break; } int first = queue.poll(); int second = queue.poll(); int mix = first + second * 2; answer++; queue.add(mix); } return answer; } public static void main(String[] args) { int[] scovile = {1, 2, 3, 9, 10, 12}; System.out.println(solution(scovile, 7)); // 2 } } ================================================ FILE: programmers/난이도별/level02.동명_동물_수_찾기/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT NAME, COUNT(*) FROM ANIMAL_INS WHERE NAME IS NOT NULL GROUP BY NAME HAVING COUNT(*) >= 2 ORDER BY NAME ================================================ FILE: programmers/난이도별/level02.땅따먹기/6047198844.cpp ================================================ #include #include #include using namespace std; // memo[N][0] // 0번째 열을 택했을때의 최대값. // memo[N][1] // 1번째 열을 택했을때의 최대값. // memo[N][2] // 2번째 열을 택했을때의 최대값. // memo[N][3] // 3번째 열을 택했을때의 최대값. int memo[100000][4]; //row, column -> 현재 row / 이전에 선택한 column //dp(N,0) = dp(N-1,1)+land[N][1] , dp(N-1,2)+land[N][2],dp(N-1,3)+land[N][3] int dp(int row, int column, vector >& land) { if (row == -1) return 0; if (memo[row][column]) return memo[row][column]; int res = 0; for (int i = 0; i < 4; i++) { if (i != column) { int temp = dp(row - 1, i, land) + land[row][i]; memo[row][column] = memo[row][column] > temp ? memo[row][column] : temp; } } return memo[row][column]; } int solution(vector > land) { int answer = 0; int row = land.size() - 1; return dp(row, 5, land); } ================================================ FILE: programmers/난이도별/level02.땅따먹기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12913# 문제 : 땅따먹기 처음에는 index가 같을 때 (직전 반복에서의 두번째로 큰수+지금의 제일 큰수), (직전 반복에서의 제일 큰수+지금의 두번째로 큰 수)를 구해서 비교해서 answer에 바로바로 더하고 수정하는 방식으로 풀이하였습니다. 그러니까 풀이도 너무 복잡해지고 다 틀렸다고 나와서 다른 사람들 질문을 보고 동적 프로그래밍을 사용해야 하는 문제임을 알았습니다. index가 같을 때는 직전에서 두번째로 큰 값을, index가 다를 때는 직전에서 제일 큰 값을 land에 바로 더하여 문제를 해결하였습니다. 다른 사람들 풀이를 보니 index를 비교하지도 않고, max값과 두번째로 큰 값을 구하지도 않는 대단한 풀이가 있더라구요! ★ ω ★ [메모] land[i][j] = max(land[i-1][:j]+land[i-1][j+1:]) + land[i][j] ''' def solution(land): first, second = max(land[0]), sorted(land[0])[-2] index = land[0].index(first) for i in range(1, len(land)) : for j in range(4) : if index==j : land[i][j] += second else : land[i][j] += first first, second = max(land[i]), sorted(land[i])[-2] index = land[i].index(first) return max(land[-1]) ================================================ FILE: programmers/난이도별/level02.땅따먹기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12913 땅따먹기 [풀이] 1. max 값을 아래 리스트로 내려보낸다. 바로 아래는 두번째 max값을 전달. ''' def solution(land): one = two = idx = 0 for i in land: for j in range(4): i[j] += one i[idx] += two - one idx = i.index(max(i)) one, two = sorted(i)[-1], sorted(i)[-2] return max(land[-1]) print( solution([[1,2,3,5],[5,6,7,8],[4,3,2,1]]) ) ''' 이렇게 풀고 싶었던 것이 맞다. def solution(land): for i in range(1, len(land)): for j in range(len(land[0])): land[i][j] = max(land[i -1][: j] + land[i - 1][j + 1:]) + land[i][j] return max(land[-1]) ''' ================================================ FILE: programmers/난이도별/level02.루시와_엘라_찾기/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT ANIMAL_ID, NAME, SEX_UPON_INTAKE FROM ANIMAL_INS WHERE NAME = 'Lucy' OR NAME = 'Ella' OR NAME = 'Pickle' OR NAME = 'Rogan' OR NAME = 'Sabrina' OR NAME = 'Mitty' ORDER BY 1; ================================================ FILE: programmers/난이도별/level02.멀리_뛰기/6047198844.py ================================================ import sys sys.setrecursionlimit(10000) memo = [-1]*2001 def solution(n): if n <= 2: return n if memo[n] != -1: return memo[n] memo[n] = (solution(n-1) % 1234567 + solution(n-2) % 1234567) % 1234567 return memo[n] ================================================ FILE: programmers/난이도별/level02.멀쩡한_사각형/12eon.py ================================================ def solution(w,h): # w와 h의 최대공약수만큼 사각형을 지날때마다 꼭짓점을 중간에 만나게 되는 규칙 if w > h: # w <= h 상태를 이용 tmp = h h = w w = tmp for d in range(w,1,-1): if w%d == 0 and h%d == 0: # 최대공약수 # 최대공약수가 1이 아닌 경우 # 꼭짓점을 만날 때마다 반복되었던 위치가 1칸씩 뒤로 밀려서 만나는 사각형이 감소(d) # w + h - d return w*h - (w+h-d) # 최대공약수가 1인 경우 : 대각선이 사각형의 꼭짓점을 양끝을 제외하고는 지나지 않음 # 가로 방향에 보면 h개를 지남 + 세로 방향으로 보면 w개를 지남 - 가로와 세로로 갈 때 시작하는 사각형이 같음(1) # w + h -1 return w*h - (w+h-1) ''' import math def solution(w,h): return w*h -(w+h-math.gcd(w,h) ''' ================================================ FILE: programmers/난이도별/level02.멀쩡한_사각형/6047198844.cpp ================================================ #include #include #include using namespace std; long long solution(int w, int h) { long long answer = 0; long long temp = 0; // y = (h/w) * x double d_w = (double)w; double l_h = (double)h; for (int x = 1; x <= w; x++) { temp = ceil((l_h / d_w) * x); answer += (h - temp); } answer *= 2; return answer; } int main() { cout << solution(8, 12); } ================================================ FILE: programmers/난이도별/level02.멀쩡한_사각형/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/62048 ================================================ FILE: programmers/난이도별/level02.멀쩡한_사각형/dkdlelk99.py ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/62048 # input W : 가로 길이, H : 세로 길이 (1억 이하의 자연수) # output 멀쩡한 사각형의 갯수 # 가로 길이 W, 세로 길이 H인 사각형을 대각선으로 자를 때, 가로 세로가 1cm인 사각형이 몇개인가? import math def solution(w,h): answer = 0 all = w * h x, y = w, h # x는 최대 공약수 while y: x, y = y, x % y # 수학을 이용한 간편한 풀이 # answer = (w//x - 1) + (h//x - 1) + 1 # return all - answer * x if w == h: return all - w elif h > w: for i in range(w // x): answer += math.ceil(h*(i+1)/w) - int(h * i / w) else: for i in range(h // x): answer += math.ceil(w*(i + 1)/h) - int(w * i / h) return all - answer * x print(solution(8, 12) == 80, solution(8, 12)) ================================================ FILE: programmers/난이도별/level02.멀쩡한_사각형/s2uyeoii.cpp ================================================ #include #include #include long long solution(int w, int h) { /*사용할 수 있는 정사각형의 개수가 들어가는 변수, 'w', 'h'는 1억 이하의 자연수이므로 두 매개변수의 곱은 int형을 넘어가기에 long long형으로 설정*/ long long answer = 0; // 각 열마다 잘린 부분 전까지 사용할 수 있는 정사각형의 개수를 담는 변수 long long block = 0; // 대각선으로 잘릴 경우, 동일한 정사각형의 개수를 가지는 직각삼각형이 두개 만들어진다 // 이를 기울기 * 행의 좌표(w*i / h)를 통해 'block'을 구하여 // 직각삼각형에 들어가는 정사각형 수를 구하고 2배를 해주면서 'answer'을 구하는 동작 for (int i = 0; i < h; i++) { block = (long long)w*i / h; answer += (2 * block); } return answer; } ================================================ FILE: programmers/난이도별/level02.멀쩡한_사각형/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/62048 멀쩡한 사각형 1. 직사각형의 대각선을 지나는 1x1 격자 사각형 개수 구하기 2. 작은 길이가 1씩 증가할 때, 대각선을 지나는 격자 사각형의 개수는, 큰길이와 작은길이의 비가 정수일 때 1개, 정수가 아닐 때 2개 ''' from math import gcd def solution(w,h): w, h = min(w, h), max(w, h) g = gcd(w, h) cnt, ele = h//g, h/w for i in range(1, w//g): if float(int(i * ele)) != i * ele: cnt += 1 return w*h - cnt*g ''' def solution(w,h): return w*h-w-h+gcd(w,h) ''' ================================================ FILE: programmers/난이도별/level02.메뉴_리뉴얼/6047198844.cpp ================================================ #include #include #include #include #include #include #include using namespace std; //답을 반환한다. //vec에는 조합 <문자열, 빈도수> 가 나오며 문자열은 크기 순대로 정렬되어있다. vector make_res(vector> vec, vector course) { vector res; //해당 오더에 해당하는 최대 값을 찾는다. for (int course_idx = 0; course_idx < course.size(); course_idx++) { int max_value = -1; for (int vec_idx = 0; vec_idx < vec.size(); vec_idx++) { if (vec[vec_idx].first.size() == course[course_idx] && vec[vec_idx].second > 1 && (max_value == -1 || max_value == vec[vec_idx].second)) { if (max_value == -1) max_value = vec[vec_idx].second; res.push_back(vec[vec_idx].first); } } } sort(res.begin(), res.end()); return res; } void combi(string s, int remain, int idx, int end_idx, string &order, map & combiCustomer) { if (remain == 0) { combiCustomer[s]++; return; } if (idx > end_idx) return; combi(s + order[idx], remain - 1, idx + 1, end_idx, order, combiCustomer); combi(s, remain, idx + 1, end_idx, order, combiCustomer); } //손님의 주문으로 만드는 모든 조합을 계산한다. //길이 순으로 정렬한다. map makeCombi(vector &orders) { map combiCustomer; for (int i = 0; i < orders.size(); i++) for (int j = 2; j <= orders[i].size(); j++) combi("", j, 0, orders[i].size() - 1, orders[i], combiCustomer); return combiCustomer; } bool cmp(pair& a, pair& b) { //크기가 같을경우. if (a.first.size() == b.first.size()) return a.second > b.second; return a.first.size() < b.first.size(); } vector solution(vector orders, vector course) { for (int i = 0; i < orders.size(); i++) sort(orders[i].begin(), orders[i].end()); map m = makeCombi(orders); vector> vec(m.begin(), m.end()); sort(vec.begin(), vec.end(), cmp); return make_res(vec, course); } int main() { vector s = solution({ "ABCDE", "AB", "CD", "ADE", "XYZ", "XYZ", "ACD" }, { 2, 3, 5 }); cout << "\n"; } //["AC", "ACDE", "BCFG", "CDE"] ================================================ FILE: programmers/난이도별/level02.메뉴_리뉴얼/rockmiin.py ================================================ import itertools from collections import defaultdict def solution(orders, course): ans= [] # dict 안에 없는 key값이더라도 자동으로 추가해주려고 defaultdict를 사용 menu_dict= [defaultdict(lambda :0) for _ in range(len(course))] for idx in range(len(course)): for menu in orders: # sorted를 안해주게 되면 WX와 XW를 다른 메뉴로 구분하게 됨 menu_list= sorted(list(menu)) if len(menu_list) < idx: continue # "".join을 사용하면 리스트를 문자열로 쉽게 변환할 수 있다 for k in list(itertools.combinations(menu_list, course[idx])): menu_dict[idx]["".join(k)]+=1 for idx in range(len(course)): # menu_dict에서 최대값과 같은 모든 key 값을 ans에 append for k, v in menu_dict[idx].items(): if v== max(menu_dict[idx].values()) and v>1: ans.append(k) return sorted(ans) solution(["XYZ", "XWY", "WXA"], [2,3,4]) ================================================ FILE: programmers/난이도별/level02.메뉴_리뉴얼/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/72411 메뉴 리뉴얼 [풀이] 1. dictionary와 combinations 사용 ''' from itertools import combinations def solution(orders, course): result = [] for c in course: count = {} for order in orders: for o in combinations(order , c): key = ''.join(sorted(o)) count.setdefault(key, 0) count[key] += 1 if len(count.keys()) == 0: break max_count = count[max(count, key=count.get)] if max_count > 1: for key in count.keys(): if count[key] == max_count: result.append(key) return sorted(result) ''' `get` 을 사용해 Key로 Value를 얻을 수 있다 또, 아래 코드와 같이 collections.Counter(param).most_common() 을 사용해서 가장 많이 나온 원소를 셀 수 있다 import collections for course_size in course: order_combinations = [] for order in orders: order_combinations += itertools.combinations(sorted(order), course_size) most_ordered = collections.Counter(order_combinations).most_common() result += [ k for k, v in most_ordered if v > 1 and v == most_ordered[0][1] ] ''' ================================================ FILE: programmers/난이도별/level02.모음사전/6047198844.py ================================================ from itertools import product def solution(word): dict_words = [] candidate = ['A', 'E', 'I', 'O', 'U'] for pick_n in range(1, 5 + 1): for dict_word in product(candidate, repeat=pick_n): dict_words.append(''.join(dict_word)) dict_words.sort() return dict_words.index(word) + 1 ================================================ FILE: programmers/난이도별/level02.문자열압축/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/60057 ================================================ FILE: programmers/난이도별/level02.문자열압축/eyabc.js ================================================ const JSTestModule = require('/Users/ey/DKU/Algorithm/JSTestModule.js'); const getZippedLength = (unit, str, strLen) => { let zippedStr = ''; let pos = unit, currStr = str.slice(0, unit), currRepeat = 1; const newStr = () => ((currRepeat === 1) ? '' : currRepeat) + currStr; while (pos < strLen) { const nextStr = str.slice(pos, pos + unit); if (currStr === nextStr) currRepeat++; else { zippedStr += newStr(); [currStr, currRepeat] = [nextStr, 1]; } pos += unit; } zippedStr += newStr(); return zippedStr.length; }; function solution (s) { const strLen = s.length; const maxUnit = strLen / 2 + 1; let shortestLen = strLen; for (let unit = 1 ; unit < maxUnit ; unit++) { const zippedLen = getZippedLength(unit, s, strLen); shortestLen = Math.min(shortestLen, zippedLen); } return shortestLen; } JSTestModule('/Users/ey/DKU/Algorithm/programmers/카카오/문자열압축/test.json', solution); ================================================ FILE: programmers/난이도별/level02.문자열압축/junilhwang.js ================================================ function solution(s) { const stack = [] const len = s.length let min = len loop: for (let i = 1; i < ~~(len/2) + 1; i++) { let word = s.substr(0, i), temp = '', cnt = 1, j = i while (true) { const next = s.substr(j, i) if (word === next) { cnt += 1 } else { temp += `${cnt > 1 ? cnt : ''}${word}` word = next cnt = 1 } if (temp.length > min) continue loop if (j > len) break j+=i } //console.log(i, min, temp) if (min > temp.length) min = temp.length } return min; } // console.log(solution("aabbaccc"), 7) // console.log(solution("ababcdcdababcdcd"), 9) // console.log(solution("abcabcdede"), 8) // console.log(solution("abcabcabcabcdededededede"), 14) // console.log(solution("xababcdcdababcdcd"), 17) ================================================ FILE: programmers/난이도별/level02.문자열압축/sangmandu.py ================================================ ''' 문자열 압축 https://programmers.co.kr/learn/courses/30/lessons/60057 ''' def solution(s): size = len(s) answer = size for i in range(1, size): top = s[:i] newStr = "" cnt = 1 for j in range(1, size // i + (1 if size % i == 0 else 2)): if top == s[i*j:i*(j+1)]: cnt += 1 continue if cnt >= 2: newStr += str(cnt) newStr += str(top) top = s[i*j:i*(j+1)] cnt = 1 answer = min(answer, len(newStr)) return answer ''' ''' ================================================ FILE: programmers/난이도별/level02.방문_길이/6047198844.py ================================================ import collections def solution(dirs): answer = 0 position = (0, 0) table = { 'U' : (-1, 0), 'D' : (+1, 0), 'L' : (0, -1), 'R' : (0, +1) } res = set() for dir in dirs: y, x= position dy, dx = table[dir] ny, nx = y + dy, x + dx if -5 <= ny <= 5 and -5 <= nx <= 5: nposition = (ny, nx) res.add((position, nposition)) res.add((nposition, position)) position = nposition return len(res) // 2 ================================================ FILE: programmers/난이도별/level02.배달/6047198844.py ================================================ import collections import heapq def solution(N, roads, K): answer = 0 graph = collections.defaultdict(list) for road in roads: i, j, cost = road graph[i].append((j,cost)) graph[j].append((i,cost)) Q = [] heapq.heappush(Q,(0,1)) distance = collections.defaultdict(int) while Q: time, node = heapq.heappop(Q) if time > K: break if node not in distance: distance[node] = time for k, v in graph[node]: alt = time + v heapq.heappush(Q,(alt,k)) return len(distance) ================================================ FILE: programmers/난이도별/level02.삼각_달팽이/6047198844.cpp ================================================ #include #include #include using namespace std; vector solution(int n) { int arr[1000][1000]; int current_y = -1; int current_x = 0; int num = 0; int add_y[3] = { +1,0,-1 }; int add_x[3] = { 0,+1,-1 }; for (int i = 0; i < n; i++) { for (int j = 0; j < n-i; j++) { num++; current_y += add_y[i % 3]; current_x += add_x[i % 3]; arr[current_y][current_x] = num; } } vector answer; for (int y = 0; y < n; y++)for (int x = 0; x <= y; x++) { if (arr[y][x]) answer.push_back(arr[y][x]); } return answer; } int main() { solution(4); } ================================================ FILE: programmers/난이도별/level02.삼각_달팽이/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/68645 삼각 달팽이 [풀이] 1. 삼각형의 테두리부터 반시계방향으로 1을 채워넣기 2. 머리, 몸통, 꼬리로 나누어서 합치기, 이 때 인덱스를 점화식으로 생각했음. ''' def snail(n, s): if n == 1: return [[s - 1]] elif n == 2: return [[s - 1], [s, s + 1]] elif n == 3: return [[s - 1], [s, s + 4], [s + 1, s + 2, s + 3]] head = [[s - 1], [s, s + 3 * n - 5]] body = [[a, 2 * s + 3 * n - 5 - a] for a in range(s + 1, s + n -2)] tail = [[i for i in range(s + n - 2, s + 2 * n - 2)]] entity = [] for i, j in zip(body, snail(n - 3, s + 3 * n - 3)): entity += [[i[0]] + j + [i[1]]] return head + entity + tail def solution(n): return sum(snail(n, 2), []) ''' 수학처럼이 아니라, 컴퓨터 처럼 풀었어야 했던 것 같다. 삼각형의 각 진행방향에 따라 dx와 dy를 나눠서 구현한 풀이를 보고 본인의 s와 n으로 구성된 점화식으로 구현한 풀이를 보니 너무나도 어렵게 풀었구나 생각이 들음. def solution(n): dx=[0,1,-1];dy=[1,0,-1] b=[[0]*i for i in range(1,n+1)] x,y=0,0;num=1;d=0 while num<=(n+1)*n//2: b[y][x]=num ny=y+dy[d];nx=x+dx[d];num+=1 if 0<=ny #include #include using namespace std; bool check[50001]; void Sieve(){ int n = 50000; memset(check,false,sizeof(bool)*50001); check[1] = true; for(int i =1;i<=50000;i++){ if(!check[i]) for(int j = i+i; j<50000;j+=i) check[j]=true; } return; } int brute_force(int idx,int sum, int cnt, vector &nums){ if(cnt==3){ if(!check[sum]) return 1; else return 0; } if(idx==nums.size()) return 0; int pick = brute_force(idx+1,sum+nums[idx], cnt+1, nums); int non_pick = brute_force(idx+1,sum, cnt, nums); return pick+non_pick; } int solution(vector nums) { Sieve(); return brute_force(0,0,0, nums); } ================================================ FILE: programmers/난이도별/level02.소수_만들기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12977 문제 : 소수 만들기 3개의 조합을 만드느라 애쓰다가 결국 검색 찬스로 itertools라는 것을 알게 됐습니다. 저번주 은행 코테에서 itertools를 알고 있었으면 풀 수 있었을 문제가 있던터라 너무나 아쉽...〒▽〒 저는 prime 변수를 추가로 이용해서 break 했는지 확인하였는데 for else문을 사용하면 별도의 변수 지정 없이 바로 확인이 가능하더라구요!!! ''' from itertools import combinations def solution(nums): answer = 0 com = list(combinations(nums,3)) for i in com : prime = True s = sum(i) for j in range(2,s//2+1) : if s%j == 0 : prime = False break if prime : answer += 1 return answer ================================================ FILE: programmers/난이도별/level02.소수_만들기/s2uyeoii.cpp ================================================ #include #include using namespace std; bool primenum(int n) { if (n <2) return false; for (int i = 2; i < n / 2; i++) { if (n % i == 0) return false; } return true; } int solution(vector nums) { int answer = 0; int numSize = nums.size(); int sum = 0; for (int i = 0; i < numSize; i++) { for (int j = i + 1; j < numSize; j++) { for (int k = j + 1; k < numSize; k++) { sum = nums[i] + nums[j] + nums[k]; if (primenum(sum)) answer++; } } } return answer; } ================================================ FILE: programmers/난이도별/level02.소수_만들기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12977 소수 만들기 ''' from itertools import combinations def solution(nums): nums = sorted([sum(i) for i in combinations(nums, 3)]) rear = nums[-1] sieve = [True] * (rear + 1) for i in range(2, rear + 1): if sieve[i] == True: for j in range(i + i, rear + 1, i): sieve[j] = False return [sieve[i] for i in nums].count(True) ''' ''' ================================================ FILE: programmers/난이도별/level02.소수_찾기/6047198844.cpp ================================================ #include #include #include #include using namespace std; bool prime[9999999]; // false이면 소수 bool check[7]; set s; void sieve() { memset(prime, false, sizeof(bool) * 9999999); prime[0] = prime[1] = true; for (int i = 2; i < 3200; i++) { if (!prime[i]) for (int j = i + i; j <= 9999999; j+=i) prime[j] = true; } } void brute_force(string numbers, string string_n, int n,int cnt) { if (cnt == n) { int check_prime = stoi(string_n); if (!prime[check_prime]) s.insert(check_prime); return; } int number_size = numbers.size(); for (int i = 0; i < number_size; i++) { if (!check[i]) { check[i] = true; brute_force(numbers, string_n + numbers[i], n,cnt+1); check[i] = false; } } } int solution(string numbers) { int answer = 0; sieve(); int numbers_size = numbers.size(); memset(check, false, sizeof(bool) * 7); for (int i = 1; i <= numbers_size; i++) brute_force(numbers, "", i,0); answer = s.size(); return answer; } ================================================ FILE: programmers/난이도별/level02.소수_찾기/Jaewon0702.py ================================================ import itertools def solution(numbers): permutation=[] for i in range(1,len(numbers)+1) : #모든 경우의 수 permutation+=list((map(int,map(''.join,itertools.permutations(numbers,i))))) permutation=set(permutation); permutation-=set(range(0,2)) m=max(permutation) for i in range(2,int(m**0.5)+1) : #에라토스테네스의 체 permutation-=set(range(i*2,m+1,i)) return len(permutation) #100점 print(solution("011")==2) print(solution("17")==3) ================================================ FILE: programmers/난이도별/level02.소수_찾기/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42839 function solution(numbers) { const arr = Array.from(numbers) const answer = new Set(); const f = n => { if (n < 2) return false for (let i = 2; i <= ~~(n / 2); i++) if (n % i === 0) return false return true } const len = arr.length const f2 = p => { const n = p.map(k => arr[k]).join('')*1 if (f(n)) answer.add(n) if (p.length === len) return arr.forEach((v, k) => {if (p.indexOf(k) === -1) f2([...p, k])}) } arr.forEach((v, k) => f2([k])) return answer.size; } console.log(solution("17"), 3) console.log(solution("011"), 2) ================================================ FILE: programmers/난이도별/level02.소수_찾기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/70128 소수 찾기 [풀이] 1. 주어진 숫자로 만들 수 있는 모든 수에 대한 소수 판별 2. 조합 사용 ''' from itertools import permutations def solution(numbers): num = list(set(map(int, sum([list(map(''.join, permutations(numbers, i))) for i in range(1, len(numbers)+1)], [])))) answer = 0 for n in num: if all([(n%i) for i in range(2, int(n**0.5)+1)] + [n > 1]): answer += 1 return answer ''' 에라토스테네스 채를 사용하고 싶었는데, 마땅히 생각이 안났다 아래와 같이 풀이 가능 from itertools import permutations def solution(n): a = set() for i in range(len(n)): a |= set(map(int, map("".join, permutations(list(n), i + 1)))) a -= set(range(0, 2)) for i in range(2, int(max(a) ** 0.5) + 1): a -= set(range(i * 2, max(a) + 1, i)) return len(a) ''' ================================================ FILE: programmers/난이도별/level02.쇠막대기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42585 ================================================ FILE: programmers/난이도별/level02.쇠막대기/dkdlelk99.py ================================================ def solution(arrangement): stack = [] answer = 0 arrangement = arrangement.replace("()", "|") for i in arrangement: if i == '(': stack.append(i) elif i == ')': stack.pop() answer += 1 else: answer += len(stack) return answer print(solution("()(((()())(())()))(())") == 17) ================================================ FILE: programmers/난이도별/level02.쇠막대기/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42586?language=javascript function solution(progresses, speeds) { var answer = []; while (progresses.length) { if (progresses.length === 1) { answer.push(1) break } for (let i = 0, len = progresses.length; i < len; i++) { if (progresses[i] < 100) progresses[i] += speeds[i] } let num = 0 while (progresses[0] >= 100) { num += 1, progresses.shift(), speeds.shift() } if (num > 0) answer.push(num) } return answer; } console.log(solution([1, 93, 30, 99], [99, 1, 29, 5])) ================================================ FILE: programmers/난이도별/level02.수식_최대화/6047198844.cpp ================================================ #include #include #include #include using namespace std; long long caluate(vector token) { string pmm = "*+-"; long long max_num = -1; do { vector res = token; for (char sign : pmm) { if (sign == '-') { for (int i = 1; i < res.size(); i += 2) { if (res[i] == "-") { res.insert(res.begin() + i - 1, to_string(stoll(res[i - 1]) - stoll(res[i + 1]))); res.erase(res.begin() + i, res.begin() + i + 3); i += -2; } } } else if (sign == '+'){ for (int i = 1; i < res.size(); i += 2) { if (res[i] == "+") { res.insert(res.begin() + i - 1, to_string(stoll(res[i - 1]) + stoll(res[i + 1]))); res.erase(res.begin() + i, res.begin() + i + 3); i += -2; } } } else { for (int i = 1; i < res.size(); i += 2) { if (res[i] == "*") { res.insert(res.begin() + i - 1, to_string(stoll(res[i - 1]) * stoll(res[i + 1]))); res.erase(res.begin() + i, res.begin() + i + 3); i += -2; } } } } max_num = max_num < abs(stoll(res[0])) ? abs(stoll(res[0])) : max_num; } while (next_permutation(pmm.begin(), pmm.end())); return max_num; } vector tokenize(string expression) { vector token; int expression_size = expression.size(); for (int i = 0; i < expression_size; i++) { string num; while ('0' <= expression[i] && expression[i] <= '9') { num += expression[i]; i++; } token.push_back(num); string sign; sign += expression[i]; if (i != expression_size) token.push_back(sign); //to_string은 정수형으로 바꾼뒤 string으로 바꾼다. } return token; } long long solution(string expression) { vector res = tokenize(expression); return caluate(res); } int main() { solution("100-200*300-500+20"); } ================================================ FILE: programmers/난이도별/level02.수식_최대화/rockmiin.py ================================================ import re from itertools import permutations def solution(expression): ans= 0 # 정규 표현식으로 num과 op를 나눠줌 num= re.findall('\d+', expression) op= re.findall('[-*+]', expression) # order list는 어차피 6개니까 내가 리스트로 줘도 된다 그러면 연산 시간 내려감 order_list= list(permutations(set(op), len(set(op)))) # print(num) # print(op) # print(order_list) for order in order_list: tmp_num= num[:] tmp_op= op[:] # print(order) for o in order: i= 0 while(i ans: ans= abs(tmp_num[0]) return ans print(solution("100-200*300-500+20")) ================================================ FILE: programmers/난이도별/level02.수식_최대화/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/67257 수식 최대화 [풀이] 1. +-*의 순열에 따라 모든 반복문 진행. 이후 피연산자 연산자 피연산자를 피연산자의 꼴로 바꿈. ''' from itertools import permutations def solution(expression): operator = ['+', '-', '*'] exp = '' for i in expression: exp += f" {i} " if i in operator else i exp = exp.split() num = 0 for i in list(permutations(operator, 3)): copy = exp[:] for j in i: while j in copy: idx = copy.index(j) copy[idx] = str(eval(copy[idx - 1] + j + copy[idx + 1])) copy.pop(idx + 1) copy.pop(idx - 1) num = max(num, abs(int(copy[0]))) return num ''' ''' ================================================ FILE: programmers/난이도별/level02.순위_검색/6047198844.py ================================================ #정확성 테스트 통과 효율성 테스트 통과 X import collections import re import bisect from functools import reduce def solution(info, query): answer = [] #info를 기준으로 dictionary를 만든다. kind_table = collections.defaultdict(set) score_table = collections.defaultdict(set) #info를 나누어 테이블에 담는다. for idx, info_ in enumerate(info): *kind_info, score_info = info_.split() for kind in kind_info: kind_table[kind].add(idx) score_table[int(score_info)].add(idx) score_table = sorted(score_table.items(), key = lambda x:x[0]) for query_ in query: *splited_query, score = query_.replace('-','').replace('and','').split() group_score, group = zip(*score_table) score_idx = bisect.bisect_left(group_score, int(score)) res = set().union(*group[score_idx:]) for q in splited_query: res &= kind_table[q] answer.append(len(res)) return answer #효율성 테스트 통과 import heapq from bisect import bisect_left from collections import defaultdict from itertools import combinations def solution(infos, queries): answer = [] #타입에 따라 table에 담는다. table = defaultdict(list) #info를 타입과 점수로 분리한다. for info in infos: *info_type, info_score = info.split() #해당 타입으로 만들수있는 모든 경우의수에(쿼리도 나올수있는 경우의 수) 점수를 저장한다. for i in range(5): for c in combinations(info_type,i): table[''.join(c)].append(int(info_score)) #bisect를 위해서 정렬. for v in table.values(): v.sort() #쿼리로 검색한다. for query in queries: *query_type, query_score = query.replace('-','').replace('and','').split() query_type = ''.join(query_type) n = len(table[query_type]) - bisect_left(table[query_type], int(query_score)) answer.append(n) return answer ================================================ FILE: programmers/난이도별/level02.순위_검색/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/72412 순위 검색 [풀이] 1. dictionary 고급 문제 2. bisect 사용 ''' from itertools import product from bisect import bisect_left as bisl def solution(info, query): dic = {} for words in info: words = words.split() words, score = words[:-1], int(words[-1]) for word in product(*zip(words, '-' * 4)): key = ''.join(word) dic.setdefault(key, []) dic[''.join(word)].append(score) for key in dic.keys(): dic[key].sort() answer = [] for q in query: q = q.replace('and ', '').split() q, score = ''.join(q[:-1]), int(q[-1]) arr = dic.get(q) if arr == None: answer.append(0) else: answer.append(len(arr) - bisl(arr, score)) return answer ''' 이건 미친 문제이다. 설마 이거야? 했던 풀이방법으로 풀어야 되는 문제. 정답률이 5%에 안되는 문제인데 level02 에 존재하면 안된다. 실제 시험볼 때도 못풀었다 ㅠ 지금도 못풀어서 카카오 공식 풀이 보다가 dictionary로 풀으라길래 푼 문제.. 미친 풀이가 있는데, 각 매칭을 비트 연산자 방식으로 생각한 것이 독특하다. 심지어 코드도 간결 from functools import reduce from collections import defaultdict from bisect import insort, bisect_left def solution(info, query): table = {"c": 3, "j": 5, "p": 6, "b": 6, "f": 5, "s": 6, "-": 0} conv = lambda l, t: (reduce(lambda a, k: (a << 3) + t(table[k[0]]), l[:-1], 0), int(l[-1])) info = list(map(lambda s: conv(s.split(" "), lambda x: 7 - x), info)) query = list(map(lambda s: conv([c for c in s.split(" ") if c != "and"], lambda x: x), query)) d = defaultdict(list) for k, v in info: insort(d[k], v) return [sum([len(l) - bisect_left(l, v) for k, l in d.items() if not k & q]) for q, v in query] ''' ================================================ FILE: programmers/난이도별/level02.숫자의_표현/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12924# 문제 : 숫자의 표현 단순히 중첩 for문을 이용해서 정말로 연속한 자연수의 합이 n과 같은지 확인하는 방법으로 구했다. 그런데 다른 사람들 풀이를 보니 약수중 홀수의 개수로 구하면 된다고 한다. 사실 열심히 읽어보고 이해해보려 했으나 이해가 잘 안됨... [메모] len([i for i in range(1,num+1,2) if num%i==0]) ''' def solution(n): answer = 0 num = 0 for i in range(1,n+1) : for j in range(i,n+1) : num += j if num==n : answer += 1 break elif num>n : num = 0 break return answer ================================================ FILE: programmers/난이도별/level02.숫자의_표현/HyeonJeong.py ================================================ import math def solution(n): answer = 0 for i in range(1, math.ceil(n/2)): total = 0 for j in range(i, n): total += j if total == n: answer += 1 if total >= n: break return answer + 1 # n = n print(solution(15) == 4) ================================================ FILE: programmers/난이도별/level02.숫자의_표현/README.md ================================================ #출처 https://programmers.co.kr/learn/courses/30/lessons/12924 ================================================ FILE: programmers/난이도별/level02.숫자의_표현/khw970421.js ================================================ function solution(n) { let answer=0; let count=0; for(let i=1;i<=n;i++) { answer=0; for(let j=i;j<=n;j++) { answer+=j; // i부터 하나씩 계속 더하기 if(answer==n){ //값이 같아지면 count 증가와 break count++; break; } else if(answer>n){ //값이 더 커지면 필요없으므로 진행 안하게 break break; } } } return count; // 연속으로 더한 값들의 count 반환 } //출처 : https://programmers.co.kr/learn/courses/30/lessons/12924 // 이게 가장 효율도 문제없이 한것 같습니다.... //피드백 받아서 수정 function solution(n) { let answer=0; let count=0; for(let i=1;i<=n;i++) { answer=0; for(let j=i;j<=n && n > answer; j++) { answer+=j; // i부터 하나씩 계속 더하기 if (answer === n) count += 1; } } return count; } ================================================ FILE: programmers/난이도별/level02.숫자의_표현/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12924 숫자의 표현 ''' def solution(n): cnt = 0 for i in range(1, n): sumN = 0 while sumN < n: sumN += i i += 1 if sumN == n: cnt += 1 return cnt + 1 ''' 말도 안되는 등차 수열 공식.. def expressions(num): return len([i for i in range(1,num+1,2) if num % i is 0]) ''' ================================================ FILE: programmers/난이도별/level02.스킬트리/HyeonJeong.py ================================================ def solution(skill, skill_trees): answer = 0 slist = [""]*len(skill_trees) for i, x in enumerate(skill_trees): for y in x: if y in skill: slist[i] += y for j in slist: if skill.find(j) == 0: answer += 1 return answer print(solution("CBD", ["BACDE", "CBADF", "AECB", "BDA"])== 2) ================================================ FILE: programmers/난이도별/level02.스킬트리/README.md ================================================ #출처 https://programmers.co.kr/learn/courses/30/lessons/49993 ================================================ FILE: programmers/난이도별/level02.스킬트리/desktop.ini ================================================ [.ShellClassInfo] LocalizedResourceName=@level02.ųƮ,0 ================================================ FILE: programmers/난이도별/level02.스킬트리/dkdlelk99.py ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/49993 # skill 선행 스킬 순서 문자열, (1이상 26이하) # skill_trees 검사해봐야할 스킬트리 문자열(2이상 26이하)들의 리스트(1이상 20이하) # 선후수를 만족하는 스킬트리의 갯수 return def solution(skill, skill_trees): answer = 0 len_skill = len(skill) for tree in skill_trees: order = [] for i in range(len_skill):# order 리스트에 skill의 index를 찍어줌 order.append(tree.find(skill[i])) for i in range(len_skill):# ex) [3, 5, 1, -1, -1] => [3, 5, 1]로 만들어줌 if order[-1] == -1: order.pop() else: break if order == []: answer += 1 else: if order[0] == -1: continue elif order == sorted(order): answer += 1 return answer print(solution("CBD",["BACDE", "CBADF", "AECB", "BDA"]), \ solution("CBD",["BACDE", "CBADF", "AECB", "BDA"]) == 2) print(solution("abc", ["adbic", "ajrgp", "bcida","aicls", "bdgs", "abc","qwer"]), \ solution("abc", ["adbic", "ajrgp", "bcida","aicls", "bdgs", "abc","qwer"]) == 4) # my test case ================================================ FILE: programmers/난이도별/level02.스킬트리/eyabc.js ================================================ /** * 스킬트리 * 문제 : https://programmers.co.kr/learn/courses/30/lessons/49993 * @param skill 선행 스킬 순서 / 알파벳 대문자 (1~26자) 중복스킬 없음, * @param skill_trees 유저들이 만든 스킬트리 (1~20개) (2~26자) * return : 가능한 스킬트리 개수 * * 아이디어 */ function solution(skill, skill_trees) { const reg = new RegExp(`[${skill}]`, 'g'); return skill_trees.reduce((cnt, user_skill) => { const found = user_skill.match(reg); const res = found && found.every((user, j) => user === skill[j]); if (res || !found) cnt++; return cnt }, 0); } console.log(solution('CBD', ['BACDE', 'CBADF', 'AECB', 'BDA']) === 2); console.log(solution('C', ['A']) === 1); // 8개월 전에 푼것? function solution2(skill, skill_trees) { let cnt = 0; let str = skill.split(''); let tree = skill_trees.map((i, ki) => { let re = new RegExp(`[${str}]`); if (!re.exec(i)) cnt++; return i.split(''); }).forEach(i => { let que = []; i.forEach((j, jk) => str.forEach(k => k === j ? que.push(j) : '')); que.some((q, qk) => { if (q !== str[qk]) { return true; } else if (q === str[qk] && qk === que.length - 1) { cnt++; } }); }); return cnt; } ================================================ FILE: programmers/난이도별/level02.스킬트리/rockmiin.py ================================================ def solution(skill, skill_trees): ans = 0 skill = list(skill) for tree in skill_trees: tmp= [] for s in tree: if s in skill: tmp.append(s) if tmp == []: ans += 1; continue idx = 0 for i in range(len(tmp)): if tmp[i] == skill[idx] and idx < len(skill): idx += 1 elif idx < len(skill) - 1 and tmp[i] in skill[idx + 1:]: break; else: ans += 1 return ans ================================================ FILE: programmers/난이도별/level02.스킬트리/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/49993 스킬트리 선후수 관계를 지켜야 하는 문자열 찾기 ''' import re def solution(skill, skill_trees): order = [i+'|' for i in skill] match = [re.findall(''.join(order)[:-1], i) for i in skill_trees] return [skill[:len(i)] == ''.join(i) for i in match].count(True) ''' ''' ================================================ FILE: programmers/난이도별/level02.압축/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/17684 문제 : [3차] 압축 문자열이라서 신난다고 re로 풀었는데 re.match 안에 dictionary 값을 넣을 수는 없어서 포기했다. 나만 또 이상하게 풀고 있는건 아닌가 했는데 다행히 많은 사람들이 dictionary의 key를 이용해서 풀었다. key에 알파벳을 넣고, value에 값을 넣어 key에 없으면 새로운 값을 추가하는 방식으로 문제를 풀었다. dictionary는 한 줄로 초기화가 안 될 줄 알았는데 다른 사람들 풀이를 보니 :로 할 수 있었다. [메모] dic_alpha = {chr(e+64): e for e in range(1,27)} ''' def solution(msg): answer = [] start = 0 # 사전에 값 추가 후 인덱스 슬라이싱 시작 부분 변경 end = 26 # 사전의 마지막 숫자 기억 dic_match = '' # 알파벳 대문자 사전 dic_alpha = {} for i in range(26) : dic_alpha[chr(i+65)] = i+1 for i in range(1,len(msg)+2) : dic_match = msg[start:i] if (dic_match not in dic_alpha.keys()) : # 현재 입력과 일치하는 가장 긴 문자열 찾기 answer.append(dic_alpha[msg[start:i-1]]) end += 1 dic_alpha[dic_match] = end start = i-1 answer.append(dic_alpha[dic_match]) return answer ================================================ FILE: programmers/난이도별/level02.영어_끝말잇기/6047198844.cpp ================================================ #include #include #include #include using namespace std; vector solution(int n, vector words) { //index%인원수 + 1 -> 번호 / (index/인원수) + 1 -> 차례 //체크해야 할것 //1. 뒤와 앞이 맞는지 //2. 중복된 글자인지 -> map map mp; mp[words[0]] = true; int words_size = words.size(); for(int i=1;i using namespace std; int solution(int n, int a, int b) { int cnt; for(cnt = 0;a!=b;cnt++){ a = a/2 + a%2; b = b/2 + b%2; } return cnt; } ================================================ FILE: programmers/난이도별/level02.예상_대진표/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12985 예상 대진표 2의 제곱승 이용 ''' import math def solution(n,a,b): m = int(math.log2(n)) for i in range(1, m+1): if (a-1) // (2 ** i) == (b-1) // (2 ** i): return i ''' 이진수 문제는 비트연산자를 이용하는 것이 확실히 간단한 것 같다. def solution(n,a,b): return ((a-1)^(b-1)).bit_length() ''' ================================================ FILE: programmers/난이도별/level02.오픈채팅방/6047198844.cpp ================================================ //map을 사용 #include #include #include #include #include #include using namespace std; vector solution(vector record) { vector answer; //Enter이나 Change일때 바꾼다. map mp; vector > vt; mp["Enter"] = "들어왔습니다."; mp["Leave"] = "나갔습니다."; int end_idx = record.size(); string commend; string user_id; string user_name; for (int i = 0; i < end_idx; i++) { char str_buff[50]; strcpy(str_buff, record.at(i).c_str()); char* tok = strtok(str_buff, " "); commend = string(tok); tok = strtok(nullptr, " "); user_id = string(tok); if (commend == "Enter" || commend == "Leave") vt.push_back({ user_id,commend }); if (commend == "Leave") continue; tok = strtok(nullptr, " "); mp[user_id] = string(tok); } int vt_size = vt.size(); for (int i = 0; i < vt_size; i++) { string temp = mp[vt[i][0]] + "님이 " + mp[vt[i][1]]; answer.push_back(temp); } return answer; } int main() { solution({ "Enter uid1234 Muzi", "Enter uid4567 Prodo", "Leave uid1234", "Enter uid1234 Prodo", "Change uid4567 Ryan" }); } ================================================ FILE: programmers/난이도별/level02.오픈채팅방/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42888 오픈채팅방 가장 마지막에 Enter 또는 Change 된것이 최종 닉네임 ''' def solution(record): uid = {} for i in record: if i[0] == "L": continue b, c = i.split()[1:] uid[b] = c answer = [] for i in record: if i[0] == "C": continue a, b = i.split()[:2] answer.append(f"{uid[b]}님이 들어왔습니다." if a == "Enter" else f"{uid[b]}님이 나갔습니다.") return answer ''' ''' ================================================ FILE: programmers/난이도별/level02.올바른_괄호/6047198844.cpp ================================================ #include #include using namespace std; bool solution(string s) { int cnt = 0; for(auto idx : s){ if(idx=='(') cnt++; else cnt--; if(cnt<0) return false; } return cnt==0; } ================================================ FILE: programmers/난이도별/level02.올바른_괄호/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12909 문제 : 올바른 괄호 '(' 개수와 ')' 개수를 세서 비교하였습니다. 다른 사람 풀이를 보니 0에서부터 시작해서 '('면 +1, ')'면 -1을 해서 -가 될 때와 최종 결과가 0이 아닐 때 FALSE를 return 하면 변수를 한 개만 만들어도 되고 '('와 ')'의 개수가 같은지도 추가로 비교하지 않아도 되더라구요 ''' def solution(s): answer = True if s.count('(') != s.count(')') : return False s = list(s) open_count, close_count = 0,0 for i in s : if close_count > open_count : return False if i == '(' : open_count += 1 else : close_count += 1 return True ================================================ FILE: programmers/난이도별/level02.올바른_괄호/HyeonJeong.py ================================================ def solution(s): stack = [] for i, n in enumerate(s): if n == '(': stack.append('(') elif n == ')': if stack == []: return False stack.pop() return stack == [] print( solution('()()') == True, solution('(())()') == True, solution(')()(') == False, solution('(()(') == False ) ================================================ FILE: programmers/난이도별/level02.올바른_괄호/JeongShin.js ================================================ function solution(s) { let top = 0; for (const curr of s) { if (curr === "(") top++; if (curr === ")") { if (top === 0) return false; top--; } } return top === 0 } solution("()()"); ================================================ FILE: programmers/난이도별/level02.올바른_괄호/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12909 ================================================ FILE: programmers/난이도별/level02.올바른_괄호/dkdlelk99.py ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12909 # input '(' 또는 ')'으로만 이루어진 문자열 s # output 올바른 괄호인지 아닌지에 대한 bool 값 def solution(s): a ='' if s.count('(') == s.count(')'): for i in s: a += i if a[-2:] == '()': a = a[:-2] return True if a == '' else False else: return False print(solution("()()")) print(solution("(())()")) print(solution(")()(")) print(solution("(()(")) ================================================ FILE: programmers/난이도별/level02.올바른_괄호/khw970421.js ================================================ //효율성문제 발생 (for문안에 split,join을 사용해서일듯) function solution(s){ let a,b; const s_length= s.length; for(let i=s.indexOf('()');i0 ? false :true } //정확성+효율성 =100 // ()가 묶이려면 기본적으로 왼쪽에서부터 오른쪽으로 진행할때 )의 갯수가 (갯수보다 많으면 ()묶여 처리가 불가능 // 위에 의미는 )가 나오면 1감소 (가 나오면 1증가 할때 총합이 0보다 작아지면 ()묶여 처리 불가능 // 좀 더 map같은 함수를 써보고 싶은데 if else와 더불어 반복문을 줄이기 위해 if가 더있어서 map으로 바꾸기 골치아프다 // (문제 효율성이 좀 이상한지 enter가 하나 더 있는곳은 효율성 문제없고 enter가 하나 없으면 효율성 문제 뜨고 좀 이상하다) function solution(s){ const s_length = s.length; let answer=0; s=s.split(''); for(let i=0;i0 ? false: true; //return answer === 0; } //출처 : https://programmers.co.kr/learn/courses/30/lessons/12909 ================================================ FILE: programmers/난이도별/level02.올바른_괄호/s2uyeoii.c ================================================ #include #include #include #include // 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요. bool solution(const char* s) { int sum = 0; int len = strlen(s); if(s[0]=='(' && s[len-1]==')'){ for(int i = 0; i #include #include #include using namespace std; int solution(vector> clothes) { map clothes_cnt; int answer = 1; for (auto c : clothes) clothes_cnt[c[1]]++; for (auto m : clothes_cnt) answer *= (m.second + 1); answer--; return answer; } ================================================ FILE: programmers/난이도별/level02.위장/HyeonJeong.py ================================================ def solution(clothes): answer = 1 num = 0 length = len(clothes) list = set([clothes[i][1] for i in range(length)]) for n in list: for m in clothes: if n == m[1]: num += 1 answer *= num + 1 # 그 옷을 입지 않는 경우로 + 1 num = 0 return answer - 1 # 전부 입지 않는 경우로 -1 print( solution([['yellow_hat', 'headgear'], ['blue_sunglasses', 'eyewear'], ['green_turban', 'headgear']]) == 5, solution([['crow_mask', 'face'], ['blue_sunglasses', 'face'], ['smoky_makeup', 'face']]) == 3 ) ================================================ FILE: programmers/난이도별/level02.위장/Jaewon0702.py ================================================ def solution(clothes): kind_count={} for v in clothes : key=v[len(v)-1] kind_count[key]=kind_count.get(key,0)+1 combination=1 for i in kind_count.values() : combination*=(i+1) return combination-1 #점수 : 100점 cl=[['y','d'],['b','c'],['g','h'],['c','h'],['c','h']] print(solution(cl)) ================================================ FILE: programmers/난이도별/level02.위장/JeongShin.js ================================================ function solution(clothes) { const count = {} for (const c of clothes) count[c[1]] = (count[c[1]] || 0) + 1 return Object.values(count).reduce((acc, curr) => { return acc * (curr + 1) }, 1) - 1; } solution([["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]) ================================================ FILE: programmers/난이도별/level02.위장/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42578 ================================================ FILE: programmers/난이도별/level02.위장/dkdlelk99.py ================================================ def solution(clothes): category = {} for i in clothes: category[i[1]] = category.get(i[1], 0) + 1 multiply_of_list = 1 for i in category.values(): multiply_of_list *= (i+1) return multiply_of_list-1 print(solution([["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]) == 5) print(solution([["crow_mask", "face"], ["blue_sunglasses", "face"], ["smoky_makeup", "face"]]) == 3) ================================================ FILE: programmers/난이도별/level02.위장/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/42578?language=javascript * 스파이들은 매일 다른 옷을 조합하여 입어 자신을 위장합니다. * @param clothes 스파이가 가진 의상들이 담긴 2차원 배열 * @return 서로 다른 옷의 조합의 수 clothes의 각 행은 [의상의 이름, 의상의 종류]로 이루어져 있습니다. 스파이가 가진 의상의 수는 1개 이상 30개 이하입니다. 같은 이름을 가진 의상은 존재하지 않습니다. clothes의 모든 원소는 문자열로 이루어져 있습니다. 모든 문자열의 길이는 1 이상 20 이하인 자연수이고 알파벳 소문자 또는 '_' 로만 이루어져 있습니다. 스파이는 하루에 최소 한 개의 의상은 입습니다. */ function solution(clothes) { // hash = { headgear: 2, eyewear: 1 }, 키 (의상의 분류), value: 의상의 개수 const hash = clothes.reduce((hash, [cloth, kind]) => { hash[kind] = (hash[kind] || 0) + 1; return hash; }, {}); // (2 + 1) * ( 1 + 1 ) = 4 : 1 을 더하는 이유는 의상의 분류에서 아무옷도 선택하지 않는 경우의 수도 추가 하였기 때문이다. // 4 - 1 : 1을 빼는 것은 위 경우의 수에서 모든 의상 분류에서 아무것도 입지 않았을 경우의 수도 count 하였기 때문임 return Object.values(hash) .reduce((ans, value) => ans *= (value + 1), 1) - 1; } console.log( solution([['blue_sunglasses', 'eyewear'], ['green_turban', 'headgear']]) === 3, solution([['crow_mask', 'face'], ['blue_sunglasses', 'face'], ['smoky_makeup', 'face']]) === 3, solution([['crow_mask', 'face'], ['blue_sunglasses', 'face']]) === 2, solution([['crow_mask', 'face']]) === 1, ); ================================================ FILE: programmers/난이도별/level02.위장/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42578 위장 : 해시 문제 dictionary에 의상 별 갯수를 저장해서 조합할 수 있는 경우의 수 계산 ''' def solution(clothes): otjang = {} #https://www.youtube.com/watch?v=Hfp77VwW950 for _, a in clothes: otjang.setdefault(a, 0) otjang[a] += 1 answer = 1 for i in otjang.values(): answer *= (i+1) return answer-1 ''' answer 라는 새로운 메모리 사용대신 reduce를 사용할 수 있다. dictionary값이 개수라면 counter 사용 import collections from functools import reduce def solution(c): return reduce(lambda x,y:x*y,[a+1 for a in collections.Counter([x[1] for x in c]).values()])-1 ''' ================================================ FILE: programmers/난이도별/level02.위장/sjjyy.java ================================================ import java.util.Arrays; import java.util.HashMap; import static java.util.stream.Collectors.*; public class sjjyy { /* * 의상의 종류와 이름이 담긴 2차원 배열이 주어질 때 서로 다른 옷 조합의 수를 리턴 String[][] clothes = {{의상의 이름, 의상의 종류} ... } * 원소 개수는 1개 이상 30개 이하이며 모두 1 이상 20 이하 길이의 문자열로 이루어져 있음 * 하루에 최소 한 개 이상의 옷을 입어야 함 */ public static int solution(String[][] clothes) { int answer = 1; // multiple HashMap hashMap = new HashMap<>(); for (int i = 0; i < clothes.length; i++) hashMap.put(clothes[i][1], hashMap.getOrDefault(clothes[i][1], 0) + 1); // 같은 종류의 의상이라면 + 1 for (int i : hashMap.values()) answer *= (i + 1); // 총 경우의 수 *= (의상 개수 + 입지 않을 경우) return answer - 1; // 전부 입지 않는 경우 제외 } public static int solution2(String[][] clothes) { return Arrays.stream(clothes) .collect(groupingBy(p -> p[1], mapping(p -> p[0], counting()))) .values() .stream() .collect(reducing(1L, (x, y) -> x * (y + 1))).intValue() - 1; } // 다른 사람 풀이 public static void main(String[] args) { String[][] clothes1 = {{"yellow_hat", "headgear"}, {"blue_sunglasses", "eyewear"}, {"green_turban", "headgear"}}; String[][] clothes2 = {{"crow_mask", "face"}, {"blue_sunglasses", "face"}, {"smoky_makeup", "face"}}; System.out.println(solution(clothes1)); // 5 System.out.println(solution(clothes2)); // 3 } } ================================================ FILE: programmers/난이도별/level02.이름에_el이_들어가는_동물_찾기/6047198844.sql ================================================ -- 코드를 입력하세요 SELECT ANIMAL_ID, NAME FROM ANIMAL_INS WHERE NAME LIKE '%EL%' AND ANIMAL_TYPE = 'Dog' ORDER BY 2 ================================================ FILE: programmers/난이도별/level02.이름이_없는_동물의_아이디/6047198844_.sql ================================================ SELECT ANIMAL_ID FROM ANIMAL_INS WHERE NAME IS NULL ORDER BY 1 ================================================ FILE: programmers/난이도별/level02.이진_변환_반복하기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/70129 ================================================ FILE: programmers/난이도별/level02.이진_변환_반복하기/dkdlelk99.py ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/70129 # input 0과 1로 이루어진 문자열 s # output 이진 변환의 횟수와 변환 과정에서 제거된 모든 0의 개수 # 여기서 x에 대한 이진 변환이란 아래와 같다 # 1. x의 모든 0을 제거합니다. # 2. x의 길이를 c라고 하면, x를 "c를 2진법으로 표현한 문자열"로 바꿉니다. def solution(s): cnt_change = 0 cnt_zero = 0 while s != '1': cnt_change += 1 cnt = 0 for i in s: if i =='0': cnt += 1 cnt_zero += cnt s = format((len(s)-cnt),'b') return [cnt_change,cnt_zero] print(solution('110010101001'), solution('110010101001') == [3,8]) print(solution('01110'), solution('01110') == [3,3]) print(solution('1111111'), solution('1111111') == [4,1]) ================================================ FILE: programmers/난이도별/level02.이진_변환_반복하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/70129 이진 변환 반복하기 0의 개수와 반복문 돈 횟수 카운트. ''' def solution(s): cnt = num = 0 while s != "1": zero = s.count('0') s = format(len(s)-zero,'b') num += zero cnt += 1 return [cnt, num] ''' ''' ================================================ FILE: programmers/난이도별/level02.저울/JeongShin.js ================================================ ================================================ FILE: programmers/난이도별/level02.전화번호_목록/6047198844.cpp ================================================ #include #include #include #include #include using namespace std; bool solution(vector phone_book) { bool answer = true; sort(phone_book.begin(), phone_book.end()); map mp; for (auto i : phone_book) { mp[i] = true; int i_size = i.size(); for (int j = 1; j < i_size; j++) { if (mp[i.substr(0, j)]) { answer = false; break; } } if (!answer) break; } return answer; } int main() { solution({ "97674223", "1195524421","119" }); } ================================================ FILE: programmers/난이도별/level02.전화번호_목록/HyeonJeong.py ================================================ def solution(phone_book): phone_book.sort(key = len) for i, n in enumerate(phone_book): for j in range(i + 1, len(phone_book)): if n == phone_book[j][0:len(phone_book[i])]: return False return True print( solution(['119', '97674223', '1195524421']) == False, solution(['123', '456', '789']) == True, solution(['12', '123', '1235', '567', '88']) ) ================================================ FILE: programmers/난이도별/level02.전화번호_목록/Jaewon0702.py ================================================ def solution(phone_book): phone_book.sort() for i in range(len(phone_book)) : for v in phone_book[i:] : if phone_book[i]!=v : return not phone_book[i] in v return True p=['119','97674223','119'] print(solution(p)) #채점 결과 : 100점 ================================================ FILE: programmers/난이도별/level02.전화번호_목록/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42577 ================================================ FILE: programmers/난이도별/level02.전화번호_목록/dkdlelk99.py ================================================ def solution(phone_book): length = len(phone_book) phone_book.sort() for i in range(length): for j in range(i+1, length): if phone_book[j].find(phone_book[i]) >= 0: return False return True print(solution( ["119", "97674223", "1195524421"]) == False) print(solution(['123','456','789']) == True) print(solution( ["12", "123", "1235", "567", "88"]) == False) ================================================ FILE: programmers/난이도별/level02.전화번호_목록/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/42577?language=python3 * * @param phone_book 전화번호부에 적힌 전화번호를 담은 배열 * @return 어떤 번호가 다른 번호의 접두어인 경우가 있으면 false를 그렇지 않으면 true를 return * 구조대 전화번호는 영석이의 전화번호의 접두사입니다. 구조대 : 119 박준영 : 97 674 223 지영석 : 11 9552 4421 phone_book의 길이는 1 이상 1,000,000 이하입니다. 각 전화번호의 길이는 1 이상 20 이하입니다. */ function solution(phone_book) { const len = phone_book.length + 1; // sort 를 먼저 하면 유사한 phone 과 더 먼저 비교를 할 수 있습니다. phone_book.sort(); // 접두사를 포함하는지 검사합니다. 접두사를 포함하면 반복문을 종료하고 true 를 리턴합니다. const hasPrefix = (phone, i) => { // phone 으로 시작하는 다른 phone 이 있는지 검사하는 정규식을 수행합니다. const regex = new RegExp(`^${phone}`); for (let j = i + 1 ; j < len ; j++) if (regex.test(phone_book[j])) return true; }; return !phone_book.some(hasPrefix); } function solution2(phone_book) { const len = phone_book.length + 1; const hasPrefix = (phone, i) => { const regex = new RegExp(`^${phone}`); for (let j = i + 1 ; j < len ; j++) if (regex.test(phone_book[j])) return true; }; return !phone_book.some(hasPrefix); } console.log(solution(['119', '97674223', '1195524421']) === false); console.log(solution(['123', '456', '789']) === true); console.log(solution(['12', '123', '1235', '567', '88']) === false); ================================================ FILE: programmers/난이도별/level02.전화번호_목록/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17682 전화번호 목록 : 접두사 찾기 re 정규식 사용 ''' import re def solution(phone_book): for i in phone_book: for j in phone_book: if i == j: continue if re.match(i, j) != None: return False return True ''' ''' ================================================ FILE: programmers/난이도별/level02.전화번호_목록/sjjyy.java ================================================ import java.util.Arrays; public class sjjyy { /* https://programmers.co.kr/learn/courses/30/lessons/42577 어떤 번호가 다른 번호의 접두어인지 확인 @param phone_book 전화번호를 담은 배열 @return 접두어인 경우 false, 그렇지 않으면 true */ public static boolean solution(String[] phone_book) { boolean answer = true; int len = phone_book.length; Arrays.sort(phone_book); // 좀 더 빠르게 for (int i = 0 ; i < len ; i++) { for (int j = 0 ; j < len ; j++) { if (i == j) continue; if (phone_book[j].indexOf(phone_book[i]) == 0) answer = false; } } return answer; } public static void main(String[] args) { String[] phone_book1 = {"119", "97674223", "1195524421"}; String[] phone_book2 = {"123", "456", "789"}; String[] phone_book3 = {"12", "123", "1235", "567", "88"}; System.out.println(solution(phone_book1)); // false System.out.println(solution(phone_book2)); // true System.out.println(solution(phone_book3)); // false } } ================================================ FILE: programmers/난이도별/level02.점프와_순간이동/6047198844.cpp ================================================ #include #include using namespace std; int brute_force(int n) { int res = 0; while (n) { if (n % 2) res++; n /= 2; } return res; } int solution(int n) { return brute_force(n); } ================================================ FILE: programmers/난이도별/level02.점프와_순간이동/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12980 점프와 순간이동 //2와 -1을 해서 0을 만듬. 이 때 -1할때 카운트 ''' def solution(n): cnt = 0 while n: if n % 2: cnt += 1 n = n-1 n = n // 2 return cnt ''' def solution(n): return bin(n).count('1') ''' ================================================ FILE: programmers/난이도별/level02.조이스틱/6047198844.cpp ================================================ #include #include #include using namespace std; int solution(string name) { int answer = 0; int name_size = name.size(); int left_cursor = name_size - 1; int right_cursor = 999999; if (name_size >= 2) { //커서를 왼쪽으로 이동하는 경우의 수 for (int i = 1; name[i] == 'A'&&i0; i--) { // --right_cursor; //} } int cursor_cnt = left_cursor > right_cursor ? right_cursor : left_cursor; int name_cnt = 0; int up_cursor; int down_cursor; for (auto i : name) { up_cursor = 'Z' - i + 1; down_cursor = i - 'A'; if (up_cursor > down_cursor) name_cnt += down_cursor; else name_cnt += up_cursor; } answer = name_cnt + cursor_cnt; return answer; } ================================================ FILE: programmers/난이도별/level02.조이스틱/HyeonJeong.py ================================================ def solution(name): answer = 0 locat = 0 list = [91 - ord(n) if ord(n) > 78 else ord(n) - 65 for n in name] while 1: answer += list[locat] list[locat] = 0 if sum(list) == 0: break left = 1 right = 1 while list[locat + right] == 0: right += 1 while list[locat - left] == 0: left += 1 if left >= right: locat += right answer += right else: locat -= left answer += left return answer print( solution("JEROEN") == 56, solution("JAN") == 23 ) ================================================ FILE: programmers/난이도별/level02.조이스틱/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42860?language=javascript function solution(name) { const now = [], last = [], rmd = [], len = name.length const zCode = 'Z'.charCodeAt() - 'A'.charCodeAt() Array.from(name).forEach((v, k) => { const code = v.charCodeAt() - 'A'.charCodeAt() now.push(0), last.push(code), rmd.push(!code) }) let min = Infinity const f = (n, p, now, rmd, tmp1 = last[p], tmp2 = zCode - tmp1 + 1) => { if ( n > min ) return if (tmp1 !== now[p]) { const tmp = tmp1 < tmp2 ? tmp1 : tmp2 now[p] = tmp1, rmd[p] = true, n += tmp } if (rmd.find(v => !v) === undefined && n < min) { min = n; return; } for (let i = 1, j = p + 1; i < len; i++, j++) { if (j >= len) j = 0 if (!rmd[j]) {f(n + i, j, [...now], [...rmd]); break;} } for (let i = 1, j = p - 1; i < len; i++, j--) { if (j < 0) j = len - 1 if (!rmd[j]) { f(n + i, j, [...now], [...rmd]); break; } } } f(0, 0, [...now], [...rmd]) return min; } //console.log(solution("JEROEN"), 56) //console.log(solution("JAN"), 23) console.log(solution("AAABAAA"), 0) ================================================ FILE: programmers/난이도별/level02.조이스틱/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/70128 조이스틱: 게임 기록 세웠을 때 자신의 이름을 등록하기 위해 레버를 움직여야 하는 횟수 진짜 어려웠던 문제. 구현하고 나니 쉬운 감이 있다. 풀이 방법 1) 각 자리에서 알파벳을 변경할 때의 횟수는 cnt에 한번에 생성 2) index 0에서 오른쪽과 왼쪽을 선택했을 때의 최소 횟수는 idx[-1], len(name) - idx[1] 3) idx 0에서 idx -1로만 이동이 가능한데, idx가 len(name) // 2 전에서 역행을 해야 최소 횟수 확보 가능 4) idx가 len(name) // 2 보다 작으면서 'A'가 아닐 때 idx 0 과의 거리 * 2 + 남은 거리를 통해 최종 비교 ''' def solution(name): cnt = [min(26 - ord(i) + 65, ord(i) - 65) for i in name if i != 'A'] idx = [i for i, v in enumerate(name) if v != 'A'] graph = [idx[i + 1] - idx[i] for i in range(len(idx) - 1)] + [len(name) - idx[-1]] if name[0] == 'A': idx = [0] + idx graph = [idx[1]] + graph answer = [2 * sum(graph[:i]) + (len(name) - idx[i + 1]) for i, v in enumerate(idx) if 0 < v < len(name) // 2] + [ idx[-1], len(name) - idx[1]] return sum(cnt) + min(answer) ''' 참고로 이 문제는 현재 잘못되었다. "BABAAAAB" 와 같은 예제에 대해서 결과 8을 출력해야 하는데 9를 출력한다. 이 문제의 채점 코드에서는 역행하는 경우의 수를 고려하지 않았다. 따라서 현재 인덱스에서 최단 거리만 방문해서 풀 수 있도록 설계해놓았다. 실제로는, 다익스트라 알고리즘이 적용되지 않는다. 따라서, 최단 거리만 방문해서는 문제를 풀 수 없다. 하지만 풀리는 이상한 문제... ''' ================================================ FILE: programmers/난이도별/level02.주식가격/Jaewon0702.py ================================================ def solution(prices): period = [] for i in range(len(prices)) : state=False for j in range(i+1,len(prices)) : if prices[i]>prices[j] : period.append(j-i) state=True break if state==False : period.append(len(prices)-i-1) return period print(solution([1,2,3,2,3])==[4,3,1,1,0]) #100점 ================================================ FILE: programmers/난이도별/level02.주식가격/README.md ================================================ https://programmers.co.kr/learn/courses/30/lessons/42584 ================================================ FILE: programmers/난이도별/level02.주식가격/dkdlelk99.py ================================================ def solution(prices): answer = [] len_prices = len(prices) for i in range(len_prices): up_price = 0 for j in range(i + 1, len_prices): up_price += 1 if prices[i] > prices[j]: answer.append(up_price) break if j == len_prices - 1: answer.append(up_price) if i == len_prices - 1: answer.append(0) return answer print(solution([1,2,3,2,3]), solution([1,2,3,2,3]) == [4,3,1,1,0]) print(solution([2,1,3,42,31,4,5,1,3,6,9,11,2]), solution([2,1,3,42,31,4,5,1,3,6,9,11,2])\ == [1, 11, 5, 1, 1, 2, 1, 5, 4, 3, 2, 1, 0]) #셀프 테스트 ================================================ FILE: programmers/난이도별/level02.주식가격/eyabc.js ================================================ /** * https://programmers.co.kr/learn/courses/30/lessons/42584 * @param prices 초 단위로 기록된 주식가격이 담긴 배열 * @return 가격이 떨어지지 않은 기간은 몇 초인지를 return prices의 각 가격은 1 이상 10,000 이하인 자연수입니다. prices의 길이는 2 이상 100,000 이하입니다. https://programmers.co.kr/questions/12172 예로 [1, 2, 3, 2, 3, 3, 1]의 결과값은 [6, 5, 1, 3, 2, 1, 0]이 나와야합니다. 1 : 2, 3, 2, 3, 3, 1 -> 6초간 떨어지지 않으니 결과값 6 2 : 3, 2, 3, 3, 1 -> 5초간 떨어지지 않으니 결과값 5 3 : 2 -> 1초 뒤에 떨어지니 기대값 1 (이부분에서 1초간 떨어지니 결과값을 3으로 생각했었습니다.) 2 : ~~ 결과값 3 3 : ~~ 결과값 2 3 : ~~ 결과값 1 1 : 결과값 0 */ function solution(prices) { const len = prices.length; return prices.map((price, i) => { for (let j = i + 1 ; j < len ; j++) if (prices[j] < price) return j - i; return len - 1 - i; }); } console.log(solution([1, 2, 3, 2, 3])); // [4, 3, 1, 1, 0] console.log(solution([1, 2, 3, 2, 3, 1])); // [ 5, 4, 1, 2, 1, 0 ] console.log(solution([3, 1])); // [ 1, 0 ] console.log(solution([1, 2, 3, 2, 3, 3, 1])); //[6, 5, 1, 3, 2, 1, 0] ================================================ FILE: programmers/난이도별/level02.주식가격/junilhwang.js ================================================ function s (prices) { const a = [] const stack = [prices.pop()] const plen = prices.length let i = 1 while (i <= plen) { const p = prices.pop() let j = 1, cnt = 0 while (j <= i && stack[i - j] >= p) cnt++, j++ if (j <= i && stack[i - j] < p) cnt += 1 stack.push(p) a[plen - i] = cnt i++ } a[plen] = 0 return a } console.log(s([100, 200, 300, 400, 500, 100, 200, 50])) ================================================ FILE: programmers/난이도별/level02.주식가격/rockmiin.py ================================================ def solution(prices): answer=[] for i in range(len(prices)): cnt=0 for j in range(i+1, len(prices)): cnt+=1 if prices[j] #include #include // prices_len은 배열 prices의 길이입니다. int* solution(int prices[], size_t prices_len) { // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요. int* answer = (int*)malloc(prices_len*sizeof(int)); int i,j; for(i=0;i stack[-1][0]: answer.append(1) stack.append((i,1)) continue cnt = 1 while stack and i <= stack[-1][0]: cnt += stack[-1][1] stack.pop() answer.append(cnt) stack.append((i, cnt)) return answer[::-1] ''' 테스트 케이스는 100,000개 인데 이중 반복문으로 구현해도 통과가 되는 이상한 문제 ''' ================================================ FILE: programmers/난이도별/level02.주식가격/sjjyy.java ================================================ import java.util.Arrays; /* @param prices[] : 초 단위로 기록된 주식 가격이 담긴 배열 각 가격은 1 이상 10,000 이하인 자연수, 배열의 길이는 2 이상 100,000 이하 @ return 가격이 떨어지지 않은 기간 (초) */ public class sjjyy { public static int[] solution(int[] prices) { int[] answer = new int[prices.length]; int count = 0, len = answer.length; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { count++; if (prices[i] > prices[j]) // 다음 가격이 더 크면 가격이 오른 것이므로 break break; } answer[i] = count; // 떨어지지 않은 초시간 저장 count = 0; } return answer; } public static void main(String[] args) { int[] prices = new int[]{1, 2, 3, 2, 3}; System.out.println(Arrays.toString(solution(prices))); // [4, 3, 1, 1, 0] } } ================================================ FILE: programmers/난이도별/level02.짝지어_제거하기/6047198844.cpp ================================================ #include #include using namespace std; int solution(string s) { stack st; for (char a_or_b : s) { if (st.empty()) { st.push(a_or_b); continue; } if (st.top() == a_or_b) { st.pop(); } else { st.push(a_or_b); } } return !st.size(); } ================================================ FILE: programmers/난이도별/level02.짝지어_제거하기/HyeonJeong.py ================================================ def solution(s): slist = [s[0]] for x in s[1:]: if slist != [] and x == slist[-1]: slist.pop() continue slist.append(x) return int(slist == []) print(solution("baabaa") == 1, solution("cdcd") == 0) ================================================ FILE: programmers/난이도별/level02.짝지어_제거하기/README.md ================================================ #출처 https://programmers.co.kr/learn/courses/30/lessons/12973 ================================================ FILE: programmers/난이도별/level02.짝지어_제거하기/eyabc.js ================================================ function solution(s) { const len = s.length; const stack = []; for (let i = 0 ; i < len ; i++) { const [thisValue, nextValue] = [s[i], s[i + 1]]; // 스택의 마지막 값과 현재 값이 같다면, 스택의 마지막값과 현재값이 사라집니다. if (stack[stack.length - 1] === thisValue) { stack.pop(); continue; } // 현재 값과 다음 값이 다르다면 ? 현재 값을 스택에다 넣습니다 : 같다면 현재값과 다음값을 스택에다 넣지않고, 다음값의 인덱스의 검사를 건너 뜁니다. (thisValue !== nextValue) ? stack.push(thisValue) : (i += 1); } // 스택이 비어 있다면 1을 반환하고 스택의 길이가 있다면 0 을 반환합니다. return !(stack.length > 0) * 1; } console.log(solution('baabaa') === 1); console.log(solution('cdcd') === 0); ================================================ FILE: programmers/난이도별/level02.짝지어_제거하기/rockmiin.py ================================================ from collections import deque def solution(s): arr= list(s) if len(arr)== 1: return 0 left_q, right_q= deque(), deque() left_q.append(s[0]) for i in range(1, len(arr)): right_q.append(arr[i]) while right_q: # print(left_q, right_q) if len(left_q)== 0: if len(right_q)> 1: left_q.append(right_q.popleft()) else: left_q.append(right_q.popleft()) break; if left_q[-1]== right_q[0]: left_q.pop(); right_q.popleft() else: left_q.append(right_q.popleft()) if len(left_q)== 0: return 1 return 0 solution('aaaab') ================================================ FILE: programmers/난이도별/level02.짝지어_제거하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12973 짝찌어 제거하기 stack을 이용 ''' def solution(s): stack = [s[0]] for i in s[1:]: if not stack or stack[-1] != i: stack.append(i) continue stack.pop() return 1 if not stack else 0 ''' 나보다 잘 푼 사람은 없는 듯 ''' ================================================ FILE: programmers/난이도별/level02.짝지어_제거하기/sjjyy.java ================================================ import java.util.Stack; public class sjjyy { /* https://programmers.co.kr/learn/courses/30/lessons/12973 @param s : 알파벳 소문자로 이루어진 문자열 문자열에서 같은 알파벳이 2개 붙어있는 짝을 찾아 제거한 뒤, 앞뒤로 문자열을 이어 붙임 해당 과정을 반복해서 문자열을 모두 제거하면 종료 @return 성공적으로 수행하면 1, 아닐 경우 0 */ public static int solution(String s) { Stack stack = new Stack<>(); for (char c : s.toCharArray()) { if (!stack.isEmpty() && stack.peek() == c) // 스택의 맨 위의 항목과 같다면 stack.pop(); // 제거 else stack.push(c); // 스택이 비어있거나 다른 문자열이면 삽입 } return stack.isEmpty() ? 1 : 0; // 스택이 비었으면 성공적으로 수행했다고 처리 } public static void main(String[] args) { System.out.println(solution("baabaa")); // 1 System.out.println(solution("cdcd")); // 0 } } ================================================ FILE: programmers/난이도별/level02.최댓값과 최솟값/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12939 ================================================ FILE: programmers/난이도별/level02.최댓값과 최솟값/dkdlelk99.py ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12939 # input s 공백으로 구분된 둘이상의 정수들 # output '(최소값) (최대값)' def solution(s): nums = list(map(int, s.split(" "))) return str(min(nums)) + " " + str(max(nums)) print(solution("1 2 3 4"), solution("1 2 3 4") == '1 4') print(solution("-1 -2 -3 -4"), solution("-1 -2 -3 -4") == '-4 -1') print(solution("-1 -1"), solution("-1 -1") == '-1 -1') ================================================ FILE: programmers/난이도별/level02.최댓값과_최솟값/6047198844.cpp ================================================ #include #include #include #include using namespace std; string solution(string s) { char* s_p = new char[s.size()]; vector vt; strcpy(s_p, s.c_str()); char* ptr = strtok(s_p, " "); while (ptr != NULL) { vt.push_back(stoi(ptr)); ptr = strtok(NULL, " "); } string answer = " "; int min = *min_element(vt.begin(),vt.end()); int max = *max_element(vt.begin(), vt.end()); return to_string(min)+answer+to_string(max); } ================================================ FILE: programmers/난이도별/level02.최댓값과_최솟값/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12939 문제 : 최댓값과 최솟값 ''' def solution(s): s = list(map(int,s.split())) return str(min(s)) + ' ' + str(max(s)) ================================================ FILE: programmers/난이도별/level02.최댓값과_최솟값/HyeonJeong.py ================================================ def solution(s): splitted_list = sorted(map(int, s.split())) return f'{splitted_list[0]} {splitted_list[-1]}' print( solution("1 2 3 4") == "1 4", solution("-1 -2 -3 -4") == "-4 -1", solution("-1 -1") == "-1 -1" ) ================================================ FILE: programmers/난이도별/level02.최댓값과_최솟값/rockmiin_최댓값과최솟값.py ================================================ def solution(s): s=list(map(int, s.split())) answer=map(str, [min(s), max(s)]) return ' '.join(answer) solution("1 2 3 4") ================================================ FILE: programmers/난이도별/level02.최댓값과_최솟값/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12939 최대값과 최솟값 ''' def solution(s): numbers = list(map(int, s.split(' '))) return f"{min(numbers)} {max(numbers)}" ''' ''' ================================================ FILE: programmers/난이도별/level02.최댓값과_최솟값/sjjyy.java ================================================ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class sjjyy { /* https://programmers.co.kr/learn/courses/30/lessons/12939 @param s : 공백으로 구분된 숫자 문자열, 둘 이상의 정수가 공백으로 구분되어 있음 숫자 중 최소값, 최대값을 찾기 @return "최소값 최대값" 형태로 반환 */ public static String solution(String s) { String [] str = s.split(" "); // 숫자 문자열 배열로 저장 int len = str.length; int [] numbers = new int[len]; for (int i = 0 ; i < len ; i++) numbers[i] = Integer.parseInt(str[i]); // Integer 타입으로 변환 Arrays.sort(numbers); // 오름차순 정렬 return numbers[0] + " " + numbers[len - 1]; // 최소값 최대값 형태로 반환 } public static String solution2(String s) { List numbers = Arrays.stream(s.split(" ")) .map(Integer::parseInt) .sorted((a, b) -> a - b) .collect(Collectors.toList()); return String.format("%d %d", numbers.get(0), numbers.get(numbers.size() -1)); } public static void main(String [] args) { System.out.println(solution("1 2 3 4")); // 1 4 System.out.println(solution("-1 -2 -3 -4")); // -4 -1 System.out.println(solution("-1 -1")); // -1 -1 System.out.println(solution2("1 2 3 4")); // 1 4 System.out.println(solution2("-1 -2 -3 -4")); // -4 -1 System.out.println(solution2("-1 -1")); // -1 -1 } } ================================================ FILE: programmers/난이도별/level02.최솟값_만들기/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12941 문제 : 최솟값 만들기 곱의 최솟값을 구하려면 제일 작은수와 제일 큰 수의 곱의 합으로 이루어져야 합니다. 그래서 하나는 오름차순, 하나는 내림차순으로 정렬하여 곱해주었습니다. 다른 사람들 풀이를 보니 zip을 사용하면 한줄로 간편하게 할 수 있더라구요 zip 진짜 편리하네요 [메모] sum(a*b for a,b in zip(sorted(A), sorted(B,reverse=True))) ''' def solution(A,B): answer = 0 A = sorted(A) B = sorted(B, reverse=True) for i in range(len(A)) : answer += A[i]*B[i] return answer ================================================ FILE: programmers/난이도별/level02.최솟값_만들기/HyeonJeong.py ================================================ def solution(A,B): # A와 B 배열에서 한 개씩 뽑아 두 수를 곱한 합이 최소가 되는 값을 구하는 문제 # A를 오름차순, B를 내림차순으로 정리하고 같은 인덱스끼리 곱한 합을 반환하게 구성함 A.sort() B.sort(reverse = True) answer = 0 for i in range(len(A)): answer += A[i] * B[i] return answer ================================================ FILE: programmers/난이도별/level02.최솟값_만들기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12941 ================================================ FILE: programmers/난이도별/level02.최솟값_만들기/dkdlelk99.py ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12941 # input A, B 길이가 같은 자연수 배열 (배열 크기, 원소 크기는 둘 다 1,000 이하) # output A, B에서 각 원소를 곱한 값의 합이 최소가 되는 값 # 예를 들어 A = [1, 4, 2] , B = [5, 4, 4] 라면 # A에서 첫번째 숫자인 1, B에서 두번째 숫자인 5를 뽑아 곱하여 더합니다. (누적된 값 : 0 + 5(1x5) = 5) # A에서 두번째 숫자인 4, B에서 세번째 숫자인 4를 뽑아 곱하여 더합니다. (누적된 값 : 5 + 16(4x4) = 21) # A에서 세번째 숫자인 2, B에서 첫번째 숫자인 4를 뽑아 곱하여 더합니다. (누적된 값 : 21 + 8(2x4) = 29) # 즉, 이 경우가 최소가 되므로 29를 return 합니다. def solution(A,B): answer = 0 A.sort(), B.sort(reverse=True) for a, b in zip(A, B): answer += a*b return answer print(solution([1,4,2], [5,4,4]) == 29, solution([1,4,2], [5,4,4])) print(solution([1,2], [3,4]) == 10, solution([1,2], [3,4])) ================================================ FILE: programmers/난이도별/level02.최솟값_만들기/rockmiin.py ================================================ def solution(A, B): answer = 0 A = sorted(A) B = sorted(B, reverse=True) for i in range(len(A)): answer += A[i] * B[i] return answer print( solution([1, 4, 2], [5, 4, 4]) ) ================================================ FILE: programmers/난이도별/level02.최솟값_만들기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12941 최솟값 만들기 각 리스트를 오름차순, 내림차순으로 곱셈 ''' def solution(A,B): return sum([a * b for a, b in zip(sorted(A), sorted(B)[::-1])]) ''' ''' ================================================ FILE: programmers/난이도별/level02.최솟값_만들기/sjjyy.java ================================================ import java.util.Arrays; public class sjjyy { /* https://programmers.co.kr/learn/courses/30/lessons/12941 @param A, B : 길이가 같은 자연수 배열 배열 A, B에서 각각 한 개의 숫자를 뽑아 두 수를 곱함. 배열의 길이만큼 반복. 두 수를 곱한 값을 누적하여 더함. @return 누적된 값의 최솟값 */ public static int solution(int[] A, int[] B) { int answer = 0; Arrays.sort(A); Arrays.sort(B); // 배열 정렬 // int j = B.length - 1; // for (int i : A) { // answer += i * B[j]; // j--; // } int len = A.length; for (int i = 0 ; i < len ; i++) { answer += A[i] * B[len - 1 - i]; } // 누적된 값의 최솟값은 한 배열의 최댓값 * 최솟값을 누적한 값이 최솟값이 됨 return answer; } public static void main(String[] args) { int[] A1 = {1, 4, 2}; int[] B1 = {5, 4, 4}; int[] A2 = {1, 2}; int[] B2 = {3, 4}; System.out.println(solution(A1, B1)); // 29 System.out.println(solution(A2, B2)); // 10 } } ================================================ FILE: programmers/난이도별/level02.최솟값만들기/6047198844.cpp ================================================ #include #include #include using namespace std; int solution(vector A, vector B) { int answer = 0; sort(A.begin(),A.end()); sort(B.begin(),B.end()); int vt_size = A.size(); for(int i =0; i #include #include #include using namespace std; vector solution(int brown, int yellow) { vector answer; int n = sqrt(yellow); for(int y_height=1;y_height<=n;y_height++){ if(!(yellow%y_height)){ int y_width = yellow/y_height; if(brown==(y_height*2+y_width*2+1*4)){ if(y_width= 세로 * 완전탐색이면 모든 가로 세로의 길이 가능성을 고려하여 풀어야 한다. */ const initSize = (width, height) => ({ width, height }); function solution(brown, yellow) { const Y = initSize(yellow / 1, 1); while (Y.width >= Y.height) { Y.width = yellow / Y.height; const computedYellowCount = Y.width * Y.height; if (Number.isInteger(Y.width) && (computedYellowCount === yellow)) { const [width, height] = [Y.width + 2, Y.height + 2]; if ((width * height - computedYellowCount) === brown) return [width, height]; } Y.height += 1; } } console.log(solution(10, 2)); // [4, 3] console.log(solution(8, 1)); // [3, 3] console.log(solution(24, 24)); // [8, 6] ================================================ FILE: programmers/난이도별/level02.카펫/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42842 function solution (b, r) { let s = b+r, n = ~~Math.sqrt(s), w = n, h = n const f = (w, h, bChk = w * 2 + h * 2 - 4, rChk = w * h - bChk) => bChk === b && rChk === r while (w >= h && !f(w, h)) w*h < s ? w++ : h-- return [w, h] } //console.log(solution(10,2), [4, 3]) //console.log(solution(8,1), [3, 3]) //console.log(solution(24,24), [8, 6]) const arr = [ [6, 4], [5, 5], [4, 4], [361, 360] ] arr.forEach(([w, h]) => { const b = w * 2 + h * 2 - 4 const r = w * h - b console.log(solution(b, r), [w, h]) }) ================================================ FILE: programmers/난이도별/level02.카펫/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42842 카펫 ''' def solution(brown, yellow): for i in range(1, int(yellow**0.5)+1): if yellow % i == 0 and i + (yellow // i) == (brown - 4) // 2: return [yellow // i+2, i+2] ''' ''' ================================================ FILE: programmers/난이도별/level02.카펫/sjjyy.java ================================================ import java.util.Arrays; public class sjjyy { /* @param brown, yellow : 테두리는 갈색, 중앙은 노란색으로 칠해져있는 카펫 갈색 격자의 수는 8이상 5,000 이하 자연수, 노란색 격자의 수는 1 이상 2,000,000 이하의 자연수 카펫의 가로 길이는 세로 길이와 같거나, 세로 길이보다 김. @return 카펫의 가로 세로 크기 배열 */ public static int[] solution(int brown, int yellow) { int width = 0, height = 0; for (int i = 1 ; i <= yellow / 2 + 1 ; i++) { // 노란색을 기준으로 탐색, 카펫이 직사각형이므로 yellow/2+1까지 탐색. width = i ; height = (yellow % i == 0) ? yellow / i : yellow / i + 1; if (2 * width + 2 *height + 4 == brown) // 테두리의 갈색은 노란색의 가로*2, 세로*2 + 모서리 4개의 개수와 같음 break; } return new int[]{Math.max(width, height) + 2, Math.min(width, height) + 2}; // 가로가 세로보다 길거나 같음 } public static void main(String [] args) { System.out.println(Arrays.toString(solution(10, 2))); // [4, 3] System.out.println(Arrays.toString(solution(8, 1))); // [3, 3] System.out.println(Arrays.toString(solution(24, 24))); // [8, 6] } } ================================================ FILE: programmers/난이도별/level02.캐시/6047198844.cpp ================================================ #include #include #include #include using namespace std; int solution(int cacheSize, vector cities) { if (!cacheSize) return cities.size()*5; int cities_size = cities.size(); for (int i = 0; i < cities_size; i++) { int city_size = cities[i].size(); for (int j = 0; j < city_size; j++) { if(cities[i][j]>='A'&& cities[i][j]<='Z') cities[i][j] = cities[i][j] - 'A' + 'a'; } } unordered_map ::iterator> cache_map; list cache; //가장 나중에 참조된것 --> 삭제한다. //cache에 있는것이 참조됨 --> 갱신한다. //cache의 맨앞에 있는것 --> 가장 최근에 참조된것 / cache의 맨뒤에 있는것 --> 가장 나중에 참조된것 int time = 0; for (string city : cities) { //못찾았을경우 if (cache_map.find(city) == cache_map.end()) { if (cache.size() == cacheSize) { string last = cache.back(); cache_map.erase(last); cache.pop_back(); } time += 5; } //찾았을경우 else { cache.erase(cache_map[city]); time += 1; } cache.push_front(city); cache_map[city] = cache.begin(); } return time; } ================================================ FILE: programmers/난이도별/level02.캐시/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17680 캐시 CS지식이 적용된 문제라 순간 놀랐다. Cache를 모르는 사람은 풀기 어려웠을 듯... ''' def solution(cacheSize, cities): if not cacheSize: return len(cities) * 5 cache = [] time = 0 for i in cities: i = i.lower() if i in cache: time += 1 cache.remove(i) cache.append(i) continue time += 5 if len(cache) == cacheSize: cache.pop(0) cache.append(i) return time ''' deque 에는 다음과 같은 maxlen 속성이 있다. 이 이상 append 되면 이전에 있던 data가 자동 pop collections.deque(maxlen=cacheSize) ''' ================================================ FILE: programmers/난이도별/level02.쿼드압축_후_개수_세기/6047198844.cpp ================================================ #include #include using namespace std; int zero_one[2] = { 0,0 }; void divide_and_conquer(vector> &arr,int y, int x, int size) { if (size == 1) { zero_one[arr[y][x]]++; return; } bool check = true; for (int i = y; i < y + size; i++) { if (!check) break; for (int j = x; j < x + size; j++) { if (arr[y][x] != arr[i][j]) { check = false; break; } } } if (check) { zero_one[arr[y][x]]++; } else { divide_and_conquer(arr,y, x, size / 2); divide_and_conquer(arr,y + size / 2, x, size / 2); divide_and_conquer(arr,y, x + size / 2, size / 2); divide_and_conquer(arr,y + size / 2, x + size / 2, size / 2); } return; } vector solution(vector> arr) { divide_and_conquer(arr,0, 0, arr[0].size()); vector answer{ zero_one[0],zero_one[1] }; return answer; } ================================================ FILE: programmers/난이도별/level02.쿼드압축_후_개수_세기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/68936 쿼드압축 후 개수 세기 특정 영역에 대해 자신과 자신의 위쪽과 자신의 왼쪽 그리고 자신의 왼쪽 위가 동일하다면 쿼드압축을 할 수 있다. 이 때 쿼드압축이 가능하다면 자신을 제외한 좌상 주변을 -1로 설정. 자신은 문자열 타입으로 변환한다. 8x8를 기준으로 설명하면, 영역 2x2 검사 ( 1 1 ) ( 1 3 ) ( 1 5 ) ( 1 7 ) ( 3 1 ) ( 3 3 ) ( 3 5 ) ( 3 7 ) ( 5 1 ) ( 5 3 ) ( 5 5 ) ( 5 7 ) ( 7 1 ) ( 7 3 ) ( 7 5 ) ( 7 7 ) 영역 4x4 검사 ( 3 3 ) ( 3 7 ) ( 7 3 ) ( 7 7 ) 영역 8x8 검사 ( 7 7 ) 다음과 같은 인덱스를 검사해야 한다. 4x4를 기준으로 예를 들면, 1 1 0 0 1 1 -1 -1 1 0 0 0 1 0 -1 '0' 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 (전) (후) 이 후 압축이 불가능 하면 0과 '0'의 개수, 1과 '1'의 개수를 반환한다. ''' import math def solution(arr): size = len(arr) n = int(math.log2(size)) for m in range(1, n+1): for i in range(2**m-1, size, 2**m): for j in range(2**m-1, size, 2**m): if arr[i-2**(m-1)][j-2**(m-1)] == arr[i-2**(m-1)][j] == arr[i][j-2**(m-1)] == arr[i][j]: arr[i-2**(m-1)][j-2**(m-1)] = arr[i-2**(m-1)][j] = arr[i][j-2**(m-1)] = -1 arr[i][j] = str(arr[i][j]) * m else: arr[i][j] = str(arr[i][j])+str(i)+str(j) arr = [[(j if type(j) == int else j[0]) for j in i] for i in arr] return [sum([i.count(0) + i.count('0') for i in arr]), sum(i.count(1) + i.count('1') for i in arr)] ''' 작은 문제를 모아서 큰 문제를 해결하는 것보다 그 반대가 좀 더 간단했던 것 같다. 다음은 array를 1/4하여 4개의 재귀함수 꼴로 해결한 풀이 import numpy as np def solution(arr): # 재귀함수 구현 def fn(a): if np.all(a == 0): return np.array([1, 0]) if np.all(a == 1): return np.array([0, 1]) n = a.shape[0]//2 return fn(a[:n, :n]) + fn(a[n:, :n]) + fn(a[:n, n:]) + fn(a[n:, n:]) # 결과 리턴 return fn(np.array(arr)).tolist() ''' ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/6047198844.cpp ================================================ //#include //#include //#include //#include //using namespace std; // //int res_max = 0; // //void brute_force(string number, string res, int idx, int cnt, int k) { // if (cnt == k) { // int temp = stoi(res); // if (temp > res_max) // res_max = temp; // return; // } // if (number.size() <= idx) // return; // // // brute_force(number, res + number[idx], idx + 1, cnt + 1, k); // ʾ // brute_force(number, res, idx + 1, cnt, k); // return; //} // //string solution(string number, int k) { // string answer = ""; // brute_force(number, "", 0, 0, number.size() - k); // answer = to_string(res_max); // return answer; //} #include #include using namespace std; string solution(string number, int k) { string answer = ""; int start_idx = 0; int end_idx = k; int number_size = number.size(); for (int end_idx = k; end_idx < number_size; end_idx++) { char temp = '0'; int temp_start_idx; for (int i = start_idx; i <= end_idx; i++) { if (number[i] > temp) { temp = number[i]; temp_start_idx = i; } } start_idx = temp_start_idx + 1; answer += temp; } return answer; } ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/Jaewon0702(1).py ================================================ def solution(number, k): i = 0 while i < len(number) - 1 and k > 0: if number[i] < number[i + 1]: number = number[:i] + number[i + 1 :] if i != 0: i -= 1 k -= 1 else: i += 1 if k > 0: return number[:-k] return number print(solution("1924", 2) == "94") print(solution("1231234", 3) == "3234") print(solution("4177252841", 4) == "775841") print(solution("100000", 2) == "1000") ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/Jaewon0702.py ================================================ def solution(number, k): stack = [] for num in number: while len(stack) > 0 and stack[-1] < num and k > 0: k -= 1 stack.pop() stack.append(num) if k != 0: stack = stack[:-k] return "".join(stack) # 100점 # https://train-validation-test.tistory.com/entry를 참고하였음. print(solution("1924", 2) == "94") print(solution("1231234", 3) == "3234") print(solution("4177252841", 4) == "775841") print(solution("100000", 2) == "1000") ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/JeongShin.js ================================================ function solution(number, k) { const stack = [] const len = number.length let top = 0 let deleteCount = 0 for (let i = 0; i < len; i++) { const curr = number[i] if (top === 0) { stack.push(curr) top++ continue } while (top > 0 && stack[top - 1] < curr) { stack.pop() deleteCount++ top--; if (top === 0) break if (deleteCount === k) return stack.join('') + number.slice(i, len) } stack.push(curr) top++ } return stack.join('').slice(0, len - k) } console.log(solution("4177252841", 4)) ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42883 ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/dkdlelk99.py ================================================ def solution(number, k): i = 0 while k > 0: if number[i] < number[i + 1]: number = number[:i] + number[i + 1:] k -= 1 if i ! = 0: i -= 1 else: i += 1 if i == len(number)-1: return number[:-k] return number print(solution("1924", 2), solution("1924", 2) == "94") print(solution("1231234", 3), solution("1231234", 3) == "3234") print(solution("4177252841", 4), solution("4177252841", 4) == "775841") print(solution("100000", 2) ,solution("100000", 2) == "1000") ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/junilhwang-01.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42883?language=javascript function solution (nums, k) { const arr = Array.from(nums) const last = nums.length, len = last - k let left = 0, idx = 0, num = "" for (let i = 0; i < len; i++) { let max = nums[left] while (left <= k + i) { const n = nums[left] if (max < n) max = n, idx = left let nextLeft = -1, nextMax = 9 while (nextMax > ~~max && nextLeft === -1) nextLeft = nums.indexOf(nextMax--, left+1) if (nextLeft === -1) break left = nextLeft < k + 1 ? nextLeft : left + 1 } num += max, left = ++idx } return num } console.log(solution("1924", 2), "94") console.log(solution("1231234", 3), "3234") console.log(solution("4177252841", 4), "775841") ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/junilhwang-02.js ================================================ function solution(number, k) { const stack = [number[0]], last = number.length, len = last - k let i = 1, j = 0, n = k do { if (n && stack[j] < number[i]) { stack.pop(), j--, n-- continue } stack.push(number[i++]), j++ } while (j < len || i < last) return stack.slice(0, len).join('') } //console.log(solution("1924", 2), "94") //console.log(solution("1231234", 3), "3234") //console.log(solution("4177252841", 4), "775841") console.log(solution("12345654654321", 10), "6654") ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42883 큰 수 만들기 : 순서를 지키면서 큰 수 만들기 수의 처음부터 비교해서 작은 수가 되면 k 횟수 안에서 pop ''' def solution(number, k): stack = [number[0]] for i in number[1:]: while k > 0 and stack and stack[-1] < i: stack.pop() k -= 1 stack.append(i) if k != 0: stack = stack[:-k] return ''.join(stack) ''' 10번 시간초과 때문에 도저히 못풀어서 다른 코드 참조. 위 코드가 내 코드보다 훨씬 잘 풀었음. ''' ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/sjjyy.java ================================================ import java.util.Stack; public class sjjyy { /* https://programmers.co.kr/learn/courses/30/lessons/42883 @param number : 1자리 이상, 1,000,000자리 이하의 숫자 문자열 number에서 k개의 수를 제거했을 떄 얻을 수 있는 가장 큰 숫자 구하기 @return 가장 큰 숫자 문자열 */ public static String solution(String number, int k) { // String answer = ""; StringBuilder stringBuilder = new StringBuilder(); int index = 0; char max; if (number.charAt(0) == '0') // 예외처리 return "0"; for (int i = 0 ; i < number.length() - k ; i++) { // 반복문 수행 max = '0'; for (int j = index ; j <= k + i ; j++) { // 현재 위치부터 뽑음 if (max < number.charAt(j)) { max = number.charAt(j); // 각 자리 숫자를 뽑을 때마다 최대값 선택 index = j + 1; } } // answer += max; stringBuilder.append(max); } // return answer; return stringBuilder.toString(); // 시간 초과 처리 } public static String solution2(String number, int k) { int len = number.length(); char[] result = new char[len - k]; Stack stack = new Stack<>(); for (int i = 0; i < len ; i++) { char c = number.charAt(i); while (!stack.isEmpty() && stack.peek() < c && k-- > 0) stack.pop(); stack.push(c); } for (int i = 0 ; i < result.length ; i++) { result[i] = stack.get(i); } return new String(result); } public static void main(String[] args) { System.out.println(solution("1924", 2)); // 94 System.out.println(solution("1231234", 3)); // 3234 System.out.println(solution("4177252841", 4)); // 775841 System.out.println(solution2("1924", 2)); // 94 System.out.println(solution2("1231234", 3)); // 3234 System.out.println(solution2("4177252841", 4)); // 775841 } } ================================================ FILE: programmers/난이도별/level02.큰_수_만들기/turquoiseluv.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42883 매번 비교하려니까 런타임 오류가 발생했고, while k > 0 and len(ans) < len(number)-k: if number[target] == max(number[target:target+k+1]): ans += number[target] 기존의 배열의 순서가 바뀌지 않는 점을 이용하여, que에 들어오는 숫자들만 보며, 최적인지 판단할 수 있었다. 1) que를 만들고, number에서 하나씩 값(num)을 넘긴다. append(pop()) 2) 이떄, 넘기는 값이 que의 맨 마지막 값(que[-1])보다 작으면, 더 큰 값이 나올 때까지 que[-1]을 버리고 반복 2-1) que = ['9']는 한자리 수로 더 큰 값을 가질 수 없기 때문에, que.pop()의 방지턱이 된다. 3) 해당 과정에서 버릴 때마다 제거해야 하는 개수 k값에서 1씩 감소 4) while문이 완료 후, 남은 number 배열을 que애 더해준다. 5) k가 남은 경우(number==null로 탈출), 이미 정렬이 완료된 que에서 남은 k만큼 뒤에서 제거해준다. ''' number = '4177252841' k = 4 def solution(number, k): number = list(number[::-1]) que = ['9'] while number and k > 0: num = number.pop() while que[-1] < num and k > 0: que.pop() k -= 1 que.append(num) que += number[::-1] if k != 0: que = que[:-k] return ''.join(que[1:]) print(solution(number, k)) ================================================ FILE: programmers/난이도별/level02.타겟 넘버/rockmiin.py ================================================ from collections import deque def solution(numbers, target): res= 0 q= deque([[numbers[0], 0], [-numbers[0], 0]]) while q: x, cnt= q.popleft() if cnt==len(numbers)-1 and x==target: res+=1 if cnt < len(numbers) - 1: for dx in [-numbers[cnt+1], numbers[cnt+1]]: q.append([x+ dx, cnt+1]) # print([x+dx, cnt+1]) return res # numbers=[1, 1, 1, 1, 1] # target= 3 # print(solution(numbers, target)) ================================================ FILE: programmers/난이도별/level02.타겟_넘버/6047198844.cpp ================================================ #include #include #include using namespace std; int brute_force(vector numbers, int target,int sum,int idx) { if (idx == numbers.size()) { if (sum == target) return 1; return 0; } int plus = brute_force(numbers, target, sum + (1 * numbers[idx]), idx + 1); int minus = brute_force(numbers, target, sum + (-1 * numbers[idx]), idx + 1); return plus + minus; } int solution(vector numbers, int target) { int answer = brute_force(numbers, target, 0, 0); return answer; } ================================================ FILE: programmers/난이도별/level02.타겟_넘버/JeongShin.js ================================================ function solution(numbers, target) { const len = numbers.length; let answer = 0; const dfs = (sum, idx) => { if (idx === len) { answer += (sum === target) return; } dfs(sum + numbers[idx], idx + 1) dfs(sum - numbers[idx], idx + 1) }; dfs(0, 0); return answer } function solution2(numbers, target) { const len = numbers.length; let graph = [0]; let lvl = 0; while (lvl < len) { const temp = []; graph.forEach((el) => { temp.push(el - numbers[lvl]); temp.push(el + numbers[lvl]); }); graph = temp; lvl++ } return graph.reduce((acc, curr) => acc + (curr === target), 0) } solution2([1, 1, 1, 1, 1], 3) ================================================ FILE: programmers/난이도별/level02.타겟_넘버/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/43165 ================================================ FILE: programmers/난이도별/level02.타겟_넘버/dkdlelk99.py ================================================ def solution(numbers, target): result = [0] for num in numbers: temp = [] for i in result: temp.append(i + num) temp.append(i - num) result = temp return result.count(target) numbers = [1,1,1,1,1] target = 3 print(solution(numbers, target), solution(numbers, target) == 5) ================================================ FILE: programmers/난이도별/level02.타겟_넘버/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12905 타켓넘버 숫자의 개수가 20개 이고, 모든 숫자는 양 또는 음의 수를 가지므로 최대 2의 20승, 대략 백만정도의 크기. 따라서 각각의 경우의 수를 모두 구하고 모든 경우의 수가 target과 매칭되는 경우를 카운트 ''' import numpy def pm(numbers, target): if not numbers: return target num = numbers.pop() return [pm(numbers[:], target-num), pm(numbers[:], target+num)] def solution(numbers, target): return numpy.array(pm(numbers, target)).flatten().tolist().count(0) ''' 좀 더 효과적인 재귀 def solution(numbers, target): if not numbers and target == 0 : return 1 elif not numbers: return 0 else: return solution(numbers[1:], target-numbers[0]) + solution(numbers[1:], target+numbers[0]) 고인물 시리즈 product를 저렇게 이용하다니 대단하다. from itertools import product def solution(numbers, target): l = [(x, -x) for x in numbers] s = list(map(sum, product(*l))) return s.count(target) ''' ================================================ FILE: programmers/난이도별/level02.타겟_넘버/sjjyy.java ================================================ public class sjjyy { /* https://programmers.co.kr/learn/courses/30/lessons/43165 @param numbers : n개의 음이 아닌 정수 이 수를 적절히 더하거나 빼서 타겟넘버 target을 만듦 @return 타겟넘버를 만드는 경우의 수 */ public static int solution(int[] numbers, int target) { return DFS(numbers, target, 0, 0); } private static int DFS(int[] numbers, int target, int index, int num) { // 깊이 우선 탐색으로 모든 경우의 수를 구함 if (index == numbers.length) return num == target ? 1 : 0; // 타겟넘버와 같으면 + 1 return DFS(numbers, target, index + 1, num + numbers[index]) // 왼쪽 노드 + DFS(numbers, target, index + 1, num - numbers[index]); // 오른쪽 노드 } public static void main(String[] args) { int[] numbers = {1, 1, 1, 1, 1}; System.out.println(solution(numbers, 3)); // 5 } } ================================================ FILE: programmers/난이도별/level02.탑/Jaewon0702.py ================================================ def solution(heights) : reception=[0] for i in range(1,len(heights)) : for j,v in enumerate(heights[i-1::-1]) : if heights[i] heights[i]: check = True answer.append(j+1) break if not check: answer.append(0) answer.reverse() return answer print(solution([6,9,5,7,4]) == [0, 0, 2, 2, 4]) print(solution([3, 9, 9, 3, 5, 7, 2]) == [0, 0, 0, 3, 3, 3, 6]) print(solution([1, 5, 3, 6, 7, 6, 5]) == [0, 0, 2, 0, 0, 5, 6]) ================================================ FILE: programmers/난이도별/level02.탑/junilhwang.js ================================================ /* 일반적인 프린터는 인쇄 요청이 들어온 순서대로 인쇄합니다. 그렇기 때문에 중요한 문서가 나중에 인쇄될 수 있습니다. 이런 문제를 보완하기 위해 중요도가 높은 문서를 먼저 인쇄하는 프린터를 개발했습니다. 이 새롭게 개발한 프린터는 아래와 같은 방식으로 인쇄 작업을 수행합니다. 1. 인쇄 대기목록의 가장 앞에 있는 문서(J)를 대기목록에서 꺼냅니다. 2. 나머지 인쇄 대기목록에서 J보다 중요도가 높은 문서가 한 개라도 존재하면 J를 대기목록의 가장 마지막에 넣습니다. 3. 그렇지 않으면 J를 인쇄합니다. */ function solution(priorities, location) { const queue = priorities.map((v, k) => ({v, k})) let i = 1; while (queue.length) { const target = queue.shift() const chk = queue.find(q => q.v > target.v) if (chk) { queue.push(target) } else { if (~~location === ~~target.k) return i i++ } } return 0; } console.log(solution([2, 1, 3, 2],2)) console.log(solution([1, 1, 9, 1, 1, 1],0)) ================================================ FILE: programmers/난이도별/level02.탑/rockmiin.py ================================================ def solution(heights): slen=len(heights) answer=[0 for _ in range(slen)] for i in range(slen-1, 0, -1): for j in range(i-1, -1, -1): if heights[i] < heights[j] : answer[i]=j+1; break; return answer print( solution([6, 9, 5, 7, 4]), solution([6, 9, 5, 7, 4])==[0, 0, 2, 2, 4] ) ================================================ FILE: programmers/난이도별/level02.튜플/6047198844.cpp ================================================ #include #include #include #include #include using namespace std; bool comp(vector a, vector b) { return a.size() < b.size(); } vector solution(string s) { vector> vt; int s_start_idx = 0; int s_end_idx = s.size() - 1; int idx = s_start_idx; while(idx < s_end_idx) { idx++; vector vt_element; // }이 나올때까지 원소로 넣는 do while문 do { idx++; int e = 0; while (s[idx] != ',' && s[idx] != '}') e = (e * 10) + (s[idx++] - '0'); vt_element.push_back(e); } while (s[idx] != '}'); idx++; vt.push_back(vt_element); } sort(vt.begin(), vt.end(), comp); vector answer; map mp; int vt_size = vt.size(); for (int i = 0; i < vt_size; i++) { for (int j = 0; j <= i; j++) { if (!mp[vt[i][j]]) { mp[vt[i][j]] = true; answer.push_back(vt[i][j]); } } } return answer; } ================================================ FILE: programmers/난이도별/level02.튜플/JeongShin.js ================================================ function solution(s) { const map = s.replace(/([{}.,])/g, " ") .match(/\S+/g) .reduce((map, curr) => { curr *= 1; map.set(curr, (map.get(curr) || 0) + 1); return map }, new Map()); return [...map] .sort((a, b) => b[1] - a[1]) .map(v => v[0]); } ================================================ FILE: programmers/난이도별/level02.튜플/eyabc.js ================================================ const parseToArr = (s) => JSON.parse(s.replace(/{/gi, '[').replace(/}/gi, ']')); const sortByLength = (a, b) => a.length - b.length; const getOrigin = (origin, tuple) => { origin.push(tuple.filter(num => !origin.includes(num))[0]); return origin; }; function solution (s) { return parseToArr(...arguments) .sort(sortByLength) .reduce(getOrigin, []); } console.log( solution('{{2},{2,1},{2,1,3},{2,1,3,4}}') === [2, 1, 3, 4], solution('{{1,2,3},{2,1},{1,2,4,3},{2}}') === [2, 1, 3, 4], solution('{{20,111},{111}}') === [111, 20], solution('{{123}}') === [123], solution('{{4,2,3},{3},{2,3,4,1},{2,3}}') === [3, 2, 4, 1], ); ================================================ FILE: programmers/난이도별/level02.튜플/sangmandu.py ================================================ def solution(s): s = s[1:-1] lst = [] while True: a = s.find('},') if a != -1: lst.append(s[1:a]) s = s[a+2:] continue break lst.append(s[1:-1]) for i in range(len(lst)): lst[i] = lst[i].split(',') lst2 = sum(lst, []) for i in range(len(lst2)): lst2[i] = int(lst2[i]) answer = [0 for i in range(len(set(lst2)))] for i in set(lst2): answer[lst2.count(i)-1] += i answer.reverse() return answer ================================================ FILE: programmers/난이도별/level02.튜플/sjjyy.java ================================================ import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; public class sjjyy { /* https://programmers.co.kr/learn/courses/30/lessons/64065 @param 원소의 개수가 n개인, 중복되는 원소가 없는 튜플을 표현하는 집합이 담긴 문자열 s @return s가 표현하는 튜플 */ public static int[] solution(String s) { s = s.substring(2, s.length()-2).replace("},{", "/"); // 앞뒤 괄호 제거, 튜플별 분리 String [] str = s.split("/"); // 튜플끼리 배열에 저장 Arrays.sort(str, new Comparator() { @Override public int compare(String s, String t1) { return s.length() - t1.length(); } }); // 배열 길이 크기대로 정렬 ArrayList arrayList = new ArrayList<>(); for (String s1 : str) { String [] arr = s1.split(","); // 튜플 값 각각 저장 for (String value : arr) { int number = Integer.parseInt(value); // String -> int if (!arrayList.contains(number)) // 중복된 값 제외 arrayList.add(number); } } int [] answer = new int[arrayList.size()]; for (int i = 0 ; i < arrayList.size() ; i++) answer[i] = arrayList.get(i); return answer; } public static void main(String [] args) { System.out.println(Arrays.toString(solution("{{2},{2,1},{2,1,3},{2,1,3,4}}"))); // [2, 1, 3, 4] System.out.println(Arrays.toString(solution("{{1,2,3},{2,1},{1,2,4,3},{2}}"))); // [2, 1, 3, 4] System.out.println(Arrays.toString(solution("{{20,111},{111}}"))); // [111, 20] System.out.println(Arrays.toString(solution("{{123}}"))); // [123] System.out.println(Arrays.toString(solution("{{4,2,3},{3},{2,3,4,1},{2,3}}"))); // [3, 2, 4, 1] } } ================================================ FILE: programmers/난이도별/level02.파일명_정렬/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/17686# 문제 : [3차] 파일명 정렬 dictonary의 value에 HEAD와 NUMBER를 분리해서 리스트로 넣고 value를 기준으로 정렬해 주었습니다. 정렬 후 key의 순서에 따라 files 값을 return 하였습니다. 정규식 사용할 생각은 전혀 하지 못했는데 다들 정규식을 사용하더라구요 문자가 나오면 무조건 re 사용하는게 편하다는 말을 또 잊어버리고 있었어요 정규식 계속 까먹어서 정규식 문제 나올때마다 링크 다시 가서 보고 중... [메모] import re a = sorted(files, key=lambda x:int(re.findall('\d+',x)[0])) b = sorted(a, key=lambda x:re.split('\d+',x.lower())[0]) ''' def solution(files): answer = [] dic = {} for i in range(len(files)) : temp = list(files[i]) ishead = True HEAD, NUMBER = '','' for j in temp : if not j.isdigit() and ishead : HEAD += j elif j.isdigit() : ishead = False NUMBER += j else : break dic[i] = [HEAD.lower()] dic[i].append(int(NUMBER)) dic = sorted(dic.items(), key=lambda x:x[1]) for i in range(len(dic)) : answer.append(files[dic[i][0]]) return answer ================================================ FILE: programmers/난이도별/level02.폰켓몬/6047198844.cpp ================================================ #include #include #include using namespace std; int solution(vector nums) { map mp; int num_size = nums.size(); for(int i=0;i mp_size ? mp_size : num_size/2; return answer; } ================================================ FILE: programmers/난이도별/level02.폰켓몬/khw.js ================================================ function solution(nums) { const set1 = new Set(nums); const n_divide_length = nums.length/2; var result = Array.from(set1); if(n_divide_length=result.length){ return result.length; } } //좀더 간결하고 const 생각하면서 수정 function solution(nums) { const set1 = new Set(nums); //중복된 것을 제거한 set1 설정 const result = Array.from(set1); // 다시 set1을 배열로 변환 const n_divide_length = nums.length/2; // N/2만큼 가져가도 좋은 크기 설정 const result_length = result.length; // 중복을 제외한 가능한 모든 종류의 갯수 return (n_divide_length list = new ArrayList<>(); for (int num : nums) { // 중복되는 폰켓몬 번호를 제외하고 리스트에 삽입 if (!list.contains(num)) list.add(num); } return Math.min(list.size(), nums.length / 2); // 선택할 수 있는 개수보다 폰켓몬의 종류가 적으면 폰켓몬의 종류를, 아니면 선택할 수 있는 개수를 리턴 } public static void main(String[] args) { int[] nums1 = {3, 1, 2, 3}; int[] nums2 = {3, 3, 3, 2, 2, 4}; int[] nums3 = {3, 3, 3, 2, 2, 2}; System.out.println(solution(nums1)); // 2 System.out.println(solution(nums2)); // 3 System.out.println(solution(nums3)); // 2 } } ================================================ FILE: programmers/난이도별/level02.프렌즈4블록/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17679 프렌즈4블록 board를 만지기 쉽게 90도 회전함. 이후 자기 자신과 왼쪽 위, 왼쪽, 위가 같으면 0으로 변경. 이후, 0을 다 뺴고 그만큼 뒤에 다시 채워넣음. ''' def solution(m, n, board): board = [list(e) for e in zip(*board[::-1])] while True: cnt = 0 rid = [] for i in range(1, n): for j in range(1, m): if board[i][j] and board[i][j] == board[i - 1][j] == board[i][j - 1] == board[i - 1][j - 1]: rid.append((i, j)) cnt += 1 if cnt == 0: break for i, j in rid: board[i][j] = board[i - 1][j] = board[i][j - 1] = board[i - 1][j - 1] = 0 for i in board: while 0 in i: i.remove(0) while len(i) != m: i.append(0) return sum([i.count(0) for i in board]) ''' ''' ================================================ FILE: programmers/난이도별/level02.프린터/6047198844.cpp ================================================ #include #include #include #include #include using namespace std; int solution(vector priorities, int location) { int answer = 0; deque > dq; //dq에는 위치(i)와 중요도 (priorities)가 저장된다. int priorities_size = priorities.size(); for (int i = 0; i < priorities_size; i++) dq.push_back({ i,priorities[i] }); int dq_size = dq.size(); int print_location = -1; //원하는 위치가 print되게 되면 반복문을 빠져나갑니다. while (location != print_location) { bool check = true; //q의 맨앞에 있는 중요도가 뒤에 있는 중요도보다 작다면 출력이 불가능합니다. check를 false로 합니다. for (int i = 1; i < dq_size; i++) { if (dq[0].second < dq[i].second) { check = false; break; } } //check가 true인 경우 프린트합니다. 프린트했으니 순서(answer)도 증가합니다. if (check) { print_location = dq.front().first; answer++; } //check가 false인 경우 프린트되지않았습니다. dq의 맨뒤에 놓습니다. (push_back합니다.) else dq.push_back(dq.front()); dq.pop_front(); } return answer; } ================================================ FILE: programmers/난이도별/level02.프린터/Jaewon0702.py ================================================ def solution(priorities, location): original=0 while(priorities!=[]) : m=max(priorities) p=priorities.pop(0) if p 0 else len(priorities)-1 continue original+=1 #이 이후로는 https://somjang.tistory.com/155를 참고하였다. if location == 0 : break else : location-=1 return original print(solution([2,2,2,1,3,4],3)==6) print(solution([2,1,3,2], 2) == 1) print(solution([1,1,9,1,1,1], 0) == 5) #100점 ================================================ FILE: programmers/난이도별/level02.프린터/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/42587 ================================================ FILE: programmers/난이도별/level02.프린터/dkdlelk99.py ================================================ def solution(priorities, location): prioritiesMax = max(priorities) bool_list = [False]*len(priorities) bool_list[location] = True count = 0 while True: if priorities[0] < prioritiesMax: priorities.append(priorities.pop(0)) bool_list.append(bool_list.pop(0)) else: count += 1 priorities.pop(0) if bool_list.pop(0): return count prioritiesMax = max(priorities) print(solution([2,1,3,2], 2) == 1) print(solution([1,1,9,1,1,1], 0) == 5) ================================================ FILE: programmers/난이도별/level02.프린터/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42583?language=javascript function solution(bridge_length, w, ws) { let num = 0, sum = 0 const queue = [] while (ws.length) { num += 1 if (queue.length && queue[0].t === num) { sum -= queue.shift().w } if (sum + ws[0] <= w) { const w = ws.shift() queue.push({w, t: num + bridge_length}) sum += w } } return queue.pop().t; } console.log(solution(2, 10, [7,4,5,6])) console.log(solution(100, 100, [10])) console.log(solution(100, 100, [10,10,10,10,10,10,10,10,10,10])) ================================================ FILE: programmers/난이도별/level02.프린터/rockmiin.py ================================================ def solution(priorities, location): answer=0 while True: if priorities[0] == max(priorities): answer+=1; priorities.pop(0) if location==0: return answer else: location-=1 else: priorities.append(priorities.pop(0)) if location==0: location=len(priorities)-1 else: location-=1 return answer print( solution([2, 1, 3, 2], 2)==1 ) ================================================ FILE: programmers/난이도별/level02.프린터/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42587 프린터 : pop한 데이터의 우선순위가 낮으면 다시 append 제일 높은 우선순위의 순서를 기록하면서 해당 우선순위를 제일 낮게 만듬 ''' def solution(priorities, location): size = len(priorities) order = [0] * size i, j = 0, 1 while min(order) == 0: if max(priorities) == priorities[i]: order[i] = j priorities[i] = 0 j += 1 i = (i + 1) % sizeㅁㄴㅇ return order[location] ''' any는 iteration 객체에 대해서 하나라도 참이면 참을 반환 all은 iteration 객체에 대해서 모두 참이어야 참을 반환 내 코드보다 수행시간이 빨라서 참고했음 ㅁㄴㅇㅁㄴㅇdef solution(priorities, location): queue = [(i,p) for i,p in enumerate(priorities)] answer = 0 while True: cur = queue.pop(0) if any(cur[1] < q[1] for q in queue): queue.append(cur) else: answer += 1 if cur[0] == location: return answer ''' ================================================ FILE: programmers/난이도별/level02.피보나치_수/Go-yj.py ================================================ ''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/12945 문제 : 피보나치 수 예전에 문제 리뷰하다가 본 멀리뛰기 문제랑 굉장히 유사했으나 며칠 지났다고 어떻게 했었는지 잊어버렸더라구요 ㅋㅋㅋㅋㅋ 리스트 없이 푸는 방법 다시 메모! [메모메모] a,b = 0,1 for i in range(2,n+1) : a,b = b,a+b return b ''' def solution(n): F = [0,1] for i in range(2,n+1) : F.append(F[i-1]+F[i-2]) return F[-1]%1234567 ================================================ FILE: programmers/난이도별/level02.피보나치_수/HyeonJeong.py ================================================ def solution(n): fibo = [0, 1] for i in range(2, n + 1): fibo.append(fibo[i - 1] + fibo[i - 2]) return fibo[-1] % 1234567 print( solution(3) == 2, solution(5) == 5 ) ================================================ FILE: programmers/난이도별/level02.피보나치_수/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/12945 ================================================ FILE: programmers/난이도별/level02.피보나치_수/dkdlelk99.py ================================================ def solution(n): fibo = [0,1] for i in range(n-1): fibo.append(fibo[-1] + fibo[-2]) return fibo[-1] % 1234567 print(solution(3) == 2) print(solution(5) == 5) ================================================ FILE: programmers/난이도별/level02.피보나치_수/rockmiin.py ================================================ def solution(n): # A(n)= A(n-1)+A(n-2) dp=[0, 1] for i in range(2, n+1): dp.append((dp[i-1]+dp[i-2])%1234567) return dp[-1] print( solution(5)==5 ) ================================================ FILE: programmers/난이도별/level02.피보나치_수/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12945 피보나치 수 ''' def solution(n): fibonachi = [0, 1] for i in range(2, n+1): fibonachi.append(fibonachi[i-1] + fibonachi[i-2]) return fibonachi[-1] % 1234567 ''' 메모리를 적게 쓰는 방법. 당연히 속도가 빨라지면 메모리는 많이 쓰게 되는 tradeoff로 생각했는데, 속도와 메모리를 둘 다 잡은 코드. a,b = 0,1 for i in range(num): a,b = b,a+b return a ''' ================================================ FILE: programmers/난이도별/level02.행렬_테두리_회전하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/77485 행렬 테두리 회전하기 matrix 조작 ''' def solution(rows, columns, queries): answer = [] board = [[row * columns + column + 1 for column in range(columns)] for row in range(rows)] for query in queries: y1, x1, y2, x2 = map(lambda a: a - 1, query) tmp = board[y1][x1] lst = [tmp] for x in range(x1 + 1, x2 + 1): board[y1][x], tmp = tmp, board[y1][x] lst.append(tmp) for y in range(y1 + 1, y2 + 1): board[y][x2], tmp = tmp, board[y][x2] lst.append(tmp) for x in range(x2 - 1, x1 - 1, -1): board[y2][x], tmp = tmp, board[y2][x] lst.append(tmp) for y in range(y2 - 1, y1 - 1, -1): board[y][x1], tmp = tmp, board[y][x1] lst.append(tmp) answer.append(min(lst)) return answer ''' 나름 깔끔히 푼 것 같다 ''' ================================================ FILE: programmers/난이도별/level02.행렬_테투리_회전하기/6047198844.py ================================================ def solution(rows, columns, queries): answer = [] # 1 + (row - 1) * columns ~ row * columns board = [list(range(1 + (row - 1) * columns, row * columns + 1)) for row in range(1, rows+1)] for query in queries: top_y, top_x, bottom_y, bottom_x = query top_x -= 1 top_y -= 1 bottom_x -= 1 bottom_y -= 1 top = board[top_y][top_x:bottom_x] bottom = board[bottom_y][top_x+1:bottom_x+1] left = list(list(zip(*board))[top_x][top_y+1:bottom_y+1]) right = list(list(zip(*board))[bottom_x][top_y:bottom_y]) answer.append(min(top+bottom+left+right)) #위쪽 이동 for idx, x in enumerate(range(top_x+1, bottom_x+1)): board[top_y][x] = top[idx] #아래쪽 이동 for idx, x in enumerate(range(top_x, bottom_x)): board[bottom_y][x] = bottom[idx] #왼쪽 이동 for idx, y in enumerate(range(top_y, bottom_y)): board[y][top_x] = left[idx] #오른쪽 이동 for idx, y in enumerate(range(top_y+1, bottom_y+1)): board[y][bottom_x] = right[idx] return answer ================================================ FILE: programmers/난이도별/level02.행렬의곱셈/6047198844.cpp ================================================ #include #include using namespace std; vector> solution(vector> arr1, vector> arr2) { int arr1_y_size = arr1.size(); int arr1_x_size = arr1[0].size(); int arr2_y_size = arr2.size(); int arr2_x_size = arr2[0].size(); vector> answer; for(int arr1_y = 0;arr1_y vt; for(int arr2_x=0;arr2_x #include #include using namespace std; int rel_size; vector > rel_col_t; //idx : 현재 골라야하는 idx //학번 이름 전공 학년 /* 학번 이름 전공 이름 학년 전공 학년 */ //vt : 현재 뽑은 col //rel_col_t : 해당 집합이 포함되서는 안된다. int select_key(vector> &relation, vector &vt, int idx, int current_sel, int target_sel) { if (current_sel == target_sel) { int rel_col_t_size = rel_col_t.size(); int vt_size = vt.size(); for (int i = 0; i < rel_col_t_size; i++) { int temp_size = rel_col_t[i].size(); int cnt = 0; for (int j = 0; j < temp_size; j++) { for (int k = 0; k < vt_size; k++) { if (rel_col_t[i][j] == vt[k]) cnt++; } } if (cnt == temp_size) return 0; } map mp; int relation_size = relation.size(); vector check_vt; for (int row = 0; row < relation_size; row++) { string temp; for (auto col : vt) { temp = temp + relation[row][col] + '/'; } check_vt.push_back(temp); } int res = 1; int check_vt_size = check_vt.size(); for (int i = 0; i < check_vt_size; i++) { if (mp.find(check_vt[i]) == mp.end()) { mp[check_vt[i]] = true; } else { res = 0; break; } } if (res) { vector temp; for (auto col : vt) temp.push_back(col); rel_col_t.push_back(temp); } return res; } if (idx == rel_size) return 0; int answer = 0; for (int i = idx; i < rel_size; i++) { vt.push_back(i); answer += select_key(relation, vt, i + 1, current_sel + 1, target_sel); vt.pop_back(); } return answer; } int solution(vector> relation) { int answer = 0; vector vt = {}; rel_size = relation[0].size(); for (int i = 1; i <= rel_size; i++) { answer += select_key(relation, vt, 0, 0, i); } return answer; } int main() { cout << solution({ {"100", "ryan", "music", "2"}, {"200", "apeach", "math", "1"}, {"300", "tube", "computer", "3"}, {"400", "con", "computer", "4"}, {"500", "muzi", "music", "3"}, {"600", "apeach", "music", "5"} }); } /* 복습하기 #include using namespace std; bool possi(vector &vec,int now){ for(int i=0;i> relation) { int n=relation.size(); int m=relation[0].size(); vector ans; for(int i=1;i<(1< s; for(int j=0;j 이후, 110을 특정 위치에 넣을것임 => 110이 몇개가 있는지 총 개수를 센다. 2. 110을 미리 빼내도 문제가 없는 것인가? => 그렇다. 110은 앞뒤로 대칭이 아니다. 문제되지 않음 => 만약 111이었다면 문제가 될 수 있다. => 111을 다 빼고 다시 넣어도 새로운 111이 생길 수 있기 때문 3. 이후 뒤에서부터 s를 세서 0을 만나면 바로 그 뒤에 110을 추가한다. => 왜? => 110은 사전순으로 뒤에서 두번째의 수이다. => 뒤에서 첫번째의 수는 111 => 따라서 111 보다는 앞에있어야 한다. => 근데 0을 만나면 왜 바로 그 뒤에 추가해? 0전에 111이 있을수도 있잖아 => 가정과 상충한다. 가정 : 이미 110을 다 뽑았음. 0전에 11이 있을 수가 없다. => 그 외에 수들은 0 00 000 10 100 이 있을 수 있다. => 이 수들은 모두 110 보다 사전순으로 앞에 오는 수. => 따라서 0을 발견하면 바로 그 뒤에 추가한다. => else문 => if는 110이 존재하지 않을 때의 예외 => elif는 110을 다 뺏더니 남은 수가 없을 때의 예외 ''' def solution(s): results = [] for num in s: stack = '' ooz = 0 for n in num: stack += n if len(stack) > 2 and stack[-3:] == "110": stack = stack[:-3] ooz += 1 add = '110' * ooz if ooz == 0: results.append(stack) elif len(stack) == 0: results.append(add) else: for idx in range(len(stack) - 1, -1, -1): if stack[idx] == "0": break else: idx -= 1 results.append(stack[:idx + 1] + add + stack[idx + 1:]) return results ''' 굉장히 어려운 문제. https://prgms.tistory.com/57?category=882795를 참고했다. ''' ================================================ FILE: programmers/난이도별/level03.110_옮기기/6047198844.py ================================================ def solution(s): answer = [] for string in s: stack = [] cnt_110 = 0 for char in string: if char == '0' and stack[-2:] == ['1','1']: stack.pop() stack.pop() cnt_110 += 1 else: stack.append(char) group_110 = '110' * cnt_110 for idx in range(len(stack)-1,-1,-1): if stack[idx] == '0': stack.insert(idx+1, group_110) break else: stack.insert(0, group_110) answer.append(''.join(stack)) return answer ================================================ FILE: programmers/난이도별/level03.2xn타일링/.vscode/launch.json ================================================ { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "(gdb) 시작", "type": "cppdbg", "request": "launch", "program": "프로그램 이름 입력(예: ${workspaceFolder}/a.exe)", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "miDebuggerPath": "/path/to/gdb", "setupCommands": [ { "description": "gdb에 자동 서식 지정 사용", "text": "-enable-pretty-printing", "ignoreFailures": true } ] } ] } ================================================ FILE: programmers/난이도별/level03.2xn타일링/6047198844.cpp ================================================ #include #include using namespace std; int memo[60001] = {1}; int dp(int n) { return n < 0 ? 0 : memo[n] ? memo[n] : memo[n] = (dp(n - 2) + dp(n - 1))%1000000007; } int solution(int n) { return dp(n); } ================================================ FILE: programmers/난이도별/level03.2xn타일링/JeongShin.js ================================================ function solution(n) { const fib = [0, 1, 2] for (let i = 3; i <= n; i++) { fib[i] = (fib[i - 2] + fib[i - 1])%1000000007 } return fib[n] } ================================================ FILE: programmers/난이도별/level03.2xn타일링/rockmiin.py ================================================ def solution(n): dp=[0]*(n+1) dp[1]=1; dp[2]=2 for i in range(3, n+1): dp[i]=(dp[i-1]+dp[i-2])%1000000007 return dp[-1] print( solution(4)==5 ) ================================================ FILE: programmers/난이도별/level03.2xn타일링/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12900 2xn 타일링 n에 대한 각 값들이 피보나치 수열로 이루어져 있음 ''' def solution(n): a, b = 1, 2 for i in range(3, n): a, b = b, a+b return (a+b) % 1000000007 ''' 처음에 팩토리얼이나 콤비네이션으로 접근했는데, 결국 중복조합 문제인지라 내 지식선에서는 해결할 수 없었다. n에 대한 각 값들이 피보나치 수열인지도 한참뒤에 알았음. ''' ================================================ FILE: programmers/난이도별/level03.N_Queen/6047198844.py ================================================ col = [True] * 50 row = [True] * 50 left_diag = [True] * 50 right_diag = [True] * 50 def dfs(r, n): if r == n: return 1 ans = 0 for c in range(n): if col[c] and row[r] and left_diag[c+r] and right_diag[n-1+r-c]: col[c] = False row[r] = False left_diag[c+r] = False right_diag[n-1+r-c] = False ans += dfs(r+1, n) right_diag[n-1+r-c] = True left_diag[c+r] = True row[r] = True col[c] = True return ans def solution(n): return dfs(0, n) ================================================ FILE: programmers/난이도별/level03.N_Queen/JeongShin.js ================================================ /* * FIFO 방식 & 분기 한정을 이용한 구현 * Variables : n, col, level * * n 👉 board 의 크기 * * col 👉 board 에 queen 의 위치 * col [1, 2] = | Q | | * | | Q | * * level 👉 현재 고려하고 있는 level 번째 queen * * queue 👉 각 노드별 level, col 의 순서대로 저장하기 위한 자료 구조 * | 2 | 1 | 2 | * | level | col | * * 2 레벨 col [1, 2]를 저장 * */ class queue { constructor() { this.queue = []; this.front = 0; this.rear = 0; } push(el) { this.queue[this.rear++] = el; } pop() { if (this.front < this.rear) { return this.queue[this.front++]; } } isEmpty() { return this.front === this.rear; } } function solution(n) { const Q = new queue(); const col = []; let result = 0; let level = 0; Q.push(level); while (!Q.isEmpty()) { // pop current level & current col let level = Q.pop(); for (let idx = 1; idx <= level; idx++) col[idx] = Q.pop(); // next level level++; // branch creating each child node & bound through promising function for (let i = 1; i <= n; i++) { col[level] = i; // if node is alive if (!promising(col, level)) continue; if (level === n) { result++; continue; } Q.push(level); // push next level to queue Q.push(...col.slice(1, level + 1)); // push current board to queue // else { node is dead 👉 don't push } } } return result } /* * 현재 col 이 현재 level 까지 살아있는지 죽어있는지 판단 합니다. * 판단 조건은 * 1. 퀸이 같은 line에 있을 경우 * 2. 퀸이 대각선에 있을 경우 * 죽은 노드가 됩니다. 즉 false 를 반환 * */ function promising(col, level) { let idx = 1; let isLive = true; while (idx < level && isLive) { // If Queens are in same line || diagonal 👉 node is dead isLive = !(col[idx] === col[level] || Math.abs(col[level] - col[idx]) === level - idx); idx++; } return isLive; } solution(4); ================================================ FILE: programmers/난이도별/level03.N_Queen/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12952 N-Queen [풀이] 1. stack에 다음과 같은 원소를 집어넣는다 {0} : story, 몇번째 가로줄인지. => 초기에 첫번째 가로줄로 초기화. 위에서부터 시작. {1} : hor, 몇번째 세로줄을 고를 수 있는지. => 이전에 고른 세로줄은 고르지 못하므로 하나씩 없어진다. => 선택한 세로줄을 없애기 위해 set 자료형 선택 {2, 3} : diag1, diag2, 대각선 검사 => 가장 왼쪽 위를 (1, 1) 이라고 하면 => 기울기가 -1 인 대각선들의 공통점은 두 좌표의 차가 일정하다는 것 => diag1 => 기울기가 1인 대각선들의 공통점은 두 좌표의 합이 일정하다는 것 => diag2 2. dfs 방식으로 조건을 만족할 때 마다 가로 층을 증가시키며 탐색한다. => bfs 방식이어도 큰 상관은 없음 ''' def solution(n): answer = 0 stack = [[1, set(range(1, n + 1)), [], []]] while stack: story, hor, diag1, diag2 = stack.pop() if story == n + 1: answer += 1 continue for x in hor: if x - story not in diag1 and x + story not in diag2: stack.append([story + 1, hor - set([x]), diag1 + [x - story], diag2 + [x + story]]) return answer ''' 미친 풀이 nQueen = [0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712, 365596, 2279184, 14772512, 95815104, 666090624, 4968057848, 39029188884, 314666222712, 2691008701644, 24233937684440, 227514171973736, 2207893435808352, 22317699616364044, 234907967154122528].__getitem__ ''' ================================================ FILE: programmers/난이도별/level03.N으로_표현/6047198844.py ================================================ #bottom - up방식으로 풀어보기 from collections import defaultdict def solution(N, number): memo = defaultdict(set) for i in range(1,8+1): memo[i].add(int(str(N)*i)) #N을 times번 사용해서 얻을수있는 값들을 리턴한다. def dp(times, N): if len(memo[times]) != 1 or times == 1: return memo[times] for t in range(1,times): for s in dp(times-t,N): for u in dp(t,N): if s + u != 0: memo[times].add(s + u) if s - u != 0: memo[times].add(s - u) if s // u != 0: memo[times].add(s // u) if s * u != 0: memo[times].add(s * u) return memo[times] dp(8,N) for key, value in sorted(memo.items()): if number in value: return key return -1 ================================================ FILE: programmers/난이도별/level03.N으로_표현/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42895 N으로 표현 : 1부터 9의 숫자 중 하나인 n을 최소로 사용하여 임의의 수 제작 총 6가지의 수로 나누었다. 1) 사칙연산 4가지와 자신을 자신으로 나눈 수 1에 대한 +, - 연산 2가지(*, // 연산은 의미가 없다) 2) 이 문제의 골치는 사칙연산 외에도 55, 555 같은 연결연산도 허용한다는 것. 따라서 반복문을 통해 cnt만큼을 비교. ''' def solution(N, number): num = str(N) nums = [0] + [int(num * i) for i in range(1, 9)] def cal(val, cnt): if cnt > 8: return 9 if val == number: return cnt exp = [9] for i in range(1, 9 - cnt): exp.append(cal(val + nums[i], cnt + i)) exp.append(cal(val - nums[i], cnt + i)) exp.append(cal(val * nums[i], cnt + i)) exp.append(cal(val // nums[i], cnt + i)) return min( min(exp), cal(val + 1, cnt + 2), cal(val - 1, cnt + 2), ) answer = cal(0, 0) return answer if answer < 9 else -1 ''' 몇몇 사람은 부분집합? 관계를 이용해서 풀던데 이해하기 귀찮아서 패스.. ''' ================================================ FILE: programmers/난이도별/level03.[1차]_셔틀버스/6047198844.py ================================================ import datetime def solution(n, t, m, timetable): #시간대로 정렬한다. timetable.sort() timeformat = "%H:%M" last_passenger = "00:00" cnt_last_passenger = 0 bus_time = "09:00" #str_time에 분을 더한뒤 다시 string으로 반환한다. def minute_add(str_time,t): str_time = datetime.datetime.strptime(str_time,timeformat) + datetime.timedelta(minutes = t) return str_time.strftime(timeformat) for bus_cnt in range(n): #m명 만큼 탑승시킨다. for _ in range(m): #버스가 도착하고 최대 m명을 탑승시킨다. if timetable and bus_time >= timetable[0]: #마지막에 탄 손님의 시간이 계산된다. last_passenger = timetable.pop(0) if bus_cnt == n-1: cnt_last_passenger += 1 #bus시간을 증가시킨다. bus_time = minute_add(bus_time,t) #마지막버스에 모두가 탑승한 경우 맨 마지막 손님보다 1분 일찍 도착한다. if cnt_last_passenger == m: return minute_add(last_passenger,-1) else: #마지막버스가 비었다면 마지막버스시간에 도착한다. return minute_add(bus_time,-t) #결론 : 콘은 무조건 버스 막차를 타야한다. #막차가 빈다고 예측되면 막차 시간에 맞춰나가면 되고. #막차가 가득찬다고 예측되면 막차를 타는 마지막 손님보다 1분 앞서 타면된다. ================================================ FILE: programmers/난이도별/level03.[1차]_셔틀버스/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/17678 [1차] 셔틀버스 [풀이] 1. 시간 문제라서 import time을 할까 했지만 직접 만지는게 편해 보임 => 각 시간 "hh:mm"을 [hh, mm] 로 변환 2. 시간 역순으로 정렬한다. => 가장 먼저 온 사람부터 태우기 위함 3. board에 가장 먼저 온 사람부터 태울 것이다. => 다 태우면(len(board) < m) 다음 차가 올 것이다(for num in range(n):) => 단, 셔틀이 오기전까지 도착한 사람만 태울 것이다(if timetable[-1][0] < hour or timetable[-1][0] == hour and timetable[-1][1] <= minute:) => 근데 셔틀이 오기전에 도착한 사람이 없으면 그냥 출발할 것이다(break) 4. 마지막 board만을 확인한다. => 콘은 제일 늦게 타야 하므로. 마지막 board만 확인 5. 마지막 셔틀에 자리가 있으면 그냥 탑승. 그렇지 않으면 가장 마지막에 탄 사람보다 1분만 빨리 기다리면 되지 않겠나? => 마지막에 탄 사람보다 1분만 빠르면 된다. (문제 조건은 00:01 부터 23:59 이므로 하루가 넘어가는 예외처리는 필요없음) 6. 이 때 여러 경우의 수를 생각해 볼 수 있다. [9시, 9시 1분, 9시 2분] => 9시 1분에 오면 된다. [9시, 9시, 9시] => 8시 59분에 오면 된다. [9시, 9시], [9시 10분, 9시 10분] => 9시 9분에 오면 된다. => 이 때 마지막 셔틀을 타는 것은 아니기 때문에 => "콘이 셔틀을 타고 사무실로 갈 수 있는도착 시간 중 제일 늦은 시각" 조건을 깨는 것이 아닐까라는 생각할 수 있다. => 그러나 가장 마지막 셔틀을 타지 않더라도 그 전 셔틀을 타는것이 콘이 사무실로 갈 수 있는 제일 늦은 셔틀이다. 7. 실제로 시간과 분을 int형태로 변환했으므로 "9:5" 를 "09:05" 로 변환할 수 있도록 한다. ''' def solution(n, t, m, timetable): timetable = sorted(list(map(lambda x: [int(x[:2]), int(x[3:])], timetable)))[::-1] for num in range(n): hour, minute = 9 + (num * t) // 60, (num * t) % 60 board = [] while len(board) < m and timetable: if timetable[-1][0] < hour or timetable[-1][0] == hour and timetable[-1][1] <= minute: board.append(timetable.pop()) continue break if len(board) >= m: l_hour, l_minute = board[-1] hour, minute = l_hour - int(l_minute - 1 < 0), ((l_minute - 1) + 60) % 60 hour, minute = "0" + str(hour) if hour < 10 else hour, "0" + str(minute) if minute < 10 else minute return f"{hour}:{minute}" ''' ''' ================================================ FILE: programmers/난이도별/level03.[1차]_추석_트래픽/6047198844.py ================================================ import datetime import collections def solution(lines): timetable = list() #데이터 전처리 for line in lines: date, time, duration = line.split() #date 필요없음 end_time = datetime.datetime.strptime(date + " " + time,"%Y-%m-%d %H:%M:%S.%f").timestamp() start_time = end_time - float(duration[:-1]) + 0.001 timetable.append((start_time, end_time)) DQ = collections.deque() answer = 1 for start_time, end_time in timetable: DQ.append((start_time, end_time)) while DQ and not(start_time - DQ[0][1] <= 0.999): DQ.popleft() answer = max(answer,len(DQ)) DQ2 = collections.deque() timetable.sort() for start_time, end_time in timetable: DQ2.append((start_time, end_time)) while DQ2 and not(DQ2[0][0] <= start_time - 0.999): DQ2.popleft() answer = max(answer,len(DQ2)) return answer ================================================ FILE: programmers/난이도별/level03.가사검색/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/60060https://programmers.co.kr/learn/courses/30/lessons/60060 ================================================ FILE: programmers/난이도별/level03.가사검색/junilhwang.js ================================================ function solution(words, queries) { const n = queries.map(v => 0) const len = words.length for (let i = 0; i < len; i++) { const v = words[i] queries.forEach((reg, k) => { const len = v.length if (len !== queries[k].length) return const a = v, b = queries[k] let chk = true for (let i = 0; i < len; i++) { if (b[i] === '?' || b[i] === a[i]) continue chk = false break } if (chk) n[k] += 1 }) } return n; } console.log( solution( ["frodo", "front", "frost", "frozen", "frame", "kakao"], ["fro??", "????o", "fr???", "fro???", "pro?"] ), [3, 2, 4, 1, 0] ) ================================================ FILE: programmers/난이도별/level03.가장_긴_팰린드롬/6047198844.py ================================================ def solution(s): for l in range(len(s),0,-1): for i in range(0,len(s)-l+1): if s[i:i+l] == s[i:i+l][::-1]: return l ================================================ FILE: programmers/난이도별/level03.가장_긴_팰린드롬/JeongShin.js ================================================ function solution(s) { const len = s.length let max = 0 for (let i = 0; i < len; i += 0.5) { const [leftIdx, rightIdx] = [Math.floor(i), Math.ceil(i)]; let count = 0 for (; count < len; count++) { const [left, right] = [s[leftIdx - count], s[rightIdx + count]] if (!left || !right || left !== right) break } max = Math.max(max, count * 2 - (leftIdx === rightIdx)) } return max } ================================================ FILE: programmers/난이도별/level03.가장_긴_팰린드롬/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12904 가장 긴 팰린드롬 매 단어마다 앞뒤 비교 ''' def solution(s): ret = 1 for idx in range(len(s)): i = j = 1 while idx-i >= 0 and idx+i < len(s) and s[idx-i] == s[idx+i]: i += 1 if idx + 1 < len(s) and s[idx] == s[idx+1]: while idx-j >= 0 and idx+1+j < len(s) and s[idx-j] == s[idx+1+j]: j += 1 if i > 1: i = i*2 - 1 if j > 1: j = j*2 ret = max(ret, i, j) return ret ''' 시간 복잡도는 N^2 정도인 것 같다. 물론 best case는 N 나름 괜찮다 하고 풀었는데 다른 사람들과 비슷해서 아쉽. 시간 효율이 떨어지지만 key point는 s에서 대칭이 아니면 s[1:]과 s[:-1]에서 대칭을 찾아야 한다는 점. 이렇게 짠 코드를 보고 놀랐다. ''' ================================================ FILE: programmers/난이도별/level03.가장_먼_노드/JeongShin.js ================================================ class queue { constructor() { this.queue = []; this.front = 0; this.rear = 0; } isEmpty() { return this.rear <= this.front; } push(v) { this.queue.push(v); this.rear++; } pop() { const result = this.queue[this.front]; if (result) { this.front++; return result; } } } function solution(n, edge) { const graph = {}; const bfs = (start) => { const Q = new queue(); Q.push({vertex: start, distance: 0}); const visited = {}; visited[start] = 0; while (!Q.isEmpty()) { const {vertex, distance} = Q.pop(); graph[vertex].forEach((neighbor) => { if (visited[neighbor] === undefined) { visited[neighbor] = distance + 1; Q.push({vertex: neighbor, distance: distance + 1}); } }); } return Object.values(visited); }; for (const v of edge) { const [from, to] = v; graph[from] = (graph[from] || []); graph[to] = (graph[to] || []); graph[from].push(to); graph[to].push(from); } const distances = bfs(1); const max_distance = Math.max(...distances); return distances.reduce((count, distance) => count + (distance === max_distance), 0); } solution(6, [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]]); ================================================ FILE: programmers/난이도별/level03.가장_먼_노드/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/49189 가장 먼 노드 [풀이] 1에서 부터 bfs로 접근하고 이에 따라서 거리를 +1씩 부여하는 방법 시간초과 이슈에 대해서는 간선을 조사할 때 행렬이 아니라 딕셔너리로 조사 ''' from collections import defaultdict def solution(n, edge): board = defaultdict(list) dist = [0, 0.5] + [0] * (n - 1) for st, ed in edge: board[st].append(ed) board[ed].append(st) stack = [1] save = [] distance = 1 while True: if not stack: if not save: return dist.count(max(dist)) distance += 1 save, stack = stack, save st = stack.pop() for idx in board[st]: if dist[idx] == 0: dist[idx] = distance save.append(idx) ''' ''' ================================================ FILE: programmers/난이도별/level03.가장_먼_노드/turquoiseluv.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/49189 BFS로 노드 길이가 최대인 노드 개수 구하기 1) 주어진 노드 정보를 graph[특정 노드] = 연결된 노드 형태로 변환 *중요! 아니면 매번 간선이 있는지 검색해야하기 때문에 런타임 오류 남 2) start 노드(now)와 인접한 노드들을 모두 save에 append 3) now가 비었으면, 다음 save와 now를 교체하여 2~3번 반복 4) save에 저장된 노드들은 모두 시작과 같은 거리의 노드들이기에, 모든 노드들이 방문되었으면 가장 마지막 save의 노드들의 개수를 반환 ''' n = 6 vertex = [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]] # return 3 def solution(n, vertex): graph = [[]for i in range(n+1)] for st, ed in vertex: graph[st].append(ed) graph[ed].append(st) visited = [1] + [0]*(n) save = [] start = 1 now = [start] visited[start] = 1 while now or not all(visited): if not now: now, save = save, now start = now.pop() for v in graph[start]: if not visited[v]: visited[v] = 1 save.append(v) return len(save) print(solution(n, vertex)) ================================================ FILE: programmers/난이도별/level03.가장먼노드/6047198844.py ================================================ #1부터 n까지 번호가 적혀있다. #1번 노드에서 가장 멀리 떨어진 노드의 갯수를 구하는것. #BFS? import collections def solution(n, edge): #graph작성 graph = collections.defaultdict(list) for u, v in edge: graph[u].append(v) graph[v].append(u) Q = [1] discovered = set() discovered.add(1) n = 0 while Q: n = len(Q) for _ in range(n): node = Q.pop(0) for v in graph[node]: if not v in discovered: discovered.add(v) Q.append(v) answer = n return answer ================================================ FILE: programmers/난이도별/level03.거스름돈/6047198844.py ================================================ from collections import defaultdict from functools import lru_cache def solution(n, money): #0인경우 1. 그외의 경우 아직정해지지 않았으므로 0 dp = [1] + [0] * n for coin in money: for price in range(coin, n + 1): if price >= coin: dp[price] += dp[price - coin] return dp[n] % 1000000007 ''' 시간초과나는 이유? answer = 0 money.sort() #memo[idx][n] memo = [[-1 for _ in range(0,n+1)] for _ in range(0,len(money))] #경우의 수를 반환한다. def dfs(cur, n): if n == 0: return 1 if memo[cur][n] != -1: return memo[cur][n] memo[cur][n] = 0 for idx in range(cur,len(money)): if n-money[idx] < 0: break memo[cur][n] = (memo[cur][n] + dfs(idx, n-money[idx]) % 1000000007) % 1000000007 return memo[cur][n] return dfs(0, n) % 1000000007 ''' ================================================ FILE: programmers/난이도별/level03.거스름돈/JeongShin.js ================================================ /* * 모든 경우의 수 중에서 sum 이 n 인걸 찾는 재귀 알고리즘 * 👉 시간초과 * */ // function solution2(n, money) { // const len = money.length; // money.sort((a, b) => b - a) // let count = 0; // const getSum = (sum, idx) => { // if (n <= sum) { // if (sum === n) // count++; // return; // } // for (let i = idx; i < len; i++) // getSum(sum + money[i], i) // } // // getSum(0, 0) // return count; // } function solution(n, money) { const table = []; const len = money.length for (let i = 0; i <= n; i++){ table[i] = i % money[0] ? 0 : 1; } for (let i = 1; i < len; i++) { for (let j = money[i]; j <= n; j++) { table[j] += table[j - money [i]] } } return table[n] % 1000000007 } solution(5, [1, 2, 5]) ================================================ FILE: programmers/난이도별/level03.거스름돈/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12907 거스름돈 [풀이] 1. 각 코인에 대해서 반복문 => 1부터 n까지 해당 코인이 n원을 이룰 수 있는지 검사 => 예를 들어 dp[1] 은 n=1 일 때의 여러 코인을 가지고 구성할 수 있는 경우의 수 => a원의 코인을 가지고 이야기 할 때, => dp[n+a]는 dp[n]에서 a원을 더한것이므로 => 적어도 dp[n]을 구성하는 경우의 수만큼은 dp[n+a]에서도 존재할 것임 따라서 dp[n]을 더해준다. => 예를 들어 시작점에서 목적지까지 A길과 B길이 있고, => A길은 2갈래 길, B길은 3갈래 길이라면 총 갈 수 있는 방법은 5가지와 마찬가지. => dp[2+3]은 dp[2]에서 3원을 더한것이므로 dp[2]의 경우를 dp[5]에 더해주고 => dp[4+1]은 dp[4]에서 1원을 더한것이므로 dp[4]의 경우를 dp[5]에 더해준다. => 핵심은 이 작업은 a원에 대해서 한다는 것 2. dp = [1] + [0] * n => price가 coin 보다 크거나 같을 때 더해주는 연산을 하는데, => 같을 때의 경우를 고려해준 것 => dp[0+5]는 dp[0]에서 5원을 더한 것이다. => 이는 기본적으로 5원을 구성하기 위해 5원 자체로 존재하는 방법 1가지가 존재하므로 => dp[0]을 1로 설정. ''' def solution(n, money): dp = [1] + [0] * n for coin in money: for price in range(coin, n + 1): dp[price] += dp[price - coin] return dp[n] % 1000000007 ''' bfs 문제로 풀었더니 시간초과. dp 로는 해결하지 못해서 다른 풀이 참조. https://velog.io/@younge/Python-프로그래머스-거스름돈-연습문제DP ''' ================================================ FILE: programmers/난이도별/level03.경주로_건설/6047198844.py ================================================ import heapq def solution(board): answer = 0 PQ = [] heapq.heappush(PQ,((0,(0,0),'R'))) heapq.heappush(PQ,((0,(0,0),'D'))) N = len(board) visited = set() visited.add(((0,0),'R')) visited.add(((0,0),'D')) DICT = {'L':(0,-1), 'R':(0,1), 'U':(-1,0), 'D':(1,0)} route = [[0 for j in range(N)] for i in range(N)] while PQ: cost, pos, prev = heapq.heappop(PQ) for direction in 'L', 'R', 'U', 'D': y, x = pos dy, dx = DICT[direction] ny, nx = y + dy, x + dx if 0 <= ny < N and 0 <= nx < N and board[ny][nx] != 1: #and ((ny,nx),direction) not in visited: ncost = cost + 100 if prev != direction: ncost = cost + 600 if ((ny,nx),direction) not in visited or ncost < route[ny][nx]: heapq.heappush(PQ,(ncost,(ny, nx),direction)) visited.add(((ny,nx),direction)) if route[ny][nx] == 0 or ncost < route[ny][nx]: route[ny][nx] = ncost return route[N-1][N-1] ================================================ FILE: programmers/난이도별/level03.경주로_건설/rockmiin.py ================================================ from collections import deque moves = [[0, 1, 'R'], [0, -1, 'L'], [1, 0, 'D'], [-1, 0, 'U']] def solution(board): n = len(board[0]) result = [] def bfs(v): cost = [[0] * n for _ in range(n)] q = deque([v]) cost[v[0]][v[1]] = 1 while q: x, y, c, d = q.popleft() if x == n - 1 and y == n - 1: result.append(cost[x][y]) continue; for dx, dy, dir in moves: tx, ty = x + dx, y + dy if 0 <= tx < n and 0 <= ty < n and board[tx][ty] == 0: if d in ['L', 'R']: if dir in ['L', 'R']: new_cost = c+ 100 else: new_cost = c+ 600 else: if dir in ['L', 'R']: new_cost = c+ 600 else: new_cost = c+ 100 if not cost[tx][ty] or cost[tx][ty] > new_cost: cost[tx][ty]= new_cost q.append([tx, ty, new_cost,dir]) # 처음 시작 방향에 따른 값 변경 bfs([0, 0, 0, 'R']) bfs([0, 0, 0, 'D']) return min(result) print(solution([[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,0],[0,0,0,1,0,0,0,1], [0,0,1,0,0,0,1,0],[0,1,0,0,0,1,0,0],[1,0,0,0,0,0,0,0]])) ================================================ FILE: programmers/난이도별/level03.경주로_건설/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/67259 경주로 건설 [풀이] 0. 문제에 오류가 있습니다. https://programmers.co.kr/questions/18816 1. [0, 0] 에서 시작하는 dfs(bfs여도 상관없음) 2. 각 노드가 visited를 가지면 시간초과 => 따라서 baord의 원소들이 최소 cost값을 비교해서 가지도록 함 => DP 문제 3. 방향이 같으면 100, 코너가 생성되면 600 4. 마지막 좌표값을 반환 ''' def solution(board): stack = [[0, 0, 'START']] # y, x, direction size = len(board) board[0][0] = -500 while stack: y, x, direction = stack.pop() cost = board[y][x] for dy, dx, drt in [(-1, 0, 'U'), (0, -1, 'L'), (1, 0, 'D'), (0, 1, 'R',)]: ny, nx = y + dy, x + dx c = 0 if 0 <= ny < size and 0 <= nx < size: if board[ny][nx] != 1: c += 100 if direction != drt: c += 500 if board[ny][nx] == 0 or board[ny][nx] >= cost + c: board[ny][nx] = cost+c stack.append([ny, nx, drt]) return board[-1][-1] ''' 문제에 오류가 있어서, 다르게 풀어보고 싶었는데 풀지 못했다. ''' ================================================ FILE: programmers/난이도별/level03.광고_삽입/6047198844.py ================================================ import datetime import collections def convert_to_time(time): hour = time // 3600 time -= hour * 3600 minute = time // 60 time -= minute * 60 sec = time return str(hour).zfill(2) + ":" + str(minute).zfill(2) + ":" + str(sec).zfill(2) def convert_to_sec(time): hour, minute, sec = map(int, time.split(':')) return hour * 3600 + minute * 60 + sec def solution(play_time, adv_time, logs): answer = '' logs.sort() times = [] for log in logs: start_time, end_time = map(convert_to_sec, log.split('-')) times.append((start_time, end_time)) arr = [0] * 360001 window = collections.deque() longest_time = 0 cur_time = 0 adv_time = convert_to_sec(adv_time) play_time = convert_to_sec(play_time) # 변화량 기록 for start_time, end_time in times: arr[start_time] += 1 arr[end_time] -= 1 # 해당 변화량으로 배열을 채운다. for idx in range(1, 360001): arr[idx] += arr[idx - 1] # 윈도우를 이용, 정답을 구한다. maxval = sum(arr[:adv_time]) maxtime = 0 curval = maxval for i in range(0, 360001 - adv_time): curval = curval - arr[i] + arr[i + adv_time] if curval > maxval: maxval = curval maxtime = i + 1 return convert_to_time(maxtime) ================================================ FILE: programmers/난이도별/level03.광고_제거/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/72414 광고 제거 [풀이] 1. 시간을 hh:mm:ss 꼴에서 ss꼴로 변환하기 => 자주 사용하므로 함수화 2. play_time 만큼의 시간 리스트를 생성한다 => DP 문제이다 3. 각 시간별로 사용자의 시청 시작 시간이 있는 위치에 +1을, 시청 종료 시간이 있는 위치에 -1을 대입한다 4. 이후, 각 시간을 이전 시간과 자신의 합으로 표현한다 => times[idx] += times[idx-1] => 이렇게 되면 각 시간에 시청하고 있는 사용자 수를 알 수 있게 된다 5. 이후, 첫 시간부터 광고시간 만큼 유저수를 비교해서 최대를 파악한다 => 이 부분도 어려운 아이디어인데, 보통 이 문제를 풀면 총 시간을 세려고 하는데 여기서는 단지 각 시간마다의 유저수를 세는 것이 포인트이다. 유저 수가 곧 1초이므로. => 이 때 매번 리스트 sum을 하면 시간 복잡도에 걸리므로 마지막 원소를 추가하고 첫 원소를 제거하는 것도 포인트이다. 6. 좀 더 이해를 돕기위해 카카오 공식 해설 링크를 삽입한다. https://tech.kakao.com/2021/01/25/2021-kakao-recruitment-round-1/ ''' def solution(play_time, adv_time, logs): spt = lambda x: list(map(int, x.split(':'))) wsum = lambda y: 3600 * y[0] + 60 * y[1] + y[2] trsf = lambda z: wsum(spt(z)) play, adv = trsf(play_time), trsf(adv_time) times = [0] * (play + 1) logs = [log.split('-') for log in logs] for st, ed in logs: times[trsf(st)] += 1 times[trsf(ed)] -= 1 for idx in range(1, play): times[idx] += times[idx - 1] curtime = sum(times[:adv]) maxidx, maxtime = 0, curtime for idx in range(adv, play): curtime = curtime + times[idx] - times[idx - adv] if maxtime < curtime: maxtime = curtime maxidx = idx - adv + 1 return f"{maxidx // 3600:02d}:{maxidx % 3600 // 60:02d}:{maxidx % 60:02d}" ''' 너무 어렵다.. 정답률 1%대 문제일 만 하다.. 당시에 나도 시간초과에 벽에 걸렸었는데 이런 아이디어를 생각하지 못했다. 역시 어지간하면 풀이는 쉽다. 어렵게 풀면 내가 잘못가고 있다고 생각해야 할 듯 https://www.youtube.com/watch?v=Yr_xHHNsBog 참고했다 ''' ================================================ FILE: programmers/난이도별/level03.기둥과보/6047198844.py ================================================ def solution(n, build_frame): structures = set() def is_valid(): for structure in structures: x, y, kind = structure if kind == 1: if not ((x, y - 1, 0) in structures or (x + 1, y - 1, 0) in structures or ( (x - 1, y, 1) in structures and (x + 1, y, 1) in structures)): return False else: if not (y == 0 or (x, y - 1, 0) in structures or (x - 1, y, 1) in structures or ( x, y, 1) in structures): return False return True for frame in build_frame: x, y, kind, cmd = frame # 삽입 if cmd == 1: structures.add((x, y, kind)) if not is_valid(): structures.remove((x, y, kind)) # 삭제 else: structures.remove((x, y, kind)) if not is_valid(): structures.add((x, y, kind)) answer = list(structures) answer.sort() return answer ================================================ FILE: programmers/난이도별/level03.기둥과보/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/60061 ================================================ FILE: programmers/난이도별/level03.기둥과보/junilhwang.js ================================================ function solution(n, build_frame) { var answer = [], stack = [], nodeA = [], nodeB = []; // a {0 - 기둥, 1 - 보}, b {0 - 삭제, 1 - 설치} build_frame.forEach(([x, y, a, b]) => { if (b === 0) { const idx = answer.findIndex(([x2, y2, a2]) => { return (x2 === x && y2 === y && a2 === a) }) answer.splice(idx, 1) } else { if (y === 0 && a === 1) return if (a === 1) { if (nodeA[y] === undefined) { nodeA[y][x] = nodeA[y][x+1] = x } else { switch (true) { case nodeA[y][x] === undefined && nodeA[y][x + 1] === undefined: nodeA[y][x] = nodeA[y][x + 1] = x break case nodeA[y][x] !== undefined && nodeA[y][x + 1] === undefined: nodeA[y][x+1] = nodeA[y][x] break case nodeA[y][x] === undefined && nodeA[y][x + 1] !== undefined: nodeA[y][x] = nodeA[y][x+1] break } } } answer.push([x, y, a]) } }) answer.sort((a, b) => a[0] - b[0]) return answer; } /* console.log( solution( 5, [[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]] ), [[1, 0, 0], [1, 1, 1], [2, 1, 0], [2, 2, 1], [3, 2, 1], [4, 2, 1], [5, 0, 0], [5, 1, 0]] ) */ console.log( solution( 5, [[0, 0, 0, 1], [2, 0, 0, 1], [4, 0, 0, 1], [0, 1, 1, 1], [1, 1, 1, 1], [2, 1, 1, 1], [3, 1, 1, 1], [2, 0, 0, 0], [1, 1, 1, 0], [2, 2, 0, 1]] ), [[0, 0, 0], [0, 1, 1], [1, 1, 1], [2, 1, 1], [3, 1, 1], [4, 0, 0]] ) ================================================ FILE: programmers/난이도별/level03.기둥과보/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/60061 기둥과 보 설치 구조물 상태를 매번 갱신 삽입 삭제시에 구조물 규칙 검사 ''' def impossible(result): COL, ROW = 0, 1 for x, y, a in result: if a == COL: # 기둥일 때 if y != 0 and (x, y - 1, COL) not in result and \ (x - 1, y, ROW) not in result and (x, y, ROW) not in result: return True else: # 보일 때 if (x, y - 1, COL) not in result and (x + 1, y - 1, COL) not in result and \ not ((x - 1, y, ROW) in result and (x + 1, y, ROW) in result): return True return False def solution(n, build_frame): result = set() for x, y, a, build in build_frame: item = (x, y, a) if build: # 추가일 때 result.add(item) if impossible(result): result.remove(item) elif item in result: # 삭제할 때 result.remove(item) if impossible(result): result.add(item) answer = map(list, result) return sorted(answer, key=lambda x: (x[0], x[1], x[2])) ''' https://velog.io/@tjdud0123/기둥과-보-설치-2020-카카오-공채-python 참고 너무 많은 if문과 30점 이하의 정확성 때문에 현타. 이렇게 푸는 것이 아니라 확신했는데, 멋지게 푸는 사람 발견. 보통 이런 문제를 풀면 전체적인 board를 만들기 마련인데, 이렇게 풀 수도 있다는 것을 알았다 ''' ================================================ FILE: programmers/난이도별/level03.기지국_설치/6047198844.py ================================================ import math def solution(n, stations, w): answer = 0 able_stations = [1] for station in stations: if able_stations[-1] > station-w-1: able_stations.pop() else: able_stations.append(station-w-1) able_stations.append(station+w+1) #마지막이 범위를 넘어선경우 if able_stations[-1] > n: able_stations.pop() else: able_stations.append(n) for idx in range(0, len(able_stations), 2): start = able_stations[idx] end = able_stations[idx+1] r = end - start + 1 answer += math.ceil(r/(2*w+1)) return answer ================================================ FILE: programmers/난이도별/level03.기지국_설치/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12979 기지국 설치 [풀이] 1. 앞쪽 station 부터 얻기 위해 reverse => reverse 하지 않으려면 deque 사용도 가능 2. 기지국의 수용 범위 stat을 정의 3. 처음 시작지점은 1 4. 시작지점에서 station의 수용 범위 전까지 필요한 기지국 개수 조사 => end - w : 기지국 수용범위 가장 처음 => end - w - start : 기지국이 필요한 아파트 수 5. 다음 시작지점은 end + w + 1 로 잡는다 => end + w 까지가 기지국 수용범위 끝 6. 마지막 station 수용범위가 아파트 끝이 아니라면 그 사이까지 조사 ''' def solution(n, stations, w): stations = stations[::-1] stat = 2 * w + 1 start = 1 answer = 0 while stations: end = stations.pop() cnt = end - w - start if cnt > 0: answer += (cnt - 1) // stat + 1 start = end + w + 1 if start <= n: answer += (n - start) // stat + 1 return answer ''' ''' ================================================ FILE: programmers/난이도별/level03.길_찾기_게임/6047198844.py ================================================ import collections import sys sys.setrecursionlimit(10**6) class Node(object): def __init__(self, data): self.data = data self.left = self.right = None def solution(nodeinfo): nodeinfo = collections.deque(sorted(list(enumerate(nodeinfo, start=1)), key=lambda node:(-node[1][1],node[1][0]))) #node data는 번호, [x,y]로 이루어진다. root = None def insert(cur, node): if cur is None: cur = node else: if cur.data[1][0] > node.data[1][0]: cur.left = insert(cur.left, node) else: cur.right = insert(cur.right, node) return cur while nodeinfo: node = nodeinfo.popleft() root = insert(root, Node(node)) preorder_list = [] def preorder(root): if root: preorder_list.append(root.data[0]) preorder(root.left) preorder(root.right) preorder(root) postorder_list = [] def postorder(root): if root: postorder(root.left) postorder(root.right) postorder_list.append(root.data[0]) postorder(root) return [preorder_list,postorder_list] ================================================ FILE: programmers/난이도별/level03.길_찾기_게임/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42892 길 찾기 게임 [풀이] 0. 이진트리 구현 및 탐색 1. 클래스로 이진트리 구현 => 여기서는 idx와 val값 두개를 가지고 있는 것이 차이점 2. 재귀 제한을 풀지 않으면 5, 6번 문제에서 런타임 에러 3. nodeinfo에서 idx값을 알 수 있도록 추가 4. 주어진 nodeinfo를 y 값에 대해 내림차순 정렬 => 깊이가 낮은 순으로 트리에 쌓이게 함 => 트리는 입력 순서에 따라 내용이 달라지기 때문에 깊이 순으로 정렬 ''' class Node: def __init__(self, val, idx): self.val = val self.idx = idx self.left = None self.right = None class Tree: def __init__(self, root): self.root = root def insert(self, val, idx): cur_node = self.root while True: if cur_node.val < val: if cur_node.right != None: cur_node = cur_node.right continue else: cur_node.right = Node(val, idx) break else: if cur_node.left != None: cur_node = cur_node.left continue else: cur_node.left = Node(val, idx) break def preorder(self, cur_node): if cur_node == None: return [] return [cur_node.idx] + self.preorder(cur_node.left) + self.preorder(cur_node.right) def postorder(self, cur_node): if cur_node == None: return [] return self.postorder(cur_node.left) + self.postorder(cur_node.right) + [cur_node.idx] def solution(nodeinfo): import sys sys.setrecursionlimit(10 ** 6) nodes = [[idx] + info for idx, info in enumerate(nodeinfo, 1)] nodes.sort(key=lambda x: x[2], reverse=True) root = Node(nodes[0][1], nodes[0][0]) tree = Tree(root) for node in nodes[1:]: tree.insert(node[1], node[0]) return [tree.preorder(root), tree.postorder(root)] ''' 클래스로 풀어보는 첫 문제. 구현이 번거롭지만 구현하고 나니 풀기는 쉬웠다. ''' ================================================ FILE: programmers/난이도별/level03.네트워크/6047198844.cpp ================================================ #include #include #include using namespace std; bool computer_node[201]; void dfs(int num,vector>& computers) { if (computer_node[num]) { return; } computer_node[num] = true; int computers_size = computers.size(); for (int i = 0; i < computers_size; i++) { if (computers[num][i]) dfs(i, computers); } return; } int solution(int n, vector> computers) { int answer = 0; for (int i = 0; i < n; i++) { if (!computer_node[i]) { dfs(i, computers); answer++; } } return answer; } int main() { cout << solution(3, { {1, 1, 0 }, { 1, 1, 1 }, { 0, 1, 1 }}); } ================================================ FILE: programmers/난이도별/level03.네트워크/JeongShin.js ================================================ function solution(n, computers) { let ans = 0; const visited = new Array(n).fill(false); const check_visited_all = () => { return !visited.find(el => !el); }; const dfs = start => { const queue = []; queue.push(start); while (queue.length) { const index = queue.pop(); const curr = computers[index]; visited[index] = true; for (let i = 0; i < n; i++) { const next = curr[i]; if (next && !visited[i]) queue.push(i); } } }; while (!check_visited_all()) { const start = visited.indexOf(false); dfs(start); ans++; } return ans; } solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]); solution(3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]); ================================================ FILE: programmers/난이도별/level03.네트워크/rockmiin_네트워크.py ================================================ from collections import deque def solution(n, computers): answer=0 visited = [0] * (n + 1) arr = [[] for i in range(n + 1)] for i in range(n): for j in range(n): if computers[i][j]==1: arr[i+1].append(j+1) # print(arr) def bfs(v): q=deque([v]) while q: k= q.popleft() if not visited[k]: visited[k]=1 for e in arr[k]: if not visited[e]: q.append(e) for i in range(1, n+1): if not visited[i]: bfs(i); answer+=1 return answer print( solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]) ) ================================================ FILE: programmers/난이도별/level03.네트워크/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/43162 네트워크 기본적인 그래프 문제이다. 방문 처리를 해놓는것이 포인트 ''' def solution(n, computers): visited = [0] * n def cal(visited, idx): if visited[idx]: return 0 visited[idx] = 1 for i in range(n): if idx == i: continue if computers[idx][i]: cal(visited, i) return 1 return sum([cal(visited, i) for i in range(n)]) ''' ''' ================================================ FILE: programmers/난이도별/level03.다단계_칫솔_판매/6047198844.py ================================================ def dfs(enroll_referral, seller, credit): if seller == "-": dict[seller] = credit + dict.get(seller, 0) return dict[seller] = dict.get(seller, 0) + credit - (credit // 10) seller = enroll_referral[seller] dfs(enroll_referral, seller, credit // 10) def solution(enroll, referral, seller, amount): answer = [] global dict dict = {} enroll_referral = {} for idx in range(len(enroll)): enroll_referral[enroll[idx]] = referral[idx] for idx in range(len(amount)): dfs(enroll_referral, seller[idx], amount[idx]*100) return [dict.get(i,0) for i in enroll] ================================================ FILE: programmers/난이도별/level03.다단계_칫솔_판매/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/77486 다단계 칫솔 판매 [풀이] 1. 딕셔너리 선언 : 판매자 : [추천인, 자신의 수익] 2. 자신이 벌어든 이익을 profit = 100 * amount 로 정의 3. 자신의 추천인이 없거나, 더이상 10%로 나눠지지 않을 때 까지 수익 분배 4. 더 이상 10%로 나눠지지 않을 때는 해당 금액을 마지막 사람이 얻는 조건을 추가 5. enroll 순서에 맞게끔 각자의 수익 반환 ''' import math def solution(enroll, referral, seller, amount): dic = {e: [r, 0] for e, r in zip(enroll, referral)} for s, a in zip(seller, amount): profit = 100 * a while s != '-' and int(profit * 0.1) != 0: mine, profit = math.ceil(profit * 0.9), math.floor(profit * 0.1) dic[s][1] += mine s = dic[s][0] if s != '-': dic[s][1] += profit return [dic[e][1] for e in enroll] ''' ''' ================================================ FILE: programmers/난이도별/level03.단속카메라/6047198844.py ================================================ def solution(routes): routes.sort(key=lambda route: route[1]) pos_camera = -30001 cnt_camera = 0 for route in routes: if pos_camera < route[0]: pos_camera = route[1] cnt_camera += 1 return cnt_camera ================================================ FILE: programmers/난이도별/level03.단속카메라/JeongShin.js ================================================ function solution(routes) { let min = -Infinity; return routes.sort((a, b) => a[1] - b[1]).reduce((ans, [start, end]) => { if (min < start) { min = end; ans++; } return ans; }, 0); } solution([[-20, 15], [-14, -5], [-18, -13], [-5, -3]]); ================================================ FILE: programmers/난이도별/level03.단속카메라/junilhwang.js ================================================ // 단속카메라 - https://programmers.co.kr/learn/courses/30/lessons/42884?language=javascript function solution(routes) { // 미해결. 포기 routes.sort((a, b) => Math.abs(a[0] - a[1]) - Math.abs(b[0] - b[1])) const stack = [], last = routes.length let cnt = 0 loop: for (let i = 0; i < last; i++) { const [start, end] = routes[i] stack.push(i) let chk = false for (let j = i + 1; j < last; j++) { if (stack.indexOf(j) !== -1) continue const chk1 = routes[j][0] <= start && start <= routes[j][1] const chk2 = routes[j][0] <= end && end <= routes[j][1] if (chk1 || chk2) { chk = true stack.push(j) if (stack.length === last) { cnt += 1 break loop } } } if (chk) cnt += 1 } return cnt } //console.log(solution([[-20, 15], [-14, -5], [-18, -13], [-5, -3]]), 2) //console.log(solution([[-20, 15], [-14, -5], [-18, -13], [-5, -3]]), 2) //console.log(solution([[-2, -1], [1, 2], [-3, 0]]), 2) console.log(solution([[-20, 15], [-20, -15], [-20, -15], [-18, -13], [-5, -3]]), 2) ================================================ FILE: programmers/난이도별/level03.단속카메라/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42884 단속카메라 [풀이] 0. O(N^2)과 O(N) 방법이 모두 통과된다. 여기서는 O(N)으로 풀이 1. 자동차의 범위는 -30000부터 30000 이므로 카메라가 존재할 수 있는 위치를 -30001로 설정 => -30001 부터 30000 까지 증가해 갈 것임 2. Routes를 진출 지점을 기준으로 오름차순으로 정렬 => 어떤 자동차가 먼저 지나갔는지에 대해 정렬한 것이다. 3. 만약 5초에 진입한 자동차가 있어서 카메라를 5초에 설치했다고 하자. 진출은 9초에 했다. => 그럼 다음과 같은 4가지 경우를 생각해 볼 수 있다. 3-1. 5초 이전에 진입 9초 이전에 진출 => 애초에 말이 안된다. 5초에 진입한 차가 가장 먼저 나간것이기 떄문(진출 기준 정렬) 3-2. 5초 이전에 진입 9초 이후에 진출 => 가능하다. 3-3. 5초 이후에 진입 9초 이전에 진출 => 이것도 말이 안된다. 3-1과 같은 이유 3-4. 5초 이후에 진입 9초 이후에 진출 => 가능하다. => 5초에 같이 진입하면 반드시 카메라에 찍히므로 배제할 수 있다. => 9초에 같이 진출하면 반드시 5초 이후에 진입해야 하므로 3-4의 경우로 볼 수 있다 4. 3-2와 3-4에 대해서 경우를 자세하게 따져보면, => 3-2는 5초에 있는 카메라에 반드시 찍힌다. => 3-4는 5초에 있는 카메라에 찍히지 못한다. => 이는 카메라의 위치보다 진입 시점이 더 뒤일 경우에 카메라가 더 필요하다는 것을 의미 5. 따라서, 카메라보다 진입시점이 늦은 자동차가 있을 경우 그 자동차의 진출시점으로 카메라를 추가 => 왜 카메라를 진입시점이 아니라 진출시점으로 하는건데? => 이 자동차가 진입하고 진출할 때 까지 다른 자동차들을 추가로 더 찍을 수도 있으니까. => 진입시점으로 하면 매 차마다 카메라를 추가해야 하니까! ''' def solution(routes): camera = -30001 answer = 0 routes.sort(key=lambda x: x[1]) for route in routes: if camera < route[0]: answer += 1 camera = route[1] return answer ''' https://wwlee94.github.io/category/algorithm/greedy/speed-enforcement-camera/ 아무리 생각해도 아이디어 구현이 잘 안돼서 위 링크 코드를 참조했다. (근데 코드가 너무 간단해서 아예 똑같음) 나는 우선순위 큐 쓰고 그랬는데 이렇게 간단한 코드라니... ''' ================================================ FILE: programmers/난이도별/level03.단어_변환/6047198844.py ================================================ import collections def is_valid(step_word, word): cnt = 0 for s_char, char in zip(step_word, word): if s_char != char: cnt += 1 if cnt > 1: return False return True def solution(begin, target, words): answer = 0 visited = set() Q = collections.deque([begin]) while Q: answer += 1 for _ in range(len(Q)): step_word = Q.popleft() for word in words: if word not in visited and is_valid(step_word, word): if word == target: return answer Q.append(word) visited.add(word) return 0 ================================================ FILE: programmers/난이도별/level03.단어_변환/JeongShin.js ================================================ function solution(begin, target, words) { const len = words.length; let ans = Infinity; // 일치하지 않는 알파벳 개수 반환 const match = (str, word_idx) => { return str.split("").reduce((acc, curr, idx) => { return acc + (words[word_idx][idx] !== curr) }, 0); }; const visited = {}; const dfs = (start) => { const {word, count} = start; if (word === target) { ans = Math.min(count, ans); return null; } visited[word] = true; for (let i = 0; i < len; i++) { if (match(word, i) === 1 && visited[words[i]] === undefined) dfs({word: words[i], count: count + 1}); } }; dfs({word: begin, count: 0}); return ans === Infinity ? 0 : ans; } solution("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]); ================================================ FILE: programmers/난이도별/level03.단어_변환/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/43163 단어 변환 : 한글자만 변경하면 같아지는 글자를 찾아 이동하면서 원하는 단어를 구할 때의 이동횟수를 구하는 문제 1) 모든 단어는 50개 이하이므로 51개와 min 비교 가능 2) 선택된 단어는 words에 제거되며 words의 크기인 length로 이동횟수 파악 가능 이 때, words는 mutable 하므로 slicing한 words를 인자로 결정 3) 매번 len을 조사하는 시간을 조금이나마 줄이고자 lenWord와 lenWords 그리고 length 사용 ''' def solution(begin, target, words): if target not in words: return 0 lenWord = len(begin) lenWords = len(words) def cal(begin, words, length): if begin == target: return lenWords - length if not length: return 51 answer = [51] for idx, word in enumerate(words): if [word[i] == begin[i] for i in range(lenWord)].count(True) == lenWord - 1: answer.append(cal(word, words[:idx] + words[idx + 1:], length - 1)) return min(answer) answer = cal(begin, words, len(words)) return answer if answer != 51 else 0 ''' 처음에는 set.intersection을 이용해서 한자리가 틀린지 확인했다. hhx =? hih 같은 단어가 True로 처리되는 걸 질문게시판에서 알았고 결국 개별 인덱스를 비교했음. ''' ================================================ FILE: programmers/난이도별/level03.등굣길/6047198844.py ================================================ def solution(m, n, puddles): #board[y][x] : (y,x)에서 이동했을때의 경우의수 board = [[-1 for _ in range(m+1)] for _ in range(n+1)] board[n][m] = 1 for x, y in puddles: board[y][x] = 0 def dp(y, x): if not (1 <= y <= n and 1 <= x <= m): return 0 if board[y][x] != -1: return board[y][x] board[y][x] = 0 board[y][x] = ((dp(y+1,x) % 1000000007) + dp(y,x+1) % 1000000007) % 1000000007 return board[y][x] dp(1, 1) return board[1][1] ================================================ FILE: programmers/난이도별/level03.등굣길/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42898 등굣길 stack 사용 ''' def solution(m, n, puddles): b = [[0] * (m + 1) for _ in range(n + 1)] for x, y in puddles: if x <= m and y <= n: b[y][x] = -1 b[1][1] = 1 for i in range(1, n + 1): for j in range(1, m + 1): if b[i][j] == -1: b[i][j] = 0 continue b[i][j] += (b[i - 1][j] + b[i][j - 1]) return b[n][m] % 1000000007 ''' 완전 별로인 문제, 당연히 위아래도 고려해야 하는 줄 알았다. 아래, 왼쪽으로만 진행할 수 있도록 비가 내리는 줄 알았으면 이렇게 고민 안했을 듯 def solution(m, n, puddles): move = [(0, 1), (0, -1), (1, 0), (-1, 0)] stack = [([(1, 0)], 1, 1, 0)] answer = [] while stack: prior, x, y, dist = stack.pop(0) if x == m and y == n: answer.append(dist) continue for a, b in move: nx = x + a ny = y + b if nx <= 0 or nx > m or ny <= 0 or ny > n: continue for _x, _y in prior: if _x == nx and _y == ny: break else: for _x, _y in puddles: if _x == nx and _y == ny: break else: prior.append((x, y)) stack.append((prior, nx, ny, dist+1)) return len(answer) % 1000000007 위 아래로 갈 수 있다는 전제를 두고 풀은 코드. 잘 풀은건 아니라 이렇게 풀어도 효율이 너무 안좋아서 걸릴 가능성은 높음. 말이 안되는 문제긴 했음. 지나온 길을 기억하지 않으면 무한 루프를 돌 가능성이 높기 때문에. ''' ================================================ FILE: programmers/난이도별/level03.디스크_컨트롤러/6047198844.py ================================================ import collections import heapq def solution(jobs): answer = 0 N = len(jobs) jobs.sort() #현재 시간 current_sec = 0 #현재 진행중인 작업(들어온시간, 소요시간) , 시작한 시간 (1개 이상) current_job = None #대기 중인 작업들 PQ = [] #대기시간의 합 / 작업 종료시에 종료시점 - 작업 입력 시점(job) waiting_time = 0 #초단위로 상황 접근. #대기중인 작업 / 현재 작업이 없을때까지. #current_job : 현재 작업의 요청시간, 현재 작업의 시작시간, 현재 작업의 종료시간 while PQ or current_job or jobs or current_sec == 0: #현재시간에 넣을수있는 job들을 PQ에 넣는다. while jobs and current_sec == jobs[0][0]: #heaq오류 조심? request_time, duration = jobs.pop(0) #소요시간 / 요청시점 heapq.heappush(PQ,(duration, request_time)) #현재작업이 있는지. 현재 작업이 종료되는지 여부판단. 현재 작업 종료 시간 == 현재 시간 if current_job and current_job[2] == current_sec: print(current_job) request_time, start_sec, end_sec = current_job waiting_time += end_sec - request_time #작업 종료 current_job = None #현재 작업이 없다면 현재 작업 설정 if not current_job and PQ: #PQ의 맨앞값을 현재 작업으로 지정. duration, request_time = heapq.heappop(PQ) #현재 작업 설정 (요청시간, 시작한 시간, 종료시간) current_job = (request_time, current_sec, current_sec + duration) #1초 증가 current_sec += 1 return waiting_time // N ================================================ FILE: programmers/난이도별/level03.디스크_컨트롤러/JeongShin.js ================================================ function solution(jobs) { let currTime = 0 const queue = [...jobs] const result = [] let len = queue.length // 도착한 순서대로 정렬하고 같은 시간에 도착 했을시 빨리 끝나는 순서대로 정렬 queue.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]) queue.pop = () => { /* 현재 시각내에 할 수 있는 job이 없다면 가장 빠른거 다시 수행 */ if (currTime < queue[0][0]) return queue.shift() /* 현재 시각내에 할 수 있는 job 중 가장 빨리 끝나는 job 을 linear search */ let i = 0, minIdx = 0; while (i < queue.length && queue[i][0] <= currTime) { minIdx = queue[i][1] < queue[minIdx][1] ? i : minIdx i++ } return queue.splice(minIdx, 1).pop(); } while (queue.length) { const [arrTime, serTime] = queue.pop(); currTime = Math.max(arrTime, currTime); result.push(serTime + currTime - arrTime); currTime+=serTime; } return Math.floor(result.reduce((acc, curr) => acc + curr, 0) / len) } console.log(solution([[0, 3], [1, 9], [2, 6]])) ================================================ FILE: programmers/난이도별/level03.디스크_컨트롤러/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42627?language=javascript function solution(jobs) { jobs.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]) let total = jobs.length, job = jobs.shift(), t = job[0], sum = 0 const q = [] while (true) { while (jobs.length && t >= jobs[0][0]) { q.push(jobs.shift()) if (q.length > 1) q.sort((a, b) => a[1] - b[1]) } if (q[0] && !job && q[0][0] <= t) job = q.shift() if (job) { sum += (t += job[1]) - job[0] job = null if (jobs.length + q.length === 0) break } else t += 1 } return ~~(sum / total) } console.log(solution([[0, 3], [10, 10]]), 6) console.log(solution([[0, 3], [1, 9], [2, 6], [4, 3]]), 9) console.log(solution([[24, 10], [18, 39], [34, 20], [37, 5], [47, 22], [20, 47], [15, 2], [15, 34], [35, 43], [26, 1]]), 74) console.log(solution([[0, 9], [0, 4], [0, 5], [0, 7], [0, 3]]), 13) console.log(solution([[15,34], [15,2]]), 19) console.log(solution([[0, 5], [1, 2], [5, 5]]), 6) console.log(solution([[0, 3], [1, 9], [2, 6]]), 9) console.log(solution([[10, 6], [12, 6], [14, 4]]), 8) ================================================ FILE: programmers/난이도별/level03.디스크_컨트롤러/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42627 디스크 컨트롤러 [풀이] 1. 요청이 먼저 왔어도 수행시간이 짧은 것을 택해야 하기 때문에 우선순위 큐 사용 2. 각 요청별 걸린 시간을 result에 담아서 sum(result)를 반환 => 따라서 while문은 len(result)가 총 요청의 개수와 같을 때 까지 작동 3. 대기열이 있다면 가장 최근 요청이 걸리는 시간을 time에 더해준다 4. 대기열이 없다면 jobs에서 제일 먼저 실행되는 요청이 시작되는 시간을 time으로 설정 ''' from queue import PriorityQueue def solution(jobs): size = len(jobs) jobs.sort(reverse=True) waiting = PriorityQueue() time = 0 result = [] while len(result) < size: while jobs and jobs[-1][0] <= time: req, spend = jobs.pop() waiting.put((spend, req)) if not waiting.empty(): spend, req = waiting.get() time += spend result.append(time - req) else: time = jobs[-1][0] return sum(result) // size ''' ''' ================================================ FILE: programmers/난이도별/level03.매칭_점수/6047198844.py ================================================ import re import collections def solution(word, pages): answer = 0 #전처리 word = word.lower() pages = [page.lower() for page in pages] page_urls = [] page_basic_score = collections.defaultdict(int) page_linked = collections.defaultdict(list) page_linking_num = collections.defaultdict(int) page_matching_score = [] for idx, page in enumerate(pages): #해당 페이지 url p = re.compile(".*", re.I|re.S) m = p.search(page) p = re.compile("", re.I|re.S) m = p.search(m.group()) p = re.compile("\"https://.*\"", re.I) m = p.search(m.group()) cur_page_url = m.group()[1:-1] page_urls.append(cur_page_url) #해당 페이지 기본 점수 p = re.compile('[^a-z^A-Z]'+word+'[^a-z^A-Z]', re.I|re.S) m = p.findall(page) page_basic_score[cur_page_url] = len(m) #해당 페이지 참조 링크 p = re.compile("\"https://.*\"", re.I) m = p.findall(page) page_linking_num[cur_page_url] = len(m)-1 for link in m: if link[1:-1] != cur_page_url: page_linked[link[1:-1]].append(cur_page_url) for page_url in page_urls: matching_score = page_basic_score[page_url] for page_linking in page_linked[page_url]: matching_score += page_basic_score[page_linking] / page_linking_num[page_linking] page_matching_score.append(matching_score) print(page_matching_score.index(max(page_matching_score))) return page_matching_score.index(max(page_matching_score)) ''' 검색어에 가장 잘 맞는 웹페이지를 보여주기 위해 아래와 같은 규칙으로 검색어에 대한 웹페이지의 매칭점수를 계산 - 한 웹페이지에 대해서 기본점수, 외부 링크 수, 링크점수, 그리고 매칭점수를 구할 수 있다. - 한 웹페이지의 기본점수는 해당 웹페이지의 텍스트 중, 검색어가 등장하는 횟수이다. (대소문자 무시) - 한 웹페이지의 링크점수는 (해당 웹페이지로 링크가 걸린 다른 웹페이지의 기본점수 ÷ 외부 링크 수)의 총합이다. - 한 웹페이지의 외부 링크 수는 해당 웹페이지에서 다른 외부 페이지로 연결된 링크의 개수이다. - 한 웹페이지의 매칭점수는 기본점수와 링크점수의 합으로 계산한다. http://zeany.net/46 ''' ================================================ FILE: programmers/난이도별/level03.멀리뛰기/JeongShin.js ================================================ function solution(n) { const result = {'1': 1, '2': 2} for (let i = 3; i <= n; i++) { result[i] = (result[i - 1] + result [i -2] ) %1234567 } return result[n] } solution(4) ================================================ FILE: programmers/난이도별/level03.멀리뛰기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12914 멀리 뛰기 [풀이] 1. 이제는 너무 익숙한 파보나치 수열 2. 개별 시행에서 각 위치는 한 칸 전과 두 칸 전에서밖에 도달하지 못한다. => 따라서, 각 위치의 경우의 수는 한 칸 전과 두 칸 전에서의 경우의 수의 합이다. ''' def solution(n): dp = [1, 1] + [0] * (n-1) for i in range(2, n+1): dp[i] += (dp[i-2] + dp[i-1]) % 1234567 return dp[n] ''' 리스트를 안쓰고도 풀 수 있는 방법이 있다. => 이 방법이 더 좋은 방법 => 왜? 메모리 공간을 변수 두개밖에 사용하지 않았기 때문 => 어차피 알아야 할 것은 가장 끝 자리 => 전자는, 모든 경우의 수를 다 알야아 할 때 더 유용 파이썬의 장점 중 하나. 동시 대입! => tmp를 따로 할당할 필요가 없다는 것 def solution(n): a, b = 1, 1 for i in range(2, n+1): a, b = b, (a+b) % 1234567 return b ''' ================================================ FILE: programmers/난이도별/level03.모두_0으로_만들기/6047198844.py ================================================ import collections import sys sys.setrecursionlimit(10 ** 6) def solution(a, edges): if sum(a) != 0: return -1 #global answer answer = 0 graph = collections.defaultdict(list) visited = set() for i,j in edges: graph[i].append(j) graph[j].append(i) def dfs(vertex): visited.add(vertex) W = 0 for neigh in graph[vertex]: if neigh not in visited: W += dfs(neigh) #W는 위에서 올라온것. 즉 이동이 이루어진것이다. nonlocal answer W += a[vertex] answer = answer + abs(W) return W return answer if dfs(0) == 0 else -1 ''' for v in range(len(a)): Q = [v] level = -1 while Q and a[v] < 0: level += 1 for _ in range(len(Q)): neigh = Q.pop(0) if neigh != v and a[neigh] > 0: if a[neigh] >= -a[v]: a[neigh] += a[v] answer += -a[v] * level a[v] = 0 break else: a[v] += a[neigh] answer += a[neigh] * level a[neigh] = 0 for nv in graph[neigh]: Q.append(nv) if a[v] != 0: return -1 return answer ''' ================================================ FILE: programmers/난이도별/level03.모두_0으로_만들기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/76503 모두 0으로 만들기 [풀이] 1. 각 노드끼리의 관계를 명시할 dictionary를 선언 2. bfs로 트리의 순서를 결정한다. => stack에서 pop된 원소는 자신과 연결되어있는 노드를 stack에 넣고 자신은 save에 넣는다. => 이 과정은 트리의 깊이순으로 save에 저장되는 과정이다. => 0번 인덱스를 이 트리의 노드로 간주했다. => 이 때, 담기는 구조는 [자신의 번호, 부모의 번호] 이다. 3. save에 담긴 노드들의 순서는 트리의 깊이가 가장 깊은 노드들부터 담겨있다.(pop 기준) => 따라서 이 노드들의 parent에게 자신의 가중치를 모두 전해준다. => 최종적으로 0번 루트 노드가 0을 가지면 가중치가 모두 상쇄된 것이고, 가지지 못하면 되지 못한것. ''' from collections import defaultdict, deque def solution(a, edges): size = len(a) dic = defaultdict(list) for st, ed in edges: dic[st].append(ed) dic[ed].append(st) answer = 0 stack = deque([[0, None]]) save = [] while stack: idx, parent = stack.popleft() save.append([idx, parent]) for value in dic[idx]: if value != parent: stack.append([value, idx]) while len(save) > 1: idx, parent = save.pop() a[parent] += a[idx] answer += abs(a[idx]) return answer if a[0] == 0 else -1 ''' 처음에는 시간 초과를 해결할 수 없어서 결국 다른 풀이를 봤다. https://velog.io/@ckstn0778/프로그래머스-76503번-가사-검색-O-1-Python 대부분의 풀이가 위 링크의 풀이와 대부분 비슷하다. 아마 내 풀이가 이 문제에 대해 블로그로 작성된 유일한 풀이가 아닐까? 저 풀이를 보면서 맘에 들지 않은 이유는, 실제 테스트에서 import sys sys.setrecursionlimit(1000000) 이 부분을 모르면 어쨋든 해결하지 못하고, 이 부분은 python에서만 활용할 수 있기 때문이다. 단순히 js에서 combination 함수를 제공하는 라이브러리가 있고 없고의 문제가 아니다. => combination은 반복문으로 구현할 수 있지만 재귀깊이를 늘리는 것을 구현할 수 있는가? 그래서, 각 노드의 순서를 정의할 필요가 있었고 위와 같이 풀게 되었다. ''' ================================================ FILE: programmers/난이도별/level03.방문_길이/JeongShin.js ================================================ class player { constructor(x, y) { this.x = x; this.y = y; this.visited = {}; this.count = 0; } currPos() { return this.x + ',' + this.y; } getNewPos(dir) { switch (dir) { case 'U': this.y++; break; case 'D': this.y--; break; case 'L': this.x--; break; case 'R': this.x++; } } move(dir) { const currPos = this.currPos(); this.getNewPos(dir); this.checkOutOfBound(); const nextPos = this.currPos(); if (currPos === nextPos) return; const move = currPos + 'to' + nextPos; if (!this.visited[move]) { this.visited[move] = true; this.visited[nextPos + 'to' + currPos] = true; this.count++; } } checkOutOfBound() { const {x, y} = this; this.x -= (Math.sign(x) * (Math.abs(x) > 5)) this.y -= (Math.sign(y) * (Math.abs(y) > 5)) } } function solution(dirs) { const p = new player(0, 0); for (const dir of dirs) p.move(dir); return p.count; } ================================================ FILE: programmers/난이도별/level03.방문_길이/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/49994 방문 길이 dictionary, set 사용 ''' def solution(dirs): move = {'U': [-1, 0], 'D': [1, 0], 'L': [0, -1], 'R': [0, 1]} x = y = 0 answer = set() for i in dirs: dx = x + move[i][0] dy = y + move[i][1] if dx < -5 or dx > 5 or dy < -5 or dy > 5: continue answer.add((x, y, dx, dy)) answer.add((dx, dy, x, y)) x = dx y = dy return len(answer) // 2 ''' ''' ================================================ FILE: programmers/난이도별/level03.배달/sangmandu.py ================================================ ''' https://school.programmers.co.kr/courses/11117/lessons/71020 배달 기본적인 그래프 문제. ''' from queue import PriorityQueue def solution(N, road, K): pq = PriorityQueue() pq.put([1, 0]) dist = [500001] * (N + 1) dist[1] = 0 while not pq.empty(): current, current_cost = pq.get() for src, dest, cost in road: next_cost = cost + current_cost if src == current and next_cost < dist[dest]: dist[dest] = next_cost pq.put([dest, next_cost]) elif dest == current and next_cost < dist[src]: dist[src] = next_cost pq.put([src, next_cost]) return len([x for x in dist if x <= K]) ''' ''' ================================================ FILE: programmers/난이도별/level03.베스트앨범/6047198844.py ================================================ import collections def solution(genres, plays): answer = [] table = collections.defaultdict(list) for idx, (genre, play) in enumerate(zip(genres, plays)): table[genre].append((int(play), int(idx))) stable = sorted(table.items(), key=lambda x: sum([y[0] for y in x[1]]), reverse=True) for type in stable: for v in sorted(type[1], key=lambda x: (x[0], -x[1]), reverse=True)[:2]: answer.append(v[1]) # 같으면 낮은 순으로! 즉 reverse되면 높은순이된다. return answer ================================================ FILE: programmers/난이도별/level03.베스트앨범/JeongShin.js ================================================ function solution(genres, plays) { const [album, genre] = plays.reduce(([alb, gen], curr, idx) => { const genre = genres[idx]; alb[genre] = alb[genre] || []; alb[genre].push([idx, curr]); gen[genre] = (gen[genre] || 0) + curr; return [alb, gen]; }, [{}, {}]); const sortedGenre = []; sortedGenre.push(...Object.entries(genre)); sortedGenre.sort((a, b) => b[1] - a[1]); return sortedGenre.reduce((answer, curr) => { const genre = curr[0]; const sortedAlbum = album[genre]; sortedAlbum.sort((a, b) => a[1] === b[1] ? b[0] - a[0] : a[1] - b[1]); let count = 0; while (sortedAlbum.length && count < 2) { const idx = sortedAlbum.pop()[0]; answer.push(idx); count++; } return answer; }, []) } // 기대 값 : [4,1,3,0] const r = solution(["classic", "pop", "classic", "classic", "pop"], [800, 600, 800, 800, 2500]) console.log(r); ================================================ FILE: programmers/난이도별/level03.베스트앨범/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42579 베스트앨범 딕셔너리로 해시 기능 이용. 수가 많은 장르와 각 장르별 순위를 매기기 위해 두 가지 딕셔너리 사용 ''' def solution(genres, plays): rank, chart = {}, {} for idx, val in enumerate(zip(genres, plays)): a, b = val rank.setdefault(a, 0) rank[a] += b chart.setdefault(a, []) chart[a].append((idx, b)) best = sorted(rank.items(), key=lambda x : x[1], reverse=True) answer = [] for i in best: answer.extend(sorted(chart[i[0]], key=lambda x : (-x[1], x[0]))[:2]) return [a[0] for a in answer] ''' ''' ================================================ FILE: programmers/난이도별/level03.보석_쇼핑/6047198844.py ================================================ import collections def solution(gems): target_num = len(set(gems)) table = collections.defaultdict(int) cnt = 0 begin = 0 answer = [0, 100001] for end, gem in enumerate(gems): #end값을 table에 추가한다. table[gem] += 1 #추가한값이 새로운 값이라면, cnt를 증가시킨다. if table[gem] == 1: cnt += 1 #맨 앞에 있는 값이 두개 이상의 값을 가지고 있다면 begin을 증가시켜 윈도우를 줄인다 #물론 윈도우를 줄이면서 해당 값을 감소시킨다 while table[gems[begin]] >= 2: table[gems[begin]] -= 1 begin += 1 if cnt == target_num and end - begin < answer[1] - answer[0]: answer = [begin + 1, end + 1] return answer ================================================ FILE: programmers/난이도별/level03.보석_쇼핑/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/67258 보석 쇼핑 [풀이] 1. 난이도가 좀 있는 문제. 투 포인터를 사용할 것이라 예상까지는 했는데 풀이에 시간이 꽤 걸렸다. => 코드 자체가 어려운 편은 아니고, 방법을 생각하는 것이 어려움 2. 투 포인터 st, ed를 0으로 선언. 답으로 제출할 ast(answer st)와 aed(answer ed)는 전체 크기로 설정 3. dictionary cnt를 선언. => 첫번째 보석을 담고 있다. (st,가 0이기 때문) 4. 기본적인 작동원리 : 전체 보석 개수가 필요한 보석 개수보다 많으면 => st += 1 적으면 => ed += 1 5. ed - st값에 따라 ast와 aed를 갱신한다. => 이 때, ed - st < aed - ast 에서 부등호가 <= 가 아니라 < 여야 한다. => "만약 가장 짧은 구간이 여러 개라면 시작 진열대 번호가 가장 작은 구간을 return 합니다." 조건을 만족하기 위해서 6. 최종으로 구한 ast, aed에 +1 을 해서 반환 ''' def solution(gems): st = ed = 0 ast, aed = 0, len(gems) - 1 cnt = {gems[0]: 1} kinds = len(set(gems)) while st < len(gems) and ed < len(gems): if len(cnt) == kinds: if ed - st < aed - ast: ast, aed = st, ed cnt[gems[st]] -= 1 if cnt[gems[st]] == 0: del cnt[gems[st]] st += 1 else: ed += 1 if ed == len(gems): break cnt[gems[ed]] = cnt.get(gems[ed], 0) + 1 return [ast + 1, aed + 1] ''' 보통 dictionary를 선언하는 이유는 특정 key에 대한 value를 찾을 때 O(1)의 시간이 들기 때문. 이 value값의 유무를 조사하기 위해 처음에는 list(cnt.values()).count() 를 사용했다. 이 부분이 시간이 많이 걸렸는데. del을 사용해서 값의 유무를 판단했고 시간을 줄였다. 왜냐하면 보석이 몇 개 인지가 중요한 것이 아니라 1개 이상인지 0개인지가 판단 근거이기 때문. ''' ================================================ FILE: programmers/난이도별/level03.불량_사용자/6047198844.py ================================================ import re import collections #경우의 수만 계산하면됨. limited_ids = set() def dfs(idx, matched, banned_ids,res): if idx == len(banned_ids): limited_ids.add(''.join(sorted(list(res)))) return for user_id in matched[banned_ids[idx]]: if user_id not in res: res.add(user_id) dfs(idx+1,matched, banned_ids,res) res.remove(user_id) return def solution(user_ids, banned_ids): answer = 0 matched = collections.defaultdict(set) banned_ids = list(map(lambda banned_id: banned_id.replace('*','.'), banned_ids)) #banned_id에 맞는 user_id를 배분. for banned_id in banned_ids: cnt = 0 for user_id in user_ids: if len(banned_id) == len(user_id) and re.search(banned_id, user_id): matched[banned_id].add(user_id) dfs(0, matched, banned_ids, set()) return len(limited_ids) ================================================ FILE: programmers/난이도별/level03.불량_사용자/JeongShin.java ================================================ package programmers.난이도별.level03.불량_사용자; import java.util.regex.*; import java.util.stream.*; import java.util.*; class Solution1 { private boolean[] visited; private HashSet set; private int target; private List> possible_id; public List cloneList(List original, String str) { List cloned_list = new ArrayList(original); cloned_list.add(str); return cloned_list; } public String getRegex(String banned_id) { return "^" + banned_id.replaceAll("\\*", ".") + "$"; } public void checkPossibleAnswer(List list) { set.add(list.stream().sorted().collect(Collectors.joining(""))); } public int solution(String[] user_id, String[] banned_id) { possible_id = Arrays.stream(banned_id).map(b_id -> { String REGEX = getRegex(b_id); return Arrays.stream(user_id).filter(u_id -> Pattern.matches(REGEX, u_id)).collect(Collectors.toList()); }).collect(Collectors.toList()); target = banned_id.length; visited = new boolean[target]; set = new HashSet<>(); dfs(0, new ArrayList()); return set.size(); } public void dfs(int idx, List list) { if (idx == target) { checkPossibleAnswer(list); return; } for (String str : possible_id.get(idx)) { if (list.indexOf(str) == -1) dfs(idx + 1, cloneList(list, str)); } } } // https://leveloper.tistory.com/152 풀이 참고 class Solution2 { private String[] u_id; private String[] b_id; private int len; private int target; private boolean[] visited; private HashSet> resultSet; public int solution(String[] user_id, String[] banned_id) { u_id = user_id; visited = new boolean[user_id.length]; resultSet = new HashSet<>(); b_id = Arrays.stream(banned_id).map(v -> "^" + v.replace("*", ".") + "$").toArray(String[]::new); target = b_id.length; len = user_id.length; dfs(0, new HashSet<>()); return resultSet.size(); } private void dfs(int index, HashSet set) { if (index == target) { resultSet.add(set); return; } for (int i = 0; i < len; i++) { if (Pattern.matches(b_id[index], u_id[i]) && !visited[i]) { visited[i] = true; set.add(i); dfs(index + 1, new HashSet<>(set)); visited[i] = false; set.remove(i); } } } } ================================================ FILE: programmers/난이도별/level03.불량_사용자/JeongShin.js ================================================ function solution(user_id, banned_id) { const possible_id = []; for (const s of banned_id) { const regEx = '^' + s.replace(/\*/g, ".") + '$'; possible_id.push(user_id.reduce((arr, str) => { const r = str.match(regEx); if (r) arr.push(r.input); return arr; }, []) ); } const answer = new Set(); const checkPossibleAnswer = (stack) => answer.add(stack.sort().join('')); const len = banned_id.length; const combination = (stack, idx) => { if (idx === len) { checkPossibleAnswer(stack); return; } possible_id[idx].forEach((str) => { if (!~stack.indexOf(str)) { combination([...stack, str], idx + 1); } }) } combination([], 0); return answer.size; } solution(["frodo", "fradi", "crodo", "abc123", "frodoc"], ["fr*d*", "*rodo", "******", "******"]); ================================================ FILE: programmers/난이도별/level03.불량_사용자/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/64604 불량 사용자 [풀이] 1. 문자열 문제는 항상 re가 최고다. 시간 단축과 구현 편의에 필수 => 정규 표현식으로 불량 사용자에 해당아는 유저 아이디를 검출한다 2. 각 불량사용자마다 얻은 유저들의 아이디를 result에 모은다 3. result에있는 아이디로 구성할 수 있는 조합을 만든다. => 이 때 중복순열인 product를 사용한다. => 이를 사용하지 않으려면 while문과 리스트 연산을 해야하는데 이게 피곤하다 4. 만들어진 조합을 가지고 조건을 추려서 결과를 얻는다 => 이 조건은 코드 아래에 다시 명시하겠음 ''' import re from itertools import product def solution(user_id, banned_id): result = [] for ban in banned_id: ban = ban.replace('*', '.') banned = [user for user in user_id if re.fullmatch(ban, user)] result.append(banned) answer = set([tuple(sorted(set(i))) for i in product(*result) if len(set(i)) == len(banned_id)]) return len(answer) ''' 다음은 prodcut(*result)가 변환하는 과정. 입력값 〉 ["frodo", "fradi", "crodo", "abc123", "frodoc"], ["*rodo", "*rodo", "******"] 기댓값 〉 2 # 모든 경우의 수를 구한다 print([i for i in product(*result)]) [('frodo', 'frodo', 'abc123'), ('frodo', 'frodo', 'frodoc'), ('frodo', 'crodo', 'abc123'), ('frodo', 'crodo', 'frodoc'), ('crodo', 'frodo', 'abc123'), ('crodo', 'frodo', 'frodoc'), ('crodo', 'crodo', 'abc123'), ('crodo', 'crodo', 'frodoc')] # 중복되는 경우의 수를 제거한다 print([set(i) for i in product(*result)]) [{'abc123', 'frodo'}, {'frodo', 'frodoc'}, {'abc123', 'crodo', 'frodo'}, {'crodo', 'frodo', 'frodoc'}, {'abc123', 'crodo', 'frodo'}, {'crodo', 'frodo', 'frodoc'}, {'abc123', 'crodo'}, {'crodo', 'frodoc'}] # 문제 조건에 "불량 사용자 아이디 하나는 응모자 아이디 중 하나에 해당하고 같은 응모자 아이디가 중복해서 제재 아이디 목록에 들어가는 경우는 없습니다." 라는 조건이 있다. # 따라서, 불량 아이디는 무조건 하나의 아이디와 대응되기 때문에 불량 아이디의 개수와 경우의 수의 개수가 동일해야 한다. # 그리고 여기서 이 if문을 미리 해야한다. 다음에 나오는 sorted() 이후에 조건이 달리면 시간초과가 뜬다. => 테스트케이스 5 print([set(i) for i in product(*result) if len(set(i)) == len(banned_id)]) [{'abc123', 'crodo', 'frodo'}, {'crodo', 'frodo', 'frodoc'}, {'abc123', 'crodo', 'frodo'}, {'crodo', 'frodo', 'frodoc'}] # [a, b, c] 와 [b, a, c] 를 중복으로 판단하기 위해 정렬을 한다 print([sorted(set(i)) for i in product(*result) if len(set(i)) == len(banned_id)]) [['abc123', 'crodo', 'frodo'], ['crodo', 'frodo', 'frodoc'], ['abc123', 'crodo', 'frodo'], ['crodo', 'frodo', 'frodoc']] # set이 중복을 제거할 수 있는 타입은 '문자', '숫자' 그리고 '튜플' 뿐이다. # sorted() 된 대상은 리스트이다. # 따라서, tuple 형태로 변환한다. print([tuple(sorted(set(i)) for i in product(*result) if len(set(i)) == len(banned_id))]) [(['abc123', 'crodo', 'frodo'], ['crodo', 'frodo', 'frodoc'], ['abc123', 'crodo', 'frodo'], ['crodo', 'frodo', 'frodoc'])] # 이후 set()을 이용해 중복을 제거한다. print(set([tuple(sorted(set(i))) for i in product(*result) if len(set(i)) == len(banned_id)])) {('crodo', 'frodo', 'frodoc'), ('abc123', 'crodo', 'frodo')} ''' ================================================ FILE: programmers/난이도별/level03.블록_이동하기/6047198844.py ================================================ import collections def solution(board): answer = 0 #y, x #초기 상태 / 검사 필요 X 한변이 최소 5이므로. Q = collections.deque([((0, 0),(0, 0 + 1))]) discovered = set() discovered.add(((0, 0),(0, 0 + 1))) N = len(board) - 1 def is_valid(pos): y, x = pos return 0 <= y <= N and 0 <= x <= N and board[y][x] == 0 def move(npos1,npos2): if is_valid(npos1) and is_valid(npos2) and (npos1,npos2) not in discovered: Q.append((npos1,npos2)) discovered.add((npos1,npos2)) def is_answer(pos1,pos2): return pos1 == (N,N) or pos2 == (N,N) while Q: #이동 시작 answer += 1 for _ in range(len(Q)): #왼쪽, 오른쪽 #위쪽, 아래쪽 pos1, pos2 = Q.popleft() if is_answer(pos1,pos2): return answer - 1 y1, x1 = pos1 y2, x2 = pos2 #이동 #상하좌우로 움직인다. for dy, dx in (-1,0), (+1,0), (0,-1), (0,+1): npos1, npos2 = (y1 + dy, x1 + dx), (y2 + dy, x2 + dx) # 유효한 경우 이동한다. move(npos1,npos2) #회전한다. #가로형일때 #y1, x1은 pos1 #y2, x2는 pos2을 뜻한다. if y1 == y2: # a b # pos1 pos2 # c d a = (y1-1,x1) b = (y2-1,x2) c = (y1+1,x1) d = (y2+1,x2) #왼쪽축을 기준으로 돌린다. #반시계로 if is_valid(b): move(a,pos1) #시계로 if is_valid(d): move(pos1,c) #오른쪽을 기준으로 돌린다. #시계로 if is_valid(a): move(b,pos2) #반시계로 if is_valid(c): move(pos2,d) #세로형일때 else: # #a pos1 b #c pos2 d a = (y1,x1-1) b = (y1,x1+1) c = (y2,x2-1) d = (y2,x2+1) #위축을 기준으로 돌린다. #반시계로 if is_valid(c): move(a,pos1) #시계로 if is_valid(d): move(pos1,b) #아래축을 기준으로 돌린다. #반시계로 if is_valid(a): move(c,pos2) #시계로 if is_valid(b): move(pos2,d) #모든 경우가 반드시 도착하는 경우가 있으므로 여기 도달할리는 없음. return -1 ================================================ FILE: programmers/난이도별/level03.블록_이동하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/60063 블록 이동하기 stack, save를 이용한 BFS visited를 두 좌표에 적용해서 동시에 방문했을 경우 reject 같은 좌표축에 있을 경우는 회전이 불가 ''' from collections import deque def solution(board): move = [(0, 1), (0, -1), (1, 0), (-1, 0)] size = len(board) visited = set() stack = deque() stack.append((0, 0, 0, 1, 0)) save = deque() visited.add(((0, 0), (0, 1))) while True: if not stack: stack, save = save, stack lx, ly, rx, ry, dist = stack.popleft() if rx == ry == size - 1 or lx == ly == size - 1: return dist for x, y in move: nlx = lx + x nly = ly + y nrx = rx + x nry = ry + y if ((nlx, nly), (nrx, nry)) in visited: continue if nlx < 0 or nlx >= size or nly < 0 or nly >= size: continue if nrx < 0 or nrx >= size or nry < 0 or nry >= size: continue if board[nlx][nly] == 1 or board[nrx][nry] == 1: continue save.append((nlx, nly, nrx, nry, dist + 1)) visited.add(((lx, ly), (rx, ry))) visited.add(((rx, ry), (lx, ly))) if (x != 0 and lx == rx) or (y != 0 and ly == ry): if ((lx, ly), (nlx, nly)) not in visited: save.append((lx, ly, nlx, nly, dist + 1)) visited.add(((lx, ly), (nlx, nly))) visited.add(((nlx, nly), (lx, ly))) if ((nrx, nry), (rx, ry)) not in visited: save.append((nrx, nry, rx, ry, dist + 1)) visited.add(((nrx, nry), (rx, ry))) visited.add(((rx, ry), (nrx, nry))) ''' 시간초과가 발생해서 2주는 걸린 문제. stack에 추가할 때 visited를 바로 갱신해야 중복 케이스가 생기지 않는 것을 알게 되었다. ''' ================================================ FILE: programmers/난이도별/level03.섬_연결하기/6047198844.py ================================================ #최소 스패닝 트리 #연결할 수 없는 섬은 주어지지 않습니다. import heapq from collections import defaultdict def solution(n, costs): answer = 0 graph = defaultdict(list) for i, j, k in costs: graph[i].append((k, j)) graph[j].append((k, i)) #prim 알고리즘 #선택된 정점. 시작정점 0 selected = set([0]) edges = [] for k, j in graph[0]: heapq.heappush(edges,(k,j)) while edges: cost, i = heapq.heappop(edges) if i not in selected: selected.add(i) for k, j in graph[i]: heapq.heappush(edges,(k,j)) answer += cost return answer ================================================ FILE: programmers/난이도별/level03.섬_연결하기/JeongShin.js ================================================ function solution(n, costs) { // set 은 각 노드별로 자신의 부모를 가르킵니다. 음수는 부모가 자기 자신임을 의미하고 중치는 자식의 개수를 의미 합니다. const set = new Set(); // 그리디 알고리즘을 사용하기 위해 weight 순으로 정렬 (이후에 pop 을 사용 하기 때문에 내림차순 정렬) const sorted_costs = costs.sort((a, b) => (b[2] - a[2])); const find = child => { let parent = child; while (set[parent] >= 0) { parent = set[parent] } return parent; }; const union = (p1, p2) => { if (p1 === p2) return; const [parent, child] = [set[p1] < set[p2] ? p1 : p2, set[p1] < set[p2] ? p2 : p1]; set[parent] = set[p1] + set[p2]; set[child] = parent; }; // Array 를 이용해도 되지만 node 의 index 가 0,1,2 ... 순차적으로 오는게 아닐 경우 Set 이 적합하다 생각합니다. sorted_costs.forEach(el => { set[el[0]] = -1; set[el[1]] = -1; }); let ans = 0; /* Union - Find */ while (sorted_costs.length) { const [node1, node2, weight] = sorted_costs.pop(); union(...[node1, node2].map(find)); // Add weight to answer ans += weight; } return ans; } solution(5, [[0, 1, 1], [2, 3, 1], [3, 4, 2], [1, 2, 2], [0, 4, 100]]); ================================================ FILE: programmers/난이도별/level03.섬_연결하기/junilhwang.js ================================================ // 탐욕법 > 섬 연결하기 : https://programmers.co.kr/learn/courses/30/lessons/42861?language=javascript function solution(n, costs) { costs.sort((a, b) => a[2] - b[2]) let min = 0, cnt = 0 const node = [...Array(n).keys()] const chk = ([x, y]) => { if (node[x] === node[y]) return false const [small, big] = node[x] < node[y] ? [node[x], node[y]] : [node[y], node[x]] node.forEach((v, k) => { if ( v === big ) node[k] = small }) return true } for (const [x, y, t] of costs) { if (!chk([x, y])) continue min += t, cnt += 1 if (cnt === n) break } return min } // console.log(solution(4, [[0, 1, 1], [0, 2, 2], [1, 2, 5], [1, 3, 1], [2, 3, 8]]), 4) // console.log(solution(5, [[0, 1, 1], [0, 2, 2], [1, 3, 2], [3, 4, 1]]), 6) // console.log(solution(6, [[0, 1, 1], [0, 2, 2], [1, 3, 2], [3, 4, 1], [3, 5, 1], [4, 5, 2]]), 7) // console.log(solution(5, [[0,1,1],[0,2,2],[0,3,1],[1,4,1],[1,2,2],[3,4,1]]), 5) // console.log(solution(6, [[0, 1, 1], [0, 5, 2], [1, 2, 1], [1, 3, 1], [1, 4, 1], [2, 5, 1]]), 5) // console.log(solution(6, [[0, 1, 5], [0, 3, 2], [0, 4, 3], [1, 4, 1], [3, 4, 10], [1, 2, 2], [2, 5, 3], [4, 5, 4]]), 11) console.log(solution(7, [[0, 1, 29], [1, 2, 16], [2, 3, 12], [3, 4, 22], [4, 5, 27], [5, 0, 10], [6, 1, 15], [6, 3, 18], [6, 4, 25]]), 10 + 27 + 22 + 15 + 12 + 16) ================================================ FILE: programmers/난이도별/level03.섬_연결하기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42861 섬 연결하기 [풀이] 1. 크루스칼 알고리즘 사용 : https://it-garden.tistory.com/411 => 최단 거리를 구하는 것이므로 cost가 작은 것부터 하나씩 선택 => 만약 cycle이 된다면 거른다! => cycle이 아니라면 계속 선택 => 언제까지? 점이 n개니까 간선은 n-1개이므로 이 때 까지 2. 초기에 각 점에 대한 소속 그룹은 자신으로 둔다. => 이후 각 간선에 대해 소속 그룹을 갱신한다. => 그리고 while문을 통해 각 점에 대한 소속 그룹을 탐색할 수 있도록 한다. => 보통은 함수로 많이 정의하는 것 같다. (간단한데도 불과하고?) 3. 소속 그룹이 같으면 cycle 이므로 pass 그렇지 않으면 cost 더해주기 ''' def solution(n, costs): costs.sort(key=lambda x: x[2], reverse=True) edge_amount = 0 parent = list(range(n)) answer = 0 while edge_amount < n - 1: st, ed, cost = costs.pop() pst, ped = st, ed while parent[pst] != pst: pst = parent[pst] while parent[ped] != ped: ped = parent[ped] if pst == ped: continue edge_amount += 1 parent[ped] = pst answer += cost return answer ''' level3 들어서는 한시간 반씩은 푸는 것 같다...ㅠ 크루스칼 알고리즘. 간혹가다가 나오는 알고리즘. 그래프 문제를 탐욕법으로 풀 때 주로 등장하는 것 같다. 예전에도 한 번 크루스칼로 풀어봤는데, 까먹었다. union-find 방식을 잘 기억해둘 것. ''' ================================================ FILE: programmers/난이도별/level03.순위/6047198844.py ================================================ from collections import defaultdict def solution(n, results): answer = 0 wins = defaultdict(set) loses = defaultdict(set) for result in results: winner, loser = result wins[winner].add(loser) loses[loser].add(winner) for node in range(1, n+1): for loser in wins[node]: loses[loser] |= loses[node] for winner in loses[node]: wins[winner] |= wins[node] for node in range(1, n+1): if len(loses[node]) + len(wins[node]) == n-1: answer += 1 return answer ================================================ FILE: programmers/난이도별/level03.순위/JeongShin.js ================================================ function solution(n, results) { const players = {}; const dfs = start => { let result = 0; Object.keys(players[start]).forEach((el) => { let count = 0; let visited = {}; const stack = []; stack.push(start); while (stack[0]) { const curr = stack.pop(); players[curr][el].forEach((v) => { if (!visited[v]) { visited[v] = true; stack.push(v); count++; } }) } result += count; }) return result; } for (let i = 1; i <= n; i++) { players[i] = ({win: [], lose: []}) } for (const r of results) { const [w, l] = r; players[w].win.push(l); players[l].lose.push(w); } let answer = 0; for (let i = 1; i <= n; i++) { const result = dfs(i); answer += (result === (n - 1)) } return answer; } solution(5, [[4, 3], [4, 2], [3, 2], [1, 2], [2, 5]]) ================================================ FILE: programmers/난이도별/level03.순위/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/49191 순위 [풀이] 1. 선수 번호는 1번부터 시작하므로 번호 - 1을 해서 그래프는 0번 부터 시작하도록 함 2. 이기면 1, 지면 -1을 할당 3. 어떤 선수 A가 이긴 사람 B가 있을 때 이긴 사람 B가 이긴 사람 C가 있다면 A가 C를 이긴다. => 각 선수에 대하여 반복문을 돌린다(첫번째 FOR). 이긴 사람 B를 찾는 과정 => 그 선수가 이긴 선수에 대해서 또 반복문을 돌린다. 이긴 사람 C를 찾는 과정(두번째 FOR) => 이를 반복한다 (WHILE) 4. 정확하게 순위를 매길 수 있으려면 모든 선수와의 승패가 나타나져야 하므로 자신을 제외한 모든 숫자가 1 또는 -1 => 따라서 count(0) == 1 이 되어야 한다. ''' def solution(n, results): board = [[0] * n for _ in range(n)] for st, ed in results: board[st - 1][ed - 1] = 1 board[ed - 1][st - 1] = -1 for i in range(n): win = [idx for idx, val in enumerate(board[i]) if val == 1] while win: lose = win.pop() for idx, val in enumerate(board[lose]): if val == 1 and board[i][idx] == 0: board[i][idx] = 1 board[idx][i] = -1 win.append(idx) return sum([i.count(0) == 1 for i in board]) ''' ''' ================================================ FILE: programmers/난이도별/level03.숫자_게임/6047198844.py ================================================ import bisect def solution(A_teams, B_teams): answer = 0 B_teams.sort() for A_team in A_teams: winner_idx =bisect.bisect(B_teams, A_team) # B팀이 이긴 경우. 이길수있는 비용중 최소의 비용을 들여 이긴다. # B팀이 무조건 지는 경우. 가장 작은 값을 내보낸다 if winner_idx != len(B_teams): answer += 1 B_teams.pop(winner_idx % len(B_teams)) return answer ================================================ FILE: programmers/난이도별/level03.숫자_게임/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12987 숫자 게임 [풀이] 1. 두 리스트 A, B를 내림차순으로 정렬 2. A에 원소보다 큰 B의 원소를 찾는다. => 못찾으면 B의 포인터를 +1씩 증가 => 찾으면 A와 B의 포인터를 +1씩 증가 => 이 방법이 왜 적용되는가? => B의 입장에서는 현재 포인터에서 a보다 b가 크면 이를 만족하는 b중에 가장 최소 => 이 말은 B에서 나올 수 있는 경우의 수중 가장 효율적인 경우 => A의 입장에서는 현재 포인터에서 a보다 큰 b를 못찾으면 이후에 있는 a보다 큰 b를 찾을 수 없음 => 따라서 일단 현재 제일 작은 a부터 넘고 다음 문제를 해결해야함 3. 시간복잡도는 O(N+M) ''' def solution(A, B): A.sort() B.sort() idx = result = 0 for a in A: while idx < len(B): if a < B[idx]: result += 1 idx += 1 break idx += 1 return result ''' 첫번째 제출한 코드. 정확성 테스트는 만점. 효율성 테스트는 O(n^2) 이 되버려서 시간초과. def solution(A, B): B.sort() result = 0 for a in A: idx = 0 while idx < len(B) and a >= B[idx]: idx += 1 if idx == len(B): B = B[1:] else: B = B[:idx]+B[idx+1:] result += 1 return result 두번째 제출한 코드는 이진탐색 코드. 그러나 시간초과. O(N*logN) 도 안되나보다. 다음은 좀 더 효율성이 좋은 O(N) 코드 def solution(A, B): answer = 0 A.sort() B.sort() j = 0 for i in range(len(A)): if A[j] < B[i]: answer = answer + 1 j = j+1 return answer 이 코드 역시 A를 고정시키고 B를 증가시켰는데, 반복문의 대상을 B로 설정(나는 A로 설정) ''' ================================================ FILE: programmers/난이도별/level03.스타_수열/6047198844.py ================================================ from collections import Counter def solution(a): answer = 0 # 부분수열은 원래 순서을 유지하여 얻을 수 있는 a를 포함한 a의 부분집합이다. stars = Counter(a).most_common() for star, N in stars: # 스타를 기준으로 구함. # 현재 스타로 만들수있는 최대 스타 수열이 answer보다 같거나 작을 경우 가지치기 if N * 2 <= answer: return answer star_count = 0 idx = 0 while idx < len(a) - 1: if a[idx] != a[idx + 1] and (star == a[idx] or star == a[idx + 1]): # 수열에 추가 star_count += 2 # 현재 구간은 수열에 소모됬으므로 idx를 두번 더한다. idx += 1 idx += 1 answer = max(star_count, answer) return answer ================================================ FILE: programmers/난이도별/level03.스티커_모으기(2)/6047198844.py ================================================ import sys sys.setrecursionlimit(10 ** 7) def solution(sticker): answer = 0 if len(sticker) == 1: return sticker[0] def dp(idx, sticker, memo): if idx >= len(sticker): return 0 # 현재스티커포함 # + 다다음 스티커의 경우의수 if memo[idx] != 0: return memo[idx] memo[idx] = max(sticker[idx] + dp(idx + 2, sticker, memo), sticker[idx] + dp(idx + 3, sticker, memo)) return memo[idx] memo1 = [0] * len(sticker) memo2 = [0] * len(sticker) # 첫번째 스티커 땐경우 / 두번째 스티커 땐경우 / 세번째 스티커 땐경우 answer = max(dp(0, sticker[:-1], memo1), dp(1, sticker, memo2), dp(2, sticker, memo2)) return answer ================================================ FILE: programmers/난이도별/level03.야근_지수/khw970421.js ================================================ function solution(n, works) { works.sort((a,b)=>(b-a)) if(works.reduce((acc,val)=>acc+val ,0) < n ) return 0; while(n>0) { for(let i=0;;i++) { works[i]--; n--; if(works[i]+1 !== works[i+1] || n===0) break; } } return works.reduce((acc,val)=>acc+val*val ,0); } //문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12927# //코드 정리 : https://velog.io/@khw970421/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%95%BC%EA%B7%BC-%EC%A7%80%EC%88%98 ================================================ FILE: programmers/난이도별/level03.야근지수/6047198844.py ================================================ from collections import Counter import heapq def solution(n, works): answer = 0 queue = [] for idx, work in enumerate(works): heapq.heappush(queue, (-work,idx)) for _ in range(n): value, idx = heapq.heappop(queue) if value == 0: return 0 heapq.heappush(queue, (value + 1, idx)) return sum([value**2 for value, idx in queue]) ================================================ FILE: programmers/난이도별/level03.야근지수/JeongShin.js ================================================ class priorityQueue { constructor(arr) { this.queue = arr; this.queue.sort((a, b) => a - b); this.rear = arr.length; } push(el) { this.queue.push(el); this.queue.sort((a, b) => a - b); this.rear++; } pop() { const result = this.queue.pop(); if (result) { this.rear--; return result; } } peek() { if (this.rear > 0) return this.queue[this.rear - 1]; return 0; } } function solution(n, works) { const queue = new priorityQueue(works) while (n > 0) { const curr = queue.pop(); n-- queue.push(curr - 1); } return works.reduce((acc, curr) => acc + (curr > 0 ? curr ** 2 : 0), 0) } ================================================ FILE: programmers/난이도별/level03.야근지수/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/49994 야근지수 max heap 사용 ''' from heapq import heappush, heappop, heapify def solution(n, works): works = [-i for i in works] heapify(works) for i in range(n): if works[0] == 0: return 0 heappush(works, heappop(works) + 1) return sum([i*i for i in works]) ''' ''' ================================================ FILE: programmers/난이도별/level03.여행경로/6047198844.py ================================================ import collections def solution(tickets): answer = [] graph = collections.defaultdict(list) for ticket in tickets: departure, arrival = ticket graph[departure].append(arrival) for edges in graph.values(): edges.sort() def dfs(departure): while graph[departure]: arrival = graph[departure].pop(0) dfs(arrival) answer.append(departure) dfs("ICN") return answer[::-1] ================================================ FILE: programmers/난이도별/level03.여행경로/JeongShin.js ================================================ function solution(tickets) { // dfs 종료조건 : 모든 티켓을 사용할 때, 즉, 현재 여행 경로의 길이가 티켓 개수 + 1 const target = tickets.length + 1; let answer = false; // 1) 모든 티켓을 알파벳 순으로 정렬 tickets.sort(); const ticketCount = tickets.reduce((obj, t) => { const [from, to] = t; obj[from + to] = (obj[from + to] || 0) + 1; return obj; }, {}); const dfs = routes => { const len = routes.length; if (answer) return; if (len === target) { return answer = routes; } const visited = routes.reduce((obj, to, idx) => { const from = routes[idx - 1]; if (from) obj[from + to] = (obj[from + to] || 0) + 1; return obj; }, {}); const end = routes[len - 1]; tickets.forEach((v) => { const [from, to] = v; if (from === end && ((visited[from + to] || 0) < ticketCount[from + to])) dfs([...routes, to]); }) } dfs(["ICN"]); return answer } ================================================ FILE: programmers/난이도별/level03.여행경로/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/18/lessons/43164 여행 경로 dictionary로 사용. dfs 방식 stack 사용. ''' def solution(tickets): dic = {} for st, ed in tickets: dic.setdefault(st, []) dic[st].append(ed) for i in dic.keys(): dic[i].sort(reverse=True) stack = ["ICN"] save = [] while stack: start = stack[-1] if start not in dic or not dic[start]: save.append(stack.pop()) continue stack.append(dic[start].pop()) return save[::-1] ''' 채점 케이스 1번이 너무 안풀려서 한참 골아팠음. 이유는 잘 모르겠다. 나같은 사람들도 많던데, 다만 while문 돌릴 때 ticket의 갯수와 관련없이 stack으로 푸니까 풀렸음 ''' ================================================ FILE: programmers/난이도별/level03.예산/JeongShin.js ================================================ function solution(budgets, M) { const dividable = (arr, bud) => arr.reduce((acc, curr) => acc + Math.min(curr, bud), 0) <= M; const len = budgets.length; const sorted = budgets.sort((a, b) => a - b); let [low, high] = [sorted[0], sorted[len - 1]]; if (M < low * len) return ~~(M/len); while (low <= high) { const mid = ~~((low + high) / 2); if (dividable(sorted, mid)) low = mid + 1; else high = mid - 1; } return high; } solution([120, 110, 140, 150], 100); ================================================ FILE: programmers/난이도별/level03.외벽점검/6047198844.py ================================================ import collections import heapq def solution(n, weak, dist): answer = 0 graph = collections.defaultdict(list) N = len(weak) finders = [] for i in dist: heapq.heappush(finders,-i) while finders and weak: finder = -heapq.heappop(finders) remove = tuple() remove_val = 0 for i in weak: for j in weak: if i != j: cost = min((j-i)%n,(i-j)%n) if finder >= cost > remove_val: remove = (i,j) remove_val = cost if remove_val == 0: return -1 if len(weak) > len(dist) else len(dist) - len(weak) else: i, j = remove weak.remove(i) weak.remove(j) print(i,j) return -1 if weak else len(dist) - len(finders) ================================================ FILE: programmers/난이도별/level03.외벽점검/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/60062 ================================================ FILE: programmers/난이도별/level03.외벽점검/junilhwang.js ================================================ function solution(n, weak, dist) { weak.sort((a, b) => a - b) dist.sort((a, b) => b - a) const len = dist.length const chk = a => { } const f = (a, last) => { chk(a) for (let i = last + 1; i < len; i++) { f([...a, i], i) } } for (let i = 0; i < len; i++) f([i], i) return -1; } console.log(solution(12, [1, 5, 6, 10], [1, 2, 3, 4]),2) //console.log(solution(12, [1, 3, 4, 9, 10], [3, 5, 7]),1) ================================================ FILE: programmers/난이도별/level03.외벽점검/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/60062 외벽 점검 [풀이] 1. 몇개의 변수를 세팅해준다 1-1. 원래 week 길이를 기억하기 위한 W 1-2. 시계방향 또는 반시계방향으로 이동 가능한 것은 시계방향으로만 이동해도 무관하다 => 방향을 고려하지 않기 위해 weak을 확장 n만큼 더해준 수만큼을 추가한다 1-3. 각 지점에서 다음 지점까지의 차이를 구한 diff 1-4. 추후에, 친구들이 이동한 거리들을 구할 것이다. => 이 때, 친구들이 이동한 거리가 [5, 4, 3]이고 dist가 [6, 4, 2] 라고 하자 => 그러면 친구들이 이동한 거리 [5, 4, 3]은 실제로 이동할 수 없는 거리이다 => 왜냐하면 6과 4는 같은 인덱스 위치인 5와 4보다 같거나 크지만, 2는 3보다 작기 때문 => 이렇게, 내림차순으로 정렬해서 같은 인덱스 값을 비교함으로써 수리 여부를 판단할 수 있다 => 따라서 dist를 미리 오름차순 정렬한다. 2. 어떤 점부터 시작할 지 모르니 모든 점이 시작점이 되도록 반복문을 작성 => diff는 2n-1개만큼 존재하지만 실제로 n-1개만 고려할 것이다. => diff가 2n-1개만큼 존재하는 이유는 1-2. 에서 방향을 고려하지 않게 하기 위해서 3. 이 때, 각 점은 친구들이 단지 방문하거나 기존 점에서 이동하는 2가지 방법이 있다 => 단지 방문하면 길이는 0 => 기존 점에서 이동하면 마지막 거리값에서 플러스 4. 이제 구한 거리들이 실제로 가능한지 비교해본다. => 불가능한 거리라면 W+1을 answer에 apppend => 왜? -1을 append 하면 추후에 min을 쓰기 어려워진다 => min을 왜써? 요구사항이 가장 작은 거리를 요구하기 때문 => 이 거리들은 최대 W의 값을 가지므로 W+1의 값을 append => 이렇게 되면, min(answer) == W+1 일 때 -1을 출력 가능 ''' def solution(n, weak, dist): W = len(weak) weak += [w + n for w in weak] diff = [weak[idx] - weak[idx - 1] for idx in range(1, len(weak))] dist.sort(reverse=True) answer = [] for st in range(W): stack, save = [[]], [] for idx in range(st, W + st): while stack: lst = stack.pop() if len(lst) < len(dist): save.append(lst + [0]) if lst: save.append(lst[:-1] + [lst[-1] + diff[idx]]) stack, save = save, stack for s in stack: for a, b in zip(dist, sorted(s, reverse=True)): if a < b: answer.append(W + 1) break else: answer.append(len(s)) return -1 if min(answer) == W + 1 else min(answer) return answer ''' 너무 어렵다. 5시간 정도 고민해서 풀었다 ㅠ__ㅠ 내 풀이가 모든 경우의 수를 따지므로 combination을 사용한 풀이와 원리는 비슷하다. set을 사용한 풀이가 효율성이 좋던데 이해를 잘 못하겠다. ''' ================================================ FILE: programmers/난이도별/level03.이중우선순위큐/JeongShin.js ================================================ class minMaxHeap { constructor() { this.queue = []; } push(el) { this.queue.push(el); this.queue.sort((a, b) => b - a); } popMin() { const result = this.queue.pop(); if (result){ return result; } return 0; } popMax() { const result = this.queue.splice(0,1) * 1; if (result){ return result } return 0; } } function solution(operations) { const heap = new minMaxHeap(); for (const o of operations) { const [command, data] = o.split(" "); if (command === 'I') heap.push(data * 1); else { data === '1' ? heap.popMax() : heap.popMin(); } } return [heap.popMax(), heap.popMin()]; } console.log(solution(["I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333"])) ================================================ FILE: programmers/난이도별/level03.이중우선순위큐/junilhwang.js ================================================ // https://programmers.co.kr/learn/courses/30/lessons/42628 class Heap { constructor () { this.v = [] } push (n) { this.v.push(n) this.v.sort((a, b) => a - b) } pop (type) { type === 1 ? this.v.pop() : this.v.shift() } getMax (len = this.v.length) { return len ? this.v[len - 1] : 0 } getMin (len = this.v.length) { return len ? this.v[0] : 0 } } function solution (operations) { const heap = new Heap(); operations.forEach(v => { const [command, n] = v.split(' '); command === 'I' ? heap.push(~~n) : heap.pop(n*1) }) return [heap.getMax(), heap.getMin()]; } console.log(solution(["I 16", "I -5643", "D -1", "D 1", "D 1", "I 123", "D -1"]), [0, 0]) console.log(solution(["I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333"]), [333, -45]) // console.log(solution(["I 16", "D 1"]), [0,0]) // console.log(solution(["I 7", "I 5", "I -5", "D -1"]), [7,5]) ================================================ FILE: programmers/난이도별/level03.이중우선순위큐/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/42628 이중우선순위큐 [풀이] 1. 우선순위 큐 라이브러리 호출 2. 최솟값을 제거할 경우 => heappop 이용 3. 최댓값을 제거할 경우 => nlargest 이용 ''' from heapq import heappush, heappop, nlargest def solution(operations): que = [] for o in operations: com, num = (lambda x : (x[0], int(x[1])))(o.split()) if com == 'I': heappush(que, num) else: if num == 1: que = nlargest(len(que), que)[1:][::-1] else: if len(que) > 0: heappop(que) return (lambda x : [x[-1], x[0]] if len(x) > 0 else [0, 0])(sorted(list(que))) ''' 시간초과에 예민한 문제가 아니라 풀어도 찝찝하다. 이런 문제는 최대최소힙을 선언 후 동기화하는 과정으로 풀고 싶었다. 최대최소힙에 대한 비슷한 문제가 있어서 풀었던 것으로 기억하는데, 무슨 문제였는지 기억이 잘 안난다. 새로 알게된 문법 heapq.remove(value) : 해당 값을 삭제 heapq.nlargest(length, heap) : heap에서 크기가 큰 순으로 해당 길이만큼 반환. ''' ================================================ FILE: programmers/난이도별/level03.입국심사/6047198844.py ================================================ def solution(n, times): answer = 0 min_time = 1 max_time = max(times)*n left = min_time right = max_time while left < right: mid = (left + right) // 2 complete_person_n = 0 for time in times: complete_person_n += mid //time if complete_person_n >= n: right = mid else: left = mid + 1 answer = left return answer ================================================ FILE: programmers/난이도별/level03.입국심사/JeongShin.js ================================================ function solution(n, times) { const count = t => { return times.reduce((acc, curr) => acc + Math.floor(t / curr), 0) }; const len = times.length; let [low, high] = [Math.min(...times), Math.max(...times)].map((el => ((el * n) / len))); while (low <= high) { const mid = Math.floor((low + high) / 2); if (count(mid) < n) low = mid + 1; else high = mid - 1; } return low; } ================================================ FILE: programmers/난이도별/level03.입국심사/rockmiin.py ================================================ def solution(n, times): answer = 0 start, end = 0, max(times) * n while start <= end: mid = (start + end) // 2 tmp_n = 0 for t in times: tmp_n += mid // t if tmp_n >= n: answer = mid end = mid - 1 elif tmp_n < n: start = mid + 1 # print(start, end, tmp_n) return answer ================================================ FILE: programmers/난이도별/level03.입국심사/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/43238 입국심사 [풀이] 1. 사람이 10억명. 따라서 O(N) 이하의 시간복잡도를 가져야 한다 2. 시간을 1초부터 세지 말고 최대 걸리는 시간의 범위에서 이진탐색 실행 => 최대 시간은 max(times) * n => 심사를 오래하는 사람에게 모두 심사를 받는 경우 ''' def solution(n, times): low = 0 high = max(times) * n while low < high: mid = (low + high) // 2 sum = 0 for t in times: sum += (mid // t) if sum < n: low = mid + 1 else: high = mid return low ''' ''' ================================================ FILE: programmers/난이도별/level03.자물쇠와열쇠/6047198844.py ================================================ def solution(key, lock): def key_rotate(rkey): return list(zip(*rkey[::-1])) def is_valid(board): for y in range(M, M + N): for x in range(M, M + N): if board[y][x] != 1: return False return True def unlock(yy, xx, board, flag): for y in range(yy, yy + M): for x in range(xx, xx + M): board[y][x] += (key[y - yy][x - xx] * flag) # lock를 NXN칸의 중앙으로 놓자. M = len(key) N = len(lock) # 흰 판을 준비한다. board = [[0 for _ in range(N + 2 * M)] for _ in range(N + 2 * M)] # 흰 판에 튀어나온 부분을 입힌다. for y in range(M, M + N): for x in range(M, M + N): board[y][x] = lock[y - M][x - M] # print_board(board) # key를 4방향으로 90도씩 돌려가며 비교한다. for _ in range(4): key = key_rotate(key) for y in range(0, N + M): for x in range(0, N + M): unlock(y, x, board, +1) if is_valid(board): return True unlock(y, x, board, -1) return False ================================================ FILE: programmers/난이도별/level03.자물쇠와열쇠/README.md ================================================ # 출처 https://programmers.co.kr/learn/courses/30/lessons/60059https://programmers.co.kr/learn/courses/30/lessons/60059 ================================================ FILE: programmers/난이도별/level03.자물쇠와열쇠/junilhwang.js ================================================ function solution(key, lock) { const len = key.length const turn = arr => { const temp = arr.map(v => arr.map(v2 => 0)) for (let i = 0; i < len; i++) { for (let j = 0; j < len; j++) { temp[i][j] = arr[len - j - 1][i] } } return temp } const move = (arr, x = 0, y = 0) => { let temp = [...arr] if (y !== 0) { const absY = Math.abs(y) const [remove, insert] = y > 0 ? ['pop', 'unshift'] : ['shift', 'push'] const z = arr.map(() => 0) for (let i = 0; i < absY; i++) { temp[remove]() temp[insert](z) } } else if (x !== 0) { const absX = Math.abs(x) const [remove, insert] = x > 0 ? ['pop', 'unshift'] : ['shift', 'push'] for (let i = 0; i < len; i++) { for (let j = 0; j < absX; j++) { temp[i][remove]() temp[i][insert](0) } } } return temp } const chk = arr => { let cnt = 0 console.log(arr, lock) for (let i = 0; i < len; i++) { for (let j = 0; j < len; j++) { if (arr[i][j] === lock[i][j]) return false } } return true } let temp = key for (let i = 0; i < 4; i++) { for (let j = 0; j < len; j++) { if (move(temp, j, 0) || move(temp, -j, 0)) return true for (let k = 1; k < len; k++) { if (move(temp, j, k) || move(temp, j, -k)) return true if (move(temp, -j, k) || move(temp, -j, -k)) return true } } temp = turn(temp) } return false } console.log(solution([[0, 0, 0], [1, 0, 0], [0, 1, 1]], [[1, 1, 1], [1, 1, 0], [1, 0, 1]]), true) ================================================ FILE: programmers/난이도별/level03.자물쇠와열쇠/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/60059 자물쇠와 열쇠 : 카카오 블라인드 채용 2020 문제 1) 키가 락이 완전히 겹치지 않아도 되는 부분까지 락으로 생각하고 락 확장. 이 떄 값은 -2 2) 키와 락이 겹칠 때는 1 + 0 이나 0 + 1로 1 그리고 -2 + 1 이나 -2 + 0까지 고려 3) 모든 락 홈에 맞아야 하므로 락 홈의 개수를 미리 구하고 이후에 모양이 맞더라도 모든 홈을 맞추었는지 조사 ''' def solution(key, lock): numLocks = sum([i.count(0) for i in lock]) keysize = len(key) exlock = [[-2] * (keysize - 1) + i + [-2] * (keysize - 1) for i in lock] pad = [[-2] * len(exlock[0]) for i in range(keysize - 1)] exlock = pad + exlock + pad locksize = len(exlock) for rotate in range(4): key = [list(e) for e in zip(*key[::-1])] for i in range(locksize - keysize + 1): for j in range(locksize - keysize + 1): answer = num = 0 for k in range(keysize): for l in range(keysize): if key[k][l] + exlock[i + k][j + l] == 1 or key[k][l] + exlock[i + k][j + l] < 0: answer += 1 if exlock[i + k][j + l] == 0: num += 1 if answer == keysize ** 2 and num == numLocks: return True return False ''' 아 굳이 -2 아니고 0으로 해도 되는구나.. ''' ================================================ FILE: programmers/난이도별/level03.저울/JeongShin.js ================================================ function solution(weight) { weight.sort((a, b) => a - b) let answer = 1 for (const w of weight) { if (answer < w) break; answer+=w } return answer } solution([3, 1, 6, 2, 7, 30, 1]); ================================================ FILE: programmers/난이도별/level03.정수_삼각형/6047198844.py ================================================ def dp(triangle, y, x, n): if y == n: return 0 if memo[y][x] != -1: return memo[y][x] memo[y][x] = triangle[y][x] + max(dp(triangle, y + 1, x, n), dp(triangle, y + 1, x + 1, n)) return memo[y][x] def solution(triangle): answer = 0 global memo memo = [[-1 for _ in range(i)] for i in range(1, len(triangle) + 1)] return dp(triangle, 0, 0, len(triangle)) ================================================ FILE: programmers/난이도별/level03.정수_삼각형/JeongShin.js ================================================ function solution(triangle) { let level = triangle.length - 1; if (level === 0) return triangle[0]; const score = new Array(level + 1).fill(0); while (level > 0) { for (let i = 0; i < level; i++) { score[i] = Math.max(score[i] + triangle[level][i], score[i + 1] + triangle[level][i + 1]) } level--; } return triangle[0] * 1 + score[0] } solution([[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]]); ================================================ FILE: programmers/난이도별/level03.정수_삼각형/rockmiin.py ================================================ def solution(triangle): dp=[[0]* i for i in range(1, len(triangle)+1)] for i in range(0, len(triangle)): for j in range(i+1): if j==0: dp[i][j]=dp[i-1][j]+triangle[i][j] elif j==i: dp[i][j]=dp[i-1][j-1]+triangle[i][j] elif j>=1: dp[i][j]=max(dp[i-1][j], dp[i-1][j-1])+triangle[i][j] return max(dp[len(triangle)-1]) print( solution([[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]])==30 ) ================================================ FILE: programmers/난이도별/level03.정수_삼각형/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/43105 정수 삼각형 [풀이] 1. 왼쪽과 오른쪽은 각각 삼각형의 테두리선의 합으로 정의 2. 나머지 원소는 왼쪽 위와 왼쪽 오른 쪽중 더 큰 값을 더하기 3. 최종 층에서는 모든 경우의 수가 더해진 것 중에 큰 것들만 모인 것. 이중에 최대를 반환. ''' def solution(triangle): tri = triangle for i in range(1, len(tri)): for j in range(len(tri[i])): if j == 0: tri[i][0] += tri[i - 1][0] elif j == len(tri[i]) - 1: tri[i][-1] += tri[i - 1][-1] else: tri[i][j] += max(tri[i - 1][j - 1], tri[i - 1][j]) return max(tri[-1]) ''' [한줄코드 분석] solution = lambda t, l = []: max(l) if not t else solution(t[1:], [max(x,y)+z for x,y,z in zip([0]+l, l+[0], t[0])]) 1. solution은 t와 l로 이루어진 함수 => t는 triangle, l은 빈 리스트임 2. t가 존재하지 않으면 max(l)을 반환 3. t가 존재하면 t = t[1:], l = [max(x,y)+z for x,y,z in zip([0]+l, l+[0], t[0])] 를 다시 호출 => 재귀적 함수를 구현했다. t = t[1:] => 삼각형의 다음 층에대해 조사 => 언젠가는 다음 층이 없으므로 이 때 max(l)을 반환 4. l = [max(x,y)+z for x,y,z in zip([0]+l, l+[0], t[0])] => l은 처음 층에서 빈 리스트이기 때문에 [max(x,y)+z for x,y,z in zip([0], [0], t[0])] 가 계산됨 => 다음층으로 건네주는 l은 t[0]가 된다. => 그 다음층으로 건네주는 l은 t[0]가 더해진 t[1]이 된다 5. 두번째 층 [3,8]을 기준으로 zip을 보면 다음과 같이 된다. => zip([0, 7], [7, 0], [3,8]) 6. 따라서 x, y, z는 다음과 같은 순서쌍을 가진다 (0, 7, 3) => max(0, 3) + 7 (7, 0, 8) => max(7, 0) + 8 => 이 부분이 가장 핵심적인 부분. 한줄로 구현할 때 제일 많이 고민해야 하는 부분이다. => 전 층에서 다음층으로 넘어갈 때 더 큰 쪽을 넘겨줘야 하는 부분을 구현하면서, 양 끝에 있는 부분도 if조건없이 한번에 할 수 있도록 [0] 리스트를 더해주는 스킬 ''' ================================================ FILE: programmers/난이도별/level03.종이접기/JeongShin.js ================================================ function solution(n) { const arr = [0] let len = 1 let i = 1 while (i < n) { for (let j = 1; j <= len; j++) arr[len + j] = 1 ^ arr[len - j] arr[len] = 0; len = len * 2 + 1 i++ } return arr } solution(3) ================================================ FILE: programmers/난이도별/level03.줄_서는_방법/6047198844.py ================================================ import math from itertools import permutations def solution(n, k): answer = [] people = list(range(1, n + 1)) def dfs(people, nth): N = len(people) if N == 1: return people group, nth = nth // math.factorial(N - 1), nth % math.factorial(N - 1) M = people.pop(group) return [M] + dfs(people, nth) answer = dfs(people, k - 1) return answer ================================================ FILE: programmers/난이도별/level03.줄_서는_방법/JeongShin.js ================================================ /* * 첫 번째 시도 : recursive 하게 k 번째 경우의 수를 찾는 경우의 수 알고리즘 * 효율성에서 불합격 👉 k 번째 경우의 수까지 전에 존재하는 모든 경우의 수를 찾기 때문 * */ function solution(n, k) { const target = new Array(n).fill(null).map((el, idx) => idx + 1) let done = false; let answer = []; let trail = 0; const fill = arr => { const len = arr.length; if (done) return; if (len === n) { trail++; if (trail === k) { done = true; answer = [...arr]; } return; } target.forEach((el) => { if (!~arr.indexOf(el)) { fill([...arr, el]) } }) } fill([]) return answer; } // 몫과 나머지를 이용하여 n번의 반복문으로 k 번째 수를 찾는 알고리즘 구현 // 정확도 성능 둘다 합격 function solution2(n, k) { const arr = new Array(n).fill(null).map((el, idx) => idx + 1) const answer = [] const cache = {'0': 1} const factorial = num => { let result if (cache[num]) result = cache[num] else result = cache[num] = num * factorial(num - 1) return result } k--; let len; while ((len = answer.length) < n) { const divide = factorial(n - len - 1) const [quotient, remainder] = [k / divide, k % divide] const val = arr.splice(quotient, 1)[0]; answer.push(val); k = remainder; } return answer } solution(4, 7) ================================================ FILE: programmers/난이도별/level03.줄_서는_방법/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12936 줄 서는 방법 [풀이] 1. 각 경우의 수는 FACTORIAL 만큼 존재 => 미리 factorial을 구해놓는다 => math.factorial을 써도 가능하다 2. 사전 순으로 나열할 때 가장 처음 등장하는 수는 range(1, n+1)에서 (k-1) // (n-1)! 에 해당하는 순서의 수이다. => 반복문으로 이를 구한다 => 매번 구해지는 순서는 결과 리스트에 추가 ''' def solution(n, k): dp = [1] + [0] * n for i in range(1, n + 1): dp[i] = i * dp[i - 1] lst = list(range(1, n + 1)) ret = [] for i in range(n - 1, -1, -1): idx = (k - 1) // dp[i] ret.append(lst.pop(idx)) k = k % dp[i] return ret ''' 첫번째 제출한 코드. 효율성 뿐만 아니라 정확성 테스트에서도 시간초과가 난다. 왜냐하면 product는 O(n!) 의 시간복잡도를 가지기 때문. 여기서 O(N) 으로 돌려야 겠다고 직감 => 순서문제구나! from itertools import product def solution(n, k): lst = list(map(str, list(range(1, n+1)))) pdt = list(product(*([lst] * n))) idx = 0 for p in pdt: if len(set(p)) == n: if idx == k-1: return list(map(int, p)) else: idx += 1 ''' ================================================ FILE: programmers/난이도별/level03.징검다리_건너기/6047198844.py ================================================ import heapq import collections def solution(stones, k): window = collections.Counter(stones[:k]) answer = max_value = max(window) #최대값추출하는곳 heap = list(map(lambda key:-key, window.keys())) heapq.heapify(heap) stone_value = set(window.keys()) begin = 0 for end in range(k, len(stones)): #삭제할값 i = stones[begin] begin += 1 #추가할값 j = stones[end] #윈도우 조정 window[i] -= 1 window[j] += 1 stone_value.add(j) heapq.heappush(heap, -j) if window[i] == 0: del window[i] stone_value.remove(i) while -heap[0] not in stone_value: heapq.heappop(heap) answer = min(answer, -heap[0]) #print(heap,answer,window) return answer ================================================ FILE: programmers/난이도별/level03.징검다리_건너기/JeongShin.js ================================================ function solution(stones, k) { const len = stones.length; const checkPossible = n => { let distance = 0; for (let i = 0; i < len; i++) { distance = stones[i] >= n ? 0 : distance + 1; if (distance >= k) return false; } return true; }; let [low, high] = [1, 200000000]; let answer; while (low <= high) { const mid = ~~((low + high) / 2); const result = checkPossible(mid); if (result) { answer = mid; low = mid + 1; continue; } high = mid - 1; } return answer; } solution([0, 1, 0, 3, 0, 0, 3, 0, 0], 3); ================================================ FILE: programmers/난이도별/level03.징검다리_건너기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12938 징검다리 건너기 [풀이] 0. 이진탐색 문제 => 하지만 이진탐색문제인지 몰랐다. 한참을 고민해도 몰랐음. 결국 참고. 1. 건너뛰어야 하는 돌의 개수가 k개 이하 => n명이 이미 지나갔고, 돌에 적혀있는 수가 n이하 => n이하의 수를 가진 돌이 연속적으로 k개 이하로 두어져 있어야 함 2. 이 n을 이진탐색으로 1 to max(stones) 범위에서 찾는다. => mid는 둘의 사이 => dist는 mid보다 작은 수를 지닌 연속적으로 이어지는 돌의 개수 => answer은 기본 1 (돌다리가 최소 하나이므로 하나는 무조건 건널 수 있음) 3. for-else continue를 이용해서 break시에 두 가지 흐름도를 설정 ''' def solution(stones, k): left, right = 1, max(stones) answer = 1 while left <= right: mid = (left + right) // 2 dist = 0 for stone in stones: if stone < mid: dist += 1 else: dist = 0 if dist == k: break else: answer = max(answer, mid) left = mid + 1 continue right = mid - 1 return answer ''' ''' ================================================ FILE: programmers/난이도별/level03.최고의_집합/6047198844.py ================================================ #다시 #접근이 잘못됬음 def solution(n, s): num = s // n return [-1] if num == 0 else [num] * (n-s%n) + [num+1] * (s%n) ================================================ FILE: programmers/난이도별/level03.최고의_집합/JeongShin.js ================================================ function solution(n, s) { let [q, r] = [Math.floor(s / n), s % n] if (q === 0) return [-1] const arr = new Array(n).fill(q); let i = n - 1; while (r > 0) { arr[i]++; r--; i--; } return arr } ================================================ FILE: programmers/난이도별/level03.최고의_집합/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12938 최고의 집합 [풀이] 1. 두 수 a, b의 곱이 최대가 될 때는 a == b 일 때이다. 이는, 두 수의 차가 최소일 때 곱이 최대가 됨을 암시한다. => 수학적으로 a와 b가 2e 만큼의 차이가 있을 때 두 수의 곱은 (c-e)(c+e)와 같다. => 이 때, c = (a+b)/2 => c^2 - e^2 은 e가 최소일 때 최대이므로 따라서 두 수의 차가 최소일 때 곱이 최대이다. 2. 각 값의 차이를 줄이는 테크닉은 몫 만큼의 값을 나눠가지고 나머지를 하나씩 나눠갖는 것이다. => 따라서 몫에 해당하는 값을 나눠 가지고 rest의 길이만큼 뒤에서부터 1씩 더해준다. => 뒤에서부터 더해주는 이유 : 결과를 오름차순으로 반환해야 하기 때문 => 당연한 말이지만, rest의 길이는 전체 리스트의 길이보다 작다(작아야 한다) ''' def solution(n, s): answer = [s // n] * n rest = s % n for i in range(1, rest+1): answer[-i] += 1 return [-1] if n > s else answer ''' ''' ================================================ FILE: programmers/난이도별/level03.카드_짝_맞추기/6047198844.py ================================================ import collections import sys from itertools import permutations def solution(board, r, c): def ctrl(y, x, dy, dx): while 0 <= y < 4 and 0 <= x < 4: y += dy x += dx if (y, x) in SET: return (y, x) if 0 <= y < 4: return (y, x-dx) else: return (y-dy, x) # dept에서 dest로 갈때 최소 비용을 반납한다. def dept_to_dest(A, B): # A에서 B로 이동하는 최소비용 direction = set() Q = [A] cmd = 0 while True: for _ in range(len(Q)): y, x = Q.pop(0) if (y, x) == B: return cmd # 좌우상하 # 컨트롤 좌우상하 for dy, dx in (1, 0), (-1, 0), (0, 1), (0, -1): ny = y + dy nx = x + dx if 0 <= ny < 4 and 0 <= nx < 4 and not (ny, nx) in direction: direction.add((ny, nx)) Q.append((ny, nx)) cny, cnx = ctrl(y, x, dy, dx) if not (cny, cnx) in direction: direction.add((cny, cnx)) Q.append((cny, cnx)) cmd += 1 def short_path(cursor, dist): if not dist: return 0 # cursor -> A # A -> B A, B = dist[0] # cursor -> A -> B i = dept_to_dest(cursor, A) + 1 + dept_to_dest(A, B) + 1 # cursor -> B -> A j = dept_to_dest(cursor, B) + 1 + dept_to_dest(B, A) + 1 SET.remove(A) SET.remove(B) i += short_path(B, dist[1:]) j += short_path(A, dist[1:]) SET.add(A) SET.add(B) return min(i, j) # a에서 b로 갈때 드는 최소비용반환. # 6! answer = sys.maxsize cards = collections.defaultdict(list) for y in range(0, 4): for x in range(0, 4): if board[y][x] != 0: cards[board[y][x]].append((y, x)) SET = set() for card1, card2 in cards.values(): SET.add(card1) SET.add(card2) for p in permutations(cards.values()): answer = min(answer, short_path((r, c), p)) return answer ================================================ FILE: programmers/난이도별/level03.타일_장식물/JeongShin.js ================================================ function solution(N) { const arr = new Array(2).fill(1); for (let i = 2; i <= N; i++) { arr[i] = arr[i - 1] + arr[i - 2]; } return (arr[N] + (arr[N - 1] || 0)) * 2; } ================================================ FILE: programmers/난이도별/level03.표 편집/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/81303 표 편집 [풀이] 0. 연결리스트 문제 => 보통 이런문제가 나오면 클래스로 짜는 사람이 있다. 참 대단.. 1. 연결리스트를 딕셔너리로 구현한다. => i번째 노드는 원소가 2개인 list 타입의 값을 가진다. => [0] : left = i-1번째 노드 => [1] : right = i+1번째 노드 => 0번 노드와 n-1번 노드는 양쪽 끝에 None을 가지고 있다. 2. 명령어가 C, Z일때를 조건으로 하고 그 외에는 split()을 한다. 2-1. C일 경우 => rm 리스트에 삭제할 노드의 idx와 left, right를 추가한다. => rm 리스트는 추후에 명령어가 Z일 경우 필요 => 자신의 left 노드와 right 노드를 서로 이어준다 => 이 때 None일 경우의 예외처리 2.2 Z일 경우 => 삭제한 노드가 담겨있는 rm 리스트에서 pop => 되돌리려는 노드가 가장 마지막 노드일 경우와 아닌 경우를 나눈다. => 그리고 자신의 left, right 노드와 자신을 이어준다. => 자신의 left, right가 현재 삭제되있을 가능성은? => 없다. 왜냐하면 자신이 가장 최근에 삭제된 노드기 때문 => 자신의 left, right가 삭제되었다면 이미 또 다른 left, right값을 가지고 있을 것임 2.3 U, D 일 경우 => D면 idx 증가, U면 idx 감소. => 연결리스트의 장점이 드러나는 부분 => 그 외의 방법은 이동하면서 노드가 삭제되었는지 여부를 검사해야한다. => 연결리스트는 연결이 안돼있으면 이미 삭제된 것이기 때문에 검사할 필요가 없음. ''' def solution(n, k, cmd): dic = {} for i in range(0, n): dic[i] = [i-1, i+1] dic[0][0] = dic[n-1][1] = None rm = [] for c in cmd: if c == "C": rm.append([k, dic[k][0], dic[k][1]]) if dic[k][1] is None: k = dic[k][0] dic[k][1] = None else: if dic[k][0] is not None: dic[dic[k][0]][1] = dic[k][1] dic[dic[k][1]][0] = dic[k][0] k = dic[k][1] elif c == "Z": idx, left, right = rm.pop() if left is not None: dic[left][1] = idx if right is not None: dic[right][0] = idx dic[idx] = [left, right] else: move, steps = c.split() for _ in range(int(steps)): k = dic[k][int(move == "D")] answer = ["O"] * n for idx, _, _ in rm: answer[idx] = "X" return ''.join(answer) ''' 리스트로 이 문제를 구현하면 100% 시간초과 날 것을 예상했다. => 삭제 검사, 리스트 중간에 삽입 및 삭제가 일어날 것이기 떄문 그래서 각 리스트의 상태를 기억할 수 있도록 구조를 짰다. 굉장히 좋은 풀이라고 생각했는데 효율성에서 에러가 났다. (아마 실제 인턴십 코테에서도 저랬던 것 같다) 아래 코드는 리스트로 짠 코드. 4개의 테스트 케이스에서 시간초과가 나서 결국 버려야 했다 ㅠㅠ def solution(n, k, cmd): lst = ["O"] * n top = n-1 remove = [] for c in cmd: if c == "C": remove.append(k) lst[k] = "X" drt = 2 * (top != k) - 1 while lst[k+drt] == "X": k += drt k += drt while lst[top] == "X": top -= 1 elif c == "Z": idx = remove.pop() lst[idx] = "O" top = max(idx, top) else: move, steps = c.split() steps = int(steps) drt = 2 * (move == "D") - 1 while steps: k += drt steps -= lst[k] == "O" #print(c, lst, remove, top, k) return ''.join(lst) ''' ================================================ FILE: programmers/난이도별/level03.표_편집/6047198844.py ================================================ #다시풀어보기. 실수가 많았다. class Node: def __init__(self, data): self.data = data self.prev = self.next = None def solution(n, k, cmds): answer = '' begin = cur = Node(None) # 이중연결리스트 형식으로 표현 prev = Node(None) for i in range(n): cur.next = Node(i) cur.next.prev, cur = cur, cur.next # begin은 현재 맨앞을 가리킨다. #begin = cur = begin.next #맨 앞을 삭제하더라도 . 삭제가 안됨. # 삭제한 노드. # 문제였음 delete_node = [] # cur 은 현재 커서이다. k만큼 이동시킨다. for _ in range(k): cur = cur.next # 명령 수행한다. for cmd in cmds: # C 또는 Z if len(cmd) == 1: # C인경우. 행이 하나도 남지않는 경우는 없다. # 삭제할 노드의 이전노드와 삭제할 노드의 다음노드를 연결한다. if cmd == 'C': delete_node.append(cur) prev_node = cur.prev next_node = cur.next if prev_node: prev_node.next = next_node if next_node: next_node.prev = prev_node cur = next_node else: cur = prev_node # Z인경우 # 복구한다. # 현재 선택된 행은 바뀌지 않는다. else: #문제였음. recover_delete_node = delete_node.pop() delete_prev_node = recover_delete_node.prev delete_next_node = recover_delete_node.next if delete_prev_node: delete_prev_node.next = recover_delete_node if delete_next_node: delete_next_node.prev = recover_delete_node # U 또는 D else: cmd, X = cmd.split() # U인경우 if cmd == 'U': for _ in range(int(X)): cur = cur.prev # D인경우 else: for _ in range(int(X)): cur = cur.next cur = begin answer = ['O' for _ in range(n)] #delete_node에서 삭제한 노드를 계산 for node in delete_node: answer[node.data] = 'X' return ''.join(answer) ================================================ FILE: programmers/난이도별/level03.풍선_터트리기/6047198844.py ================================================ import heapq def solution(a): answer_balloon = set() left_heap = [] right_heap = [] # left_heap / right_heap은 왼쪽 / 오른쪽에서 최후까지 남아있는 풍선을 뜻한다. # 풍선은 왼쪽이나 오른쪽의 최후의 풍선중 하나라도 자신보다 크다면 무조건 마지막까지 살아남을수있다. # EX) 왼쪽 최후가 크고 오른쪽 최후가 작은 경우. 왼쪽 최후 터트리고 오른쪽 최후는 찬스 이용 오른쪽을 터트릴수있음. # 답을 answer_balloon에 넣는다. for idx in range(len(a)): left_balloon = a[idx] heapq.heappush(left_heap, left_balloon) if left_heap[0] >= left_balloon: answer_balloon.add(left_balloon) right_balloon = a[-1 - idx] heapq.heappush(right_heap, right_balloon) if right_heap[0] >= right_balloon: answer_balloon.add(right_balloon) return len(answer_balloon) ================================================ FILE: programmers/난이도별/level03.풍선_터트리기/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/68646 풍선 터트리기 a의 개수가 최대 2백만개라 O(n)으로 끝내야함 1) 선택한 숫자를 기준으로 양 옆의 수들에 대해 양쪽의 최소값보다 작으면 된다. 2) 양쪽 중 한쪽이라도 만족하면 가능(작은 것을 터트릴 수 있는 기회가 있기 떄문) 3) 왼쪽 오른쪽 두번에 거쳐서 1,2)를 만족하는지 기록 ; 동시에 비교하기는 어려움. ''' def solution(a): answer = [0] * len(a) left = a[0] + 1 for idx, val in enumerate(a): if val < left: answer[idx] += 1 left = min(left, val) right = a[-1] + 1 for idx, val in enumerate(a[::-1]): if val < right: answer[len(a) - 1 - idx] += 1 right = min(right, val) return [i > 0 for i in answer].count(True) ''' ''' ================================================ FILE: programmers/난이도별/level03.하노이의_탑/6047198844.py ================================================ #n source destination other def tower_of_hanoi(n:int, source:int, destination:int, other:int): if n == 0: return tower_of_hanoi(n-1, source, other, destination) answer.append([source,destination]) tower_of_hanoi(n-1,other,destination,source) def solution(n): global answer answer = [] tower_of_hanoi(n,1,3,2) return answer ================================================ FILE: programmers/난이도별/level03.하노이의_탑/JeongShin.js ================================================ /* * | A | B | C | * Move n - 1 from A to B using C * Move 1 from A to C * Move n - 1 from B to C using A * */ function solution(n) { const answer = []; const move = (n, A, B, C) => { if (n > 0) { move(n - 1, A, C, B) answer.push([A, C]); move(n - 1, B, A, C) } } move(n, 1, 2, 3) return answer; } // console.log(solution(3)) ================================================ FILE: programmers/난이도별/level03.하노이의_탑/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/12946 하노이의 탑 [풀이] 1. n = 1 => [1, 3] 2. n = 2 => [1, 2], [1, 3], [2, 3] 3. n = 3 => [1, 3], [1, 2], [3, 2], [1, 3], [2, 1], [2, 3], [1, 3] 4. n = 4 => [1, 2], [1, 3], [2, 3], [1, 2], [3, 1], [3, 2], [1, 2], [1, 3], [2, 3], [2, 1], [3, 1], [2, 3], [1, 2], [1, 3], [2, 3] 5. 여기까지 규칙을 보면 가장 큰 원판을 옮길 때를 기준으로 양쪽에 규칙이 있다. => 큰 원판을 옮기기 전까지는 n-1 에 대해서 1은 고정, 2와 3을 서로 바꾼 순서로 진행. => 큰 원판을 옮긴 후에는 n-1 에 대해서 3은 고정, 1과 2를 서로 바꾼 순서로 진행 ''' def solution(n): answer = [[1, 3]] for _ in range(n - 1): front = [] for hanoi in answer: a, b = hanoi if hanoi[0] != 1: a = 6 // hanoi[0] if hanoi[1] != 1: b = 6 // hanoi[1] front.append([a, b]) back = [] for hanoi in answer: a, b = hanoi if hanoi[0] != 3: a = 2 // hanoi[0] if hanoi[1] != 3: b = 2 // hanoi[1] back.append([a, b]) answer = front + [[1, 3]] + back return answer ''' 학부 인공지능 수업에서 하노이를 재귀로 풀었던 기억이 있는데, 까맣게 까먹었다. 다른 사람 풀이 보자마자, 아 맞다! 했다... 재귀로 풀어도 위 로직은 동일하다. (근데 재귀가 더 깔끔하고 직관적) ''' ================================================ FILE: programmers/난이도별/level03.합승_택시_요금/6047198844.py ================================================ #include #include #include using namespace std; typedef pair P; const int INF = 9876543; vector dijk (int n , int src, vector> &edges){ vector dist(n+1,INF); priority_queue < P , vector

, greater

> pq; dist[src] = 0; pq.push({dist[src],src}); while(!pq.empty()){ int here = pq.top().second; int d = pq.top().first; pq.pop(); if(d > dist[here]) continue; for(auto p : edges[here]){ int there = p.first; int e = p.second; if(dist[there] > d + e){ dist[there] = d + e; pq.push({dist[there], there}); } } } return dist; } int solution(int n, int s, int a, int b, vector> fares) { vector>> edges(n+1); for(int i = 0; i < fares.size(); i++){ int u = fares[i][0]; int v = fares[i][1]; int e = fares[i][2]; edges[u].push_back({v,e}); edges[v].push_back({u,e}); } int res = INF; vector distS = dijk(n,s,edges); for(int i = 1; i < n+1; i++){ vector distAB = dijk(n,i,edges); int tmp = distS[i] + distAB[a] + distAB[b]; if(tmp < res) res = tmp; } return res; } ================================================ FILE: programmers/난이도별/level03.합승_택시_요금/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/72413 합승 택시 요금 [풀이] 0. 그래프 문제 중에 어려운 편. 1. 최대 요금은 100,000 이므로 각 노드 별로 도달할 수 없는 노드까지의 값을 이 보다 크게 잡는다. => 이 때, 100,001 로 잡으면 안된다. => 각 경로간의 최대 요금이 100,000 이므로 5개의 경로만 지나도 500,000 이다. => 지점 수 n개 만큼이 있을 때 최대로 지날 수 있는 간선의 개수는 n-1개. => 따라서, INF = 100,000 * (n-1) + 1 로 잡는 것이 맞다. 2. 여기서는 각 노드간의 관계를 2차원 배열로 표현했다. => dictionary로 표현해도 가능하다 => 이는 다익스트라 알고리즘 => 조금 더 복잡하다 3. 각 지점마다 i -> j로 가는 방법과 i -> k -> j 로 가는 방법 중 어떤 것이 최단거리 인지 비교한다 => 플로이드 마셜 알고리즘 => 이 때 j의 범위를 1부터 n+1로 하면 시간초과가 난다. => 2차원 배열 전체를 볼 게 아니라 주대각선 위의 값만 비교하면 된다. => board[i][j] = board[j][i] 로 양쪽 대칭값을 동시에 할당하기 때문 4. dist라는 3차원 배열을 선언한다. => 각각의 값은 n부터의 거리, a까지의 거리, b까지의 거리 이다. => n부터의 거리 : 동시에 택시를 타고 가는 거리 => a, b부터의 거리 : 각자 택시를 타고 가는 거리 ''' def solution(n, s, a, b, fares): INF = (n - 1) * 100000 + 1 board = [[INF] * (n + 1) for _ in range(n + 1)] for st, ed, c in fares: board[st][ed] = board[ed][st] = c for k in range(1, n + 1): for i in range(1, n + 1): for j in range(i + 1, n + 1): board[i][j] = board[j][i] = min(board[i][j], board[i][k] + board[k][j]) dist = [[0, 0, 0] for _ in range(n + 1)] # from n, a, b for idx in range(1, n + 1): board[idx][idx] = 0 dist[idx][0] = board[s][idx] dist[idx][1] = board[idx][a] dist[idx][2] = board[idx][b] return min([x + y + z for x, y, z in dist if x + y + z != 0]) ''' '다익스트라 알고리즘' 으로 풀은 다른 사람의 풀이는 다음과 같다. 여기서는 2차원 배열대신 dictionary를 사용했다. from collections import defaultdict import heapq def solution(n, s, a, b, fares): dic = defaultdict(list) for st, ed, co in fares: dic[st].append((co, ed)) dic[ed].append((co, st)) ans = [] for i in range(1, n+1): Q = [(0, i)] visited = [True] * (n+1) dp = [float('inf')] * (n+1) dp[i] = 0 while Q: co, des = heapq.heappop(Q) if visited[des]: visited[des] = False for cost, destination in dic[des]: dp[destination] = min(cost + dp[des], dp[destination]) heapq.heappush(Q, (dp[destination], destination)) ans.append(dp[a] + dp[b] + dp[s]) return min(ans) ''' ================================================ FILE: programmers/난이도별/level03.헤비 유저가 소유한 장소/6047198844.sql ================================================ SELECT ID, NAME, HOST_ID FROM PLACES WHERE HOST_ID IN ( SELECT HOST_ID FROM PLACES GROUP BY HOST_ID HAVING COUNT(HOST_ID) > 1 ) ORDER BY ID ================================================ FILE: programmers/난이도별/level04.가사_검색/JeongShin.js ================================================ // 2020.08.25 코드 복습 및 수정 class Node { constructor(key) { this.key = key; this.count = 0; this.children = new Map(); } } class Trie { constructor() { this.root = new Node(null); } // @param {boolean} reverse : 단어를 거꾸로 넣을 것인지 (true) 순서대로 넣을 것인지 (false) insert(word, reverse, len) { let node = this.root; for (let i = 0; i < len; i++) { const curr = word[reverse ? len - i - 1 : i]; if (!node.children.has(curr)) node.children.set(curr, new Node(curr)); node = node.children.get(curr); node.count = (node.count || 0) + 1; } } search(word, reverse, len = word.length, node = this.root) { for (let i = 0; i < len; i++) { const curr = word[reverse ? len - i - 1 : i]; node = node.children.get(curr); if (!node) return 0; } return node.count; } } function solution(words, queries) { const regEx = /\?/g; const [forward, backward, exceptions] = words.reduce(([f, b, e], word) => { const len = word.length; [f[len], b[len]] = [f[len] || new Trie(), b[len] || new Trie()]; f[len].insert(word, false, len); b[len].insert(word, true, len); e[len] = (e[len] || 0) + 1; return [f, b, e]; }, [{}, {}, {}]); return queries.map((query) => { const len = query.length; const str = query.replace(regEx, ''); if (!forward[len]) return 0; if (query[0] === '?' && query[len - 1] === '?') return exceptions[len]; if (query[0] === '?') return backward[len].search(str, true); return forward[len].search(str, false); }) } ================================================ FILE: programmers/난이도별/level04.단어_퍼즐/JeongShin.js ================================================ // DP를 이용한 풀이 function solution(strings, t) { const answer = []; answer[-1] = 0; const checkStr = (str, from, to) => { for (let i = from, j = 0; i <= to; i++, j++) { if (t[i] !== str[j]) return false; } return true; }; const getCount = (char, idx) => { let count = Infinity; for (const str of strings) { const len = str.length; if (str[len - 1] === char && checkStr(str, idx - len + 1, idx)) count = Math.min(answer[idx - len] + 1, count); } return count; }; const result = t.split('').reduce((answer, char, idx) => { answer.push(getCount(char, idx)); return answer; }, answer)[t.length - 1]; return result === Infinity ? -1 : result; } // solution(["ba", "na", "n", "a"], "banana") // solution(["app", "ap", "p", "l", "e", "ple", "pp"], "apple") /* * 처음 시도 했던 트라이를 이용한 풀이 * 효율성 테스트에서 불합격 ㅠㅠ 😥 * */ class TrieNode { constructor(key) { this.key = key; this.end = false; this.children = {}; } } function Trie() { this.root = new TrieNode(); this.insert = function (word, len = word.length) { let node = this.root; for (let i = 0; i < len; i++) { const curr = word[i]; if (!node.children[curr]) node.children[curr] = new TrieNode(curr); node = node.children[curr]; if (i === (len - 1)) node.end = true; } }; } function solution2(strings, t) { const trie = new Trie(); const target = t.length; let answer = Infinity; const find = (startIdx, weight) => { let node = trie.root; if (answer <= weight) return; if (startIdx === target) return answer = weight; for (let i = startIdx; i <= target; i++) { const curr = t[i]; if (node.children[curr]) { node = node.children[curr]; if (node.end) find(i + 1, weight + 1); continue; } return } }; for (const str of strings) trie.insert(str); find(0, 0); return answer !== Infinity ? answer : -1; } ================================================ FILE: programmers/난이도별/level04.무지의_먹방_라이브/JeongShin.js ================================================ function solution(food_times, k) { let foods = []; const len = food_times.length; food_times.forEach((v, i) => foods.push({time: v, index: i})); foods.sort((a, b) => a.time - b.time); const getNextIdx = (i, prevMin, height) => { while ((foods[i].time - prevMin) === height) { i++; if (i === len) return -1; } return i; }; let i = 0; let prevMin = 0; while (i < len) { const currMin = foods[i].time; const foodChunk = (currMin - prevMin) * (len - i); if ((k - foodChunk) < 0) break; k -= foodChunk; if ((i = getNextIdx(i, prevMin, currMin - prevMin)) < 0) return -1; prevMin = currMin; } foods = foods.splice(i); foods.sort((a,b)=> a.index - b.index); return foods[k % foods.length].index + 1; } console.log(solution([3, 5, 1, 6, 5, 4], 22)); ================================================ FILE: programmers/난이도별/level04.사칙연산/sangmandu.py ================================================ ''' https://programmers.co.kr/learn/courses/30/lessons/1843 사칙연산 1. 해당 식을 거꾸로 접근한다 2. -를 만날 때 마다, gain과 loss를 계산한다. 이 때, gain과 loss가 의미하는 바가 중요한데, gain은 모든 음수들을 양수로 만들었을 때의 이득을 의미하고 loss는 음수와 음수 사이에 있는 양수들을 모두 음수로 만들었을 떄의 손해를 의미한다. gain은 모든 음수들을 대상으로 하는데에 비해 loss가 음수와 음수 사이에 있는 양수들이 범위인 이유는 일단, 모든 양수들을 대상으로 하는 것은 최대값을 구하는 방향이 아니며, 음수와 음수 사이에 있지 않은 양수들은 굳이 음수화 될 필요가 없기 때문 3. 이 때 gain - loss 가 가장 큰 경우를 구한다. 이 때가 부호를 바꿨을 때 가장 큰 기댓값 이 때 기본 + 2 * 기댓값 ''' def solution(arr): signs = [1] values = [] for x in arr: if x == "+": signs.append(1) elif x == "-": signs.append(-1) else: values.append(int(x)) base = int(eval(''.join(arr))) n = len(values) loss = [0] * n gain = [0] * n l, g = 0, 0 for i in range(n - 1, -1, -1): if signs[i] == 1: l += values[i] else: loss[i] = l l = 0 gain[i] = g g += values[i] benefit = max([g - l for (g, l) in zip(gain, loss)]) return base + 2 * benefit ''' 정확성은 문제가 없었지만 효율성을 통과하기가 굉장히 어려웠던 문제 level4부터는 확실히 다른 것 같다. 근 한달간 쩔쩔 맸음. 지금까지 본 문제중에 제일 어려웠다. ''' ================================================ FILE: programmers/난이도별/level04.스티커_모으기/JeongShin.js ================================================ // dp 를 이용한 풀이 function solution(sticker) { const len = sticker.length; if (len < 3) return Math.max(...sticker); /* 첫번째 스티커를 뜯는 경우 */ const dp1 = [sticker[0], sticker[0]]; /* 첫번째 스티커를 뜯지 않는 경우 */ const dp2 = [0, sticker[1]]; let i; for (i = 2; i < len - 1; i++) { dp1[i] = Math.max(dp1[i - 2] + sticker[i], dp1[i - 1]); dp2[i] = Math.max(dp2[i - 2] + sticker[i], dp2[i - 1]); } // 마지막 스티커 처리 dp1[i] = Math.max(dp1[i - 1], dp1[i - 2]); dp2[i] = Math.max(dp2[i - 2] + sticker[i], dp2[i - 1]); return Math.max(dp1[i], dp2[i]); } solution([14, 6, 5, 11, 3, 9, 2, 10]) solution([1, 3, 2, 5, 4]) // 1) 분기와 한정 // branch and bound 풀이로 접근하면 bound 없이는 정확한 답은 구할 수 있음. // 하지만 2 ^ n 개의 노드를 생성하기 때문에 시간 복잡도가 극악이 됨. // bound 하는 과정에서 마음대로 bound 를 하게 되면 이 문제의 경우 // 첫 번째 인덱스의 요소가 마지막 요소에 영향을 주기 때문에 // bound 과정에서 원하지 않는 노드를 삭제하게 되는 문제가 생김. // 👉 다른 풀이로 접근 필요 class Node { constructor(w, p, f) { this.weight = w; this.possible = p; this.firstNodeUsed = f; } } function solution2(sticker) { const len = sticker.length; let stack = [], next = [], bound = 0; // Case 1. 첫번째 노드를 미사용 stack.push(new Node(0, true, false)); // Case 2. 첫째째 노드 사용 stack.push(new Node(sticker[0], false, true)); for (let i = 1; i < (len - 1); i++) { while (stack[0]) { const node = stack.pop(); if ((node.weight + sticker[i]) <= bound) continue; if (node.possible) { bound = node.weight; next.push(new Node(node.weight + sticker[i], false, node.firstNodeUsed)); } node.possible = true; next.push(node); } stack = next; next = []; } // 마지막 노드는 첫번째 노드 사용 여부에 따라 따로 처리 해준다. return stack.reduce((answer, currNode) => { if (!currNode.firstNodeUsed && currNode.possible) currNode.weight += sticker[len - 1]; return Math.max(currNode.weight, answer); }, 0); } // solution([14, 6, 5, 11, 3, 9, 2, 10]) // solution([1, 3, 2, 5, 4]) ================================================ FILE: programmers/난이도별/level04.올바른_괄호의_갯수/6047198844.py ================================================ ''' n = 1 => 1 '()' n = 2 => (1) / 1 '()()' => 2 n = 3 => (2) / 1*2-1, 2*1-1 / 1 '()()()' => 2 + 2 + 1 '()()()'=> 5 카탈랑수 ''' def solution(n): answer = 0 memo = [0] * (n + 1) # C_0 == 1 memo[0] = 1 for i in range(1, n + 1): for j in range(i): print(i, j, i - 1 - j) memo[i] += memo[j] * memo[i - 1 - j] print(memo) return memo[n] ================================================ FILE: programmers/난이도별/level04.올바른_괄호의_갯수/JeongShin.js ================================================ function solution(n) { const dp = new Array(n + 1).fill(0); dp[0] = 1; for (let i = 1; i <= n; i++) for (let j = 1; j <= i; j++) // F (i, n) = G (i-1) * G (n-i) dp[i] += dp[j - 1] * dp[i - j]; return dp[n]; } solution(3); ================================================ FILE: programmers/난이도별/level04.지형_이동/6047198844.py ================================================ import heapq import collections parent = list() def find(color): if color == parent[color]: return color else: p = find(parent[color]) parent[color] = p return p def union(color1, color2): color1 = find(color1) color2 = find(color2) if color1 != color2: parent[color2] = color1 return True return False def solution(land, height): answer = 0 N = len(land) area = [[-1 for i in range(N)] for j in range(N)] graph = set() color = 0 # 각 구간에 색깔을 칠해보자. for y in range(N): for x in range(N): if area[y][x] == -1: Q = [(y, x)] area[y][x] = color while Q: yy, xx = Q.pop() area[yy][xx] = color # bfs시작 for dy, dx in (-1, 0), (+1, 0), (0, -1), (0, +1): ny = yy + dy nx = xx + dx # 범위 체크 if 0 <= ny < N and 0 <= nx < N: color1 = area[ny][nx] color2 = area[yy][xx] weight = abs(land[ny][nx] - land[yy][xx]) if color1 == -1 and weight <= height: Q.append((ny, nx)) elif color1 != -1 and color1 != color2: graph.add((weight, color1, color2)) color += 1 global parent parent = [i for i in range(color)] graph = list(graph) heapq.heapify(graph) while graph: weight, color1, color2 = heapq.heappop(graph) if union(color1, color2): answer += weight return answer ================================================ FILE: programmers/난이도별/level04.지형_이동/JeongShin.js ================================================ // 2020. 08. 26 코드 복습 및 수정 const key = (i, j) => i + ',' + j; // params {number []} start : 시작 좌표 ex) [1,2] function bfs(land, visited, start, height, edges, idx) { const stack = [start]; while (stack[0]) { const [i, j] = stack.pop(), currHeight = land[i][j], k = key(i, j); visited.set(k, idx); [[i - 1, j], [i + 1, j], [i, j + 1], [i, j - 1]].forEach(([ni, nj]) => { const nk = key(ni, nj); // case 1 . land 배열을 벗어난 경우 skip if (!land[ni] || !land[ni][nj] || visited.has(nk)) return; // case 2. 방문 가능한 지역일 경우 visited 체크 후 stack 에 푸쉬 const heightDiff = Math.abs(currHeight - land[ni][nj]); if (heightDiff <= height) { visited.set(nk, idx); stack.push([ni, nj]); return; } // case 3. 방문 불가능한 지역일 경우 edges 에 푸쉬 edges.push({from: k, to: nk, weight: heightDiff}); }) } } function find(areas, child) { let parent = child; while (areas[parent].parent > 0) { parent = areas[parent].parent; } return parent; } function union(areas, p1, p2) { if (p1 === p2) return false; areas[p1].parent = p2; return true; } function solution(land, height) { const [row, col] = [land.length, land[0].length]; const visited = new Map(), areas = {}, edges = []; let answer = 0, idx = 0; for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { if (!visited.has(key(i, j))) { areas[++idx] = {idx: idx, parent: -1}; bfs(land, visited, [i, j], height, edges, idx); } } } edges.sort((a, b) => a.weight - b.weight); for (const edge of edges) { const [from, to] = [visited.get(edge.from), visited.get(edge.to)]; if (from === to) continue; answer += (union(areas, find(areas, from), find(areas, to)) * edge.weight); } return answer; } solution([[1, 4, 8, 10], [5, 5, 5, 5], [10, 10, 10, 10], [10, 10, 10, 20]], 3); ================================================ FILE: programmers/난이도별/level04.징검다리/6047198844.py ================================================ def solution(distance, rocks, n): answer = 0 rocks.sort() # 정답의 범위 begin = 0 end = distance # print(rocks) while begin <= end: # 우리가 목표하는 거리 mid = (begin + end) // 2 # 현재 남아있는 바위의 위치 stack = [0] for rock in rocks: # 현재 거리와 stack위의 rock거리를 비교 between = rock - stack[-1] if between < mid: # 제거해야한다.-> stack에 넣지 않는다. continue stack.append(rock) # 마지막돌과 도착지점의 거리를 계산한다. # 해당 거리가 우리가 목표하는바 보다 작다면 해당 돌을 제거한다. last_distance = distance - stack[-1] if last_distance < mid: stack.pop() stack.append(distance) min_distance = distance # 돌간 최소거리 for idx in range(1, len(stack)): min_distance = min(min_distance, stack[idx] - stack[idx - 1]) # 삭제한 돌의 개수 (출발지점은 제외함) del_rock_n = len(rocks) - (len(stack) - 2) if del_rock_n <= n: # 삭제한 돌이 N보다 작은경우 -> 거리가 짧으므로 거리를 늘린다. # 삭제한 돌이 N인경우 -> 정답 갱신 answer = max(answer, min_distance) begin = mid + 1 # 삭제한 돌이 N보다 큰경우 -> 거리가 기므로 거리를 좁힌다. else: end = mid - 1 return answer ================================================ FILE: programmers/난이도별/level04.징검다리/JeongShin.java ================================================ package programmers.난이도별.level04.징검다리; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; class Solution { public boolean checkPossible(List rocksList, int min, int len, int n) { int removed = 0; int prev = 0; for (int curr : rocksList) { int distance = curr - prev; if (distance < min) removed++; prev = distance < min ? prev : curr; if (removed > n) return false; } return true; } public int solution(int distance, int[] rocks, int n) { List rocksList = IntStream.range(0, rocks.length) .map(i -> rocks[i]) .sorted() .boxed() .collect(Collectors.toList()); int answer = 0; int low = 1; int high = distance; int size = rocksList.size(); while (low <= high) { int mid = (high + low) / 2; if (checkPossible(rocksList, mid, size, n)) { answer = mid; low = mid + 1; continue; } high = mid - 1; } return answer; } } ================================================ FILE: programmers/난이도별/level04.징검다리/JeongShin.js ================================================ function solution(distance, rocks, n) { rocks.push(distance); rocks.sort((a, b) => a - b); const isPossible = (min) => { let [removed, prev] = [0, 0]; for (const curr of rocks) { const currDistance = curr - prev; removed += currDistance < min; prev = currDistance < min ? prev : curr; if (removed > n) return false; } return true; }; const binSearch = () => { let [left, mid, right] = [1, undefined, distance]; let answer; while (left <= right) { mid = ~~((left + right) / 2); const result = isPossible(mid); if (result) { answer = mid; left = mid + 1; continue; } right = mid - 1; } return answer; }; return binSearch(); } solution(25, [2, 14, 11, 21, 17], 2) ================================================ FILE: programmers/난이도별/level04.호텔_방_배정/JeongShin.java ================================================ package programmers.난이도별.level04.호텔_방_배정; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; class Solution { public long find(Map rooms, long num) { Long parent = rooms.get(num); if (parent == null) { rooms.put(num, num + 1); return num; } parent = find(rooms, parent); rooms.put(num, parent); return parent; } public long[] solution(long k, long[] room_number) { Map rooms = new HashMap(); return IntStream.range(0, room_number.length) .mapToLong(i -> find(rooms, room_number[i])) .toArray(); } } ================================================ FILE: programmers/난이도별/level04.호텔_방_배정/JeongShin.js ================================================ function solution(k, room_number) { const room = new Map(); const findAndUnion = (n) => { // find if (!room.has(n)) { room.set(n, n + 1); return n; } let parent = findAndUnion(room.get(n)); // union room.set(n, parent + 1); return parent; }; return room_number.reduce((answer, roomRequest) => { answer.push(findAndUnion(roomRequest)); return answer; }, []) } /* 효율성 테스트 케이스 3개 불합격 */ function solution2(k, room_number) { const room = {}; const findAndUnion = n => { let curr = room[n], prev; while (curr.using) { prev = curr; curr = room[curr.parent]; prev.parent = curr.parent; } // prev.forEach((v)=> room[v].parent = curr.parent); return curr.idx; }; // 여기서 모든 방에 대해서 부모를 설정할 필요가 없음. for (let i = 1; i <= k; i++) { room[i] = {idx : i, using: false, parent: i + 1}; } return room_number.map((n)=>{ if (room[n].using) n = findAndUnion(n); room[n].using = true; return n; }) } console.log(solution(10, [1, 3, 4, 1, 3, 1])); ================================================ FILE: programmers/난이도별/remove_spacebar.py ================================================ import os, re path = os.getcwd() for i in os.listdir(os.getcwd()): print(i) ori = i i = i.replace(' ', '_') print(i) print(path+'/'+ori, path+'/'+i) os.rename(path+'/'+ori, path+'/'+i) ================================================ FILE: programmers/네이버_2020_아폴로_챌린지/junilhwang/1.js ================================================ function solution(table) { const max = table[0].length; const tableOf = table.map(v => [ ...v ].reduce((arr, acc, key) => { if (acc === 'O') arr.push(key); return arr; }, [])); let min = Infinity; const f = (set, stack) => { if (stack.length > min) return; if (set.size === max) { min = Math.min(min, stack.length); return; } tableOf.forEach((v, k) => { if (stack.includes(k)) return; f(new Set([ ...set, ...v]), [ ...stack, k ]); }) } f(new Set, []); return min; } console.log( solution(["XOXO", "OXXO", "XXOX", "XOOO"]), 2, solution(["OXXO", "XOXO", "XXOO"]), 3, solution(["OXOXO", "OOOOO", "XOXOX"]), 1, ) ================================================ FILE: programmers/네이버_2020_아폴로_챌린지/junilhwang/2.js ================================================ function solution(h, w, n, board) { const boardOf = board.map(str => [ ...str ].map(Number)); let cnt = 0; for (let j = 0; j < h; j++) { let next = 0; for (let i = 0; i < w; i++) { if (boardOf[j][i] === 0) { if (next === n) cnt += 1; next = 0; continue; } next += 1; } if (next === n) cnt += 1; } for (let i = 0; i < w; i++) { let next = 0; for (let j = 0; j < h; j++) { if (boardOf[j][i] === 0) { if (next === n) cnt += 1; next = 0; continue; } next += 1; } if (next === n) cnt += 1; } const memo1 = {} const memo2 = {} const fn1 = (x, y) => { if (memo1[`${x},${y}`]) return; let next = 0; for (let i = x, j = y; i < w && j < h; i++, j++) { memo1[`${i},${j}`] = true; if (boardOf[j][i] === 0) { if (next === n) cnt += 1; next = 0; break; } next += 1; } if (next === n) cnt += 1; } const fn2 = (x, y) => { if (memo2[`${x},${y}`]) return; let next = 0; for (let i = x, j = y; i > -1 && j < h; i--, j++) { memo2[`${i},${j}`] = true; if (boardOf[j][i] === 0) { if (next === n) cnt += 1; next = 0; break; } next += 1; } if (next === n) cnt += 1; } // 대각선 검사 for (let i = 0; i < h; i++) { let before = 0; let next = 0; for (let j = 0; j < w; j++) { if (boardOf[i][j] === 0) continue; fn1(j, i); fn2(j, i); } } return cnt; } console.log( solution(7, 9, 4, ["111100000","000010011","111100011","111110011","111100011","111100010","111100000"]), 10, solution(5, 5, 5, ["11111","11111","11111","11111","11111"]), 12, ) // 1 1 1 1 1 // 1 1 1 1 1 // 1 1 1 1 1 // 1 1 1 1 1 // 1 1 1 1 1 ================================================ FILE: programmers/네이버_2020_아폴로_챌린지/junilhwang/3.js ================================================ function solution(play_list, listen_time) { let max = 0; const maxListenTime = play_list.reduce((a, b) => a+ b); if (maxListenTime <= listen_time) return play_list.length; const time = Math.min(maxListenTime, listen_time); for (let i = 0, len = play_list.length; i < len; i++) { let cnt = 1; let n = time - 1; for (let j = i + 1; j < len && n > 0; j++) { const v = play_list[j]; if (n >= 1) { n -= v; cnt += 1; } } for (let j = 0; j < len && n > 0 && cnt < len; j++) { const v = play_list[j]; if (n >= 1) { n -= v; cnt += 1; } } max = Math.min(Math.max(cnt, max), len); if (max === len) break; } return max; } console.log( solution([2, 3, 1, 4],3) == 3, solution([1, 2, 3, 4],5) == 4, solution([1, 2, 3, 4],20) === 4, ) ================================================ FILE: programmers/네이버_2020_아폴로_챌린지/junilhwang/report.20200920.150349.9360.0.001.json ================================================ { "header": { "reportVersion": 2, "event": "Allocation failed - JavaScript heap out of memory", "trigger": "FatalError", "filename": "report.20200920.150349.9360.0.001.json", "dumpEventTime": "2020-09-20T15:03:49Z", "dumpEventTimeStamp": "1600581829423", "processId": 9360, "threadId": null, "cwd": "D:\\projects\\DKU-STUDY\\Algorithm\\programmers\\네이버_2020_아폴로_챌린지\\junilhwang", "commandLine": [ "D:\\nodejs\\node.exe", "D:\\projects\\DKU-STUDY\\Algorithm\\programmers\\네이버_2020_아폴로_챌린지\\junilhwang\\3.js" ], "nodejsVersion": "v13.9.0", "wordSize": 64, "arch": "x64", "platform": "win32", "componentVersions": { "node": "13.9.0", "v8": "7.9.317.25-node.28", "uv": "1.34.2", "zlib": "1.2.11", "brotli": "1.0.7", "ares": "1.15.0", "modules": "79", "nghttp2": "1.40.0", "napi": "5", "llhttp": "2.0.4", "openssl": "1.1.1d", "cldr": "36.0", "icu": "65.1", "tz": "2019c", "unicode": "12.1" }, "release": { "name": "node", "headersUrl": "https://nodejs.org/download/release/v13.9.0/node-v13.9.0-headers.tar.gz", "sourceUrl": "https://nodejs.org/download/release/v13.9.0/node-v13.9.0.tar.gz", "libUrl": "https://nodejs.org/download/release/v13.9.0/win-x64/node.lib" }, "osName": "Windows_NT", "osRelease": "10.0.18362", "osVersion": "Windows 10 Pro", "osMachine": "x86_64", "cpus": [ { "model": "Intel(R) Core(TM) i5-3570 CPU @ 3.40GHz", "speed": 3392, "user": 17467906, "nice": 0, "sys": 8386718, "idle": 73685671, "irq": 1543531 }, { "model": "Intel(R) Core(TM) i5-3570 CPU @ 3.40GHz", "speed": 3392, "user": 18460937, "nice": 0, "sys": 7941890, "idle": 73137203, "irq": 768078 }, { "model": "Intel(R) Core(TM) i5-3570 CPU @ 3.40GHz", "speed": 3392, "user": 19391656, "nice": 0, "sys": 6040968, "idle": 74107406, "irq": 77953 }, { "model": "Intel(R) Core(TM) i5-3570 CPU @ 3.40GHz", "speed": 3392, "user": 17433468, "nice": 0, "sys": 6053531, "idle": 76053031, "irq": 66734 } ], "networkInterfaces": [ { "name": "vEthernet (Default Switch)", "internal": false, "mac": "00:15:5d:7b:1d:db", "address": "fe80::656c:e16a:f730:15d2", "netmask": "ffff:ffff:ffff:ffff::", "family": "IPv6", "scopeid": 24 }, { "name": "vEthernet (Default Switch)", "internal": false, "mac": "00:15:5d:7b:1d:db", "address": "172.17.218.113", "netmask": "255.255.255.240", "family": "IPv4" }, { "name": "이더넷", "internal": false, "mac": "d0:27:88:c6:da:dc", "address": "fe80::2418:835b:405:d19b", "netmask": "ffff:ffff:ffff:ffff::", "family": "IPv6", "scopeid": 8 }, { "name": "이더넷", "internal": false, "mac": "d0:27:88:c6:da:dc", "address": "49.172.41.50", "netmask": "255.255.255.0", "family": "IPv4" }, { "name": "VirtualBox Host-Only Network #4", "internal": false, "mac": "0a:00:27:00:00:04", "address": "fe80::848d:46e7:9e50:90df", "netmask": "ffff:ffff:ffff:ffff::", "family": "IPv6", "scopeid": 4 }, { "name": "VirtualBox Host-Only Network #4", "internal": false, "mac": "0a:00:27:00:00:04", "address": "192.168.56.1", "netmask": "255.255.255.0", "family": "IPv4" }, { "name": "VirtualBox Host-Only Network #5", "internal": false, "mac": "0a:00:27:00:00:06", "address": "fe80::b919:e650:5d58:f8c8", "netmask": "ffff:ffff:ffff:ffff::", "family": "IPv6", "scopeid": 6 }, { "name": "VirtualBox Host-Only Network #5", "internal": false, "mac": "0a:00:27:00:00:06", "address": "192.168.99.1", "netmask": "255.255.255.0", "family": "IPv4" }, { "name": "Loopback Pseudo-Interface 1", "internal": true, "mac": "00:00:00:00:00:00", "address": "::1", "netmask": "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "family": "IPv6", "scopeid": 0 }, { "name": "Loopback Pseudo-Interface 1", "internal": true, "mac": "00:00:00:00:00:00", "address": "127.0.0.1", "netmask": "255.0.0.0", "family": "IPv4" } ], "host": "DESKTOP-7JAVF7Q" }, "javascriptStack": { "message": "No stack.", "stack": [ "Unavailable." ] }, "nativeStack": [ { "pc": "0x00007ff72f1a2399", "symbol": "std::basic_ostream >::operator<<+11561" }, { "pc": "0x00007ff72f1a6849", "symbol": "std::basic_ostream >::operator<<+29145" }, { "pc": "0x00007ff72f1a56c8", "symbol": "std::basic_ostream >::operator<<+24664" }, { "pc": "0x00007ff72f2cab12", "symbol": "v8::base::CPU::has_sse+60434" }, { "pc": "0x00007ff72faf721e", "symbol": "v8::Isolate::ReportExternalAllocationLimitReached+94" }, { "pc": "0x00007ff72fade971", "symbol": "v8::SharedArrayBuffer::Externalize+785" }, { "pc": "0x00007ff72f9a59cc", "symbol": "v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1468" }, { "pc": "0x00007ff72f9c388c", "symbol": "v8::internal::Factory::NewFixedArrayWithFiller+60" }, { "pc": "0x00007ff72f9cf080", "symbol": "v8::internal::Factory::NewUninitializedFixedArray+64" }, { "pc": "0x00007ff72f89d00c", "symbol": "v8::debug::Script::GetIsolate+7628" }, { "pc": "0x00007ff72f7450ba", "symbol": "v8::internal::interpreter::JumpTableTargetOffsets::iterator::operator=+163002" }, { "pc": "0x00007ff72ff40b6d", "symbol": "v8::internal::SetupIsolateDelegate::SetupHeap+517453" }, { "pc": "0x00000365cbec31f0", "symbol": "" } ], "javascriptHeap": { "totalMemory": 2730844160, "totalCommittedMemory": 2730844160, "usedMemory": 2695532976, "availableMemory": 17021864, "memoryLimit": 2197815296, "heapSpaces": { "read_only_space": { "memorySize": 262144, "committedMemory": 262144, "capacity": 33040, "used": 33040, "available": 0 }, "new_space": { "memorySize": 33554432, "committedMemory": 33554432, "capacity": 16758784, "used": 0, "available": 16758784 }, "old_space": { "memorySize": 2240512, "committedMemory": 2240512, "capacity": 1657016, "used": 1393936, "available": 263080 }, "code_space": { "memorySize": 430080, "committedMemory": 430080, "capacity": 154560, "used": 154560, "available": 0 }, "map_space": { "memorySize": 528384, "committedMemory": 528384, "capacity": 199440, "used": 199440, "available": 0 }, "large_object_space": { "memorySize": 1791266816, "committedMemory": 1791266816, "capacity": 1791238336, "used": 1791238336, "available": 0 }, "code_large_object_space": { "memorySize": 49152, "committedMemory": 49152, "capacity": 2784, "used": 2784, "available": 0 }, "new_large_object_space": { "memorySize": 902512640, "committedMemory": 902512640, "capacity": 902510880, "used": 902510880, "available": 0 } } }, "resourceUsage": { "userCpuSeconds": 2.718, "kernelCpuSeconds": 0.843, "cpuConsumptionPercent": 118.7, "maxRss": 2743500800, "pageFaults": { "IORequired": 675371, "IONotRequired": 0 }, "fsActivity": { "reads": 2, "writes": 6 } }, "libuv": [ ], "workers": [ ], "environmentVariables": { "=::": "::\\", "=D:": "D:\\", "ALLUSERSPROFILE": "C:\\ProgramData", "APPDATA": "C:\\Users\\junil\\AppData\\Roaming", "BREAKPAD_DUMP_LOCATION": "C:\\Program Files (x86)\\Google\\Chrome", "COLORTERM": "true", "CommonProgramFiles": "C:\\Program Files\\Common Files", "CommonProgramFiles(x86)": "C:\\Program Files (x86)\\Common Files", "CommonProgramW6432": "C:\\Program Files\\Common Files", "COMPOSE_CONVERT_WINDOWS_PATHS": "true", "COMPUTERNAME": "DESKTOP-7JAVF7Q", "ComSpec": "C:\\WINDOWS\\system32\\cmd.exe", "DEBUG_COLORS": "true", "DOCKER_CERT_PATH": "C:\\Users\\junil\\.docker\\machine\\machines\\default", "DOCKER_HOST": "tcp://192.168.99.100:2376", "DOCKER_MACHINE_NAME": "default", "DOCKER_TLS_VERIFY": "1", "DOCKER_TOOLBOX_INSTALL_PATH": "D:\\Docker Toolbox", "DriverData": "C:\\Windows\\System32\\Drivers\\DriverData", "FORCE_COLOR": "true", "FPS_BROWSER_APP_PROFILE_STRING": "Internet Explorer", "FPS_BROWSER_USER_PROFILE_STRING": "Default", "HOMEDRIVE": "C:", "HOMEPATH": "\\Users\\junil", "IDEA_INITIAL_DIRECTORY": "C:\\Program Files\\JetBrains\\IntelliJ IDEA 2019.2.4\\jbr\\bin", "IntelliJ IDEA": "C:\\Program Files\\JetBrains\\IntelliJ IDEA 2019.2.4\\bin;", "JAVA_HOME": "C:\\Program Files\\Java\\jdk1.8.0_161", "JRE_HOME": "C:\\Program Files\\Java\\jre1.8.0_161", "LOCALAPPDATA": "C:\\Users\\junil\\AppData\\Local", "LOGONSERVER": "\\\\DESKTOP-7JAVF7Q", "MOCHA_COLORS": "1", "MOZ_DISABLE_OOP_PLUGINS": "1", "NO_PROXY": "192.168.99.100", "npm_config_color": "always", "NUMBER_OF_PROCESSORS": "4", "OneDrive": "C:\\Users\\junil\\OneDrive", "OS": "Windows_NT", "PASSWORD": "P@ssw0rd!", "Path": "D:\\xampp\\php;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program Files\\PowerShell\\6\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\NVIDIA Corporation\\NVIDIA NvDLISR;D:\\nodejs\\;C:\\Program Files\\Git\\cmd;C:\\Users\\junil\\AppData\\Local\\Programs\\Python\\Python37\\Scripts\\;C:\\Users\\junil\\AppData\\Local\\Programs\\Python\\Python37\\;C:\\Ruby23\\bin;C:\\Users\\junil\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Program Files\\Java\\jdk1.8.0_131\\bin;C:\\Program Files\\Java\\jdk1.8.0_161\\bin;C:\\Python27;C:\\Python27\\Scripts;C:\\Program Files\\Java\\jdk1.8.0_161;C:\\Users\\junil\\AppData\\Local\\Programs\\Microsoft VS Code\\bin;D:\\xampp\\php;C:\\Program Files\\JetBrains\\IntelliJ IDEA 2019.2.4\\bin;;C:\\Users\\junil\\AppData\\Roaming\\npm;D:\\Docker Toolbox;D:\\Docker Toolbox", "PATHEXT": ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC", "PROCESSOR_ARCHITECTURE": "AMD64", "PROCESSOR_IDENTIFIER": "Intel64 Family 6 Model 58 Stepping 9, GenuineIntel", "PROCESSOR_LEVEL": "6", "PROCESSOR_REVISION": "3a09", "ProgramData": "C:\\ProgramData", "ProgramFiles": "C:\\Program Files", "ProgramFiles(x86)": "C:\\Program Files (x86)", "ProgramW6432": "C:\\Program Files", "PSModulePath": "C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules", "PUBLIC": "C:\\Users\\Public", "SESSIONNAME": "Console", "SystemDrive": "C:", "SystemRoot": "C:\\WINDOWS", "TEMP": "C:\\Users\\junil\\AppData\\Local\\Temp", "TMP": "C:\\Users\\junil\\AppData\\Local\\Temp", "USERDOMAIN": "DESKTOP-7JAVF7Q", "USERDOMAIN_ROAMINGPROFILE": "DESKTOP-7JAVF7Q", "USERNAME": "junil", "USERPROFILE": "C:\\Users\\junil", "VBOX_MSI_INSTALL_PATH": "C:\\Program Files\\Oracle\\VirtualBox\\", "windir": "C:\\WINDOWS" }, "sharedObjects": [ "D:\\nodejs\\node.exe", "C:\\WINDOWS\\SYSTEM32\\ntdll.dll", "C:\\WINDOWS\\System32\\KERNEL32.DLL", "C:\\WINDOWS\\System32\\KERNELBASE.dll", "C:\\WINDOWS\\System32\\WS2_32.dll", "C:\\WINDOWS\\System32\\RPCRT4.dll", "C:\\WINDOWS\\System32\\PSAPI.DLL", "C:\\WINDOWS\\System32\\ADVAPI32.dll", "C:\\WINDOWS\\System32\\msvcrt.dll", "C:\\WINDOWS\\System32\\sechost.dll", "C:\\WINDOWS\\System32\\USER32.dll", "C:\\WINDOWS\\System32\\win32u.dll", "C:\\WINDOWS\\System32\\GDI32.dll", "C:\\WINDOWS\\System32\\gdi32full.dll", "C:\\WINDOWS\\System32\\msvcp_win.dll", "C:\\WINDOWS\\SYSTEM32\\dbghelp.dll", "C:\\WINDOWS\\System32\\ucrtbase.dll", "C:\\WINDOWS\\System32\\CRYPT32.dll", "C:\\WINDOWS\\System32\\MSASN1.dll", "C:\\WINDOWS\\System32\\bcrypt.dll", "C:\\WINDOWS\\SYSTEM32\\USERENV.dll", "C:\\WINDOWS\\System32\\profapi.dll", "C:\\WINDOWS\\SYSTEM32\\IPHLPAPI.DLL", "C:\\WINDOWS\\SYSTEM32\\WINMM.dll", "C:\\WINDOWS\\SYSTEM32\\WINMMBASE.dll", "C:\\WINDOWS\\System32\\cfgmgr32.dll", "C:\\WINDOWS\\System32\\bcryptPrimitives.dll", "C:\\WINDOWS\\System32\\IMM32.DLL", "C:\\WINDOWS\\System32\\powrprof.dll", "C:\\WINDOWS\\System32\\UMPDC.dll", "C:\\WINDOWS\\SYSTEM32\\CRYPTBASE.DLL", "C:\\WINDOWS\\system32\\uxtheme.dll", "C:\\WINDOWS\\System32\\combase.dll", "C:\\WINDOWS\\system32\\mswsock.dll", "C:\\WINDOWS\\System32\\kernel.appcore.dll", "C:\\WINDOWS\\System32\\NSI.dll", "C:\\WINDOWS\\SYSTEM32\\dhcpcsvc6.DLL", "C:\\WINDOWS\\SYSTEM32\\dhcpcsvc.DLL", "C:\\WINDOWS\\SYSTEM32\\DNSAPI.dll", "C:\\WINDOWS\\system32\\napinsp.dll", "C:\\WINDOWS\\system32\\pnrpnsp.dll", "C:\\WINDOWS\\System32\\winrnr.dll", "C:\\WINDOWS\\system32\\NLAapi.dll", "C:\\WINDOWS\\system32\\wshbth.dll" ] } ================================================ FILE: programmers/부스트캠프/boost1.py ================================================ def solution(name_list): for i in range (len(name_list)): for j in range (i+1, len(name_list)): if(name_list[i]==name_list[j]): return True elif(len(name_list[i]) 1) return true; } } return false; } console.log( solution(['가을', '우주', '너굴']) === false, solution(['봄', '여울', '봄봄']) === true, solution(['너굴', '너울', '여울', '서울'], ) === false, ); ================================================ FILE: programmers/부스트캠프/eyabc_1_2.js ================================================ function solution (arrayA, arrayB) { const ASet = arrayA.reduce((arr, v) => { if (arr.indexOf(v) === -1) arr.push(v); return arr; }, []); const BSet = arrayB.reduce((arr, v) => { if (arr.indexOf(v) === -1) arr.push(v); return arr; }, []); const sum = ASet.reduce((arr, v) => { if (arr.indexOf(v) === -1) arr.push(v); return arr; }, [...BSet]); const diff = BSet.reduce((arr, v) => { const idx = arr.indexOf(v); if (idx !== -1) { arr.splice(idx, 1); } ; return arr; }, [...ASet]); const same = BSet.reduce((arr, v) => { const idx = ASet.indexOf(v); if (idx !== -1) { arr.push(v); } ; return arr; }, []); return [ASet.length, BSet.length, sum.length, diff.length, same.length]; } // '[a의 set, b의 셋, ab 합,ab 차, ab교]'; console.log( solution([1, 2, 3, 2], [1, 3]), solution([2, 3, 4, 3, 5], [1, 6, 7]), ); ================================================ FILE: programmers/부스트캠프/eyabc_2_1.js ================================================ const keyboard = [['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'], ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'], ['Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '?']]; function solution (word) { let answer = ''; const keyLen = keyboard.length; const wordArr = word.split(''); let nowIdx = [0, 0]; const inputIndex = wordArr.map(char => { for (let i = 0 ; i < keyLen ; i++) { const res = keyboard[i].indexOf(char); if (res !== -1) return [i, res]; } }); const actionX = (diff) => diff < 0 ? '_' : '^'; const actionY = (diff) => diff < 0 ? '>' : '<'; inputIndex.forEach(idx => { const [diffX, diffY] = [ nowIdx[0] - idx[0], nowIdx[1] - idx[1], ]; answer = answer + actionX(diffX).repeat(Math.abs(diffX)) + actionY(diffY).repeat(Math.abs(diffY)) + '@'; nowIdx = idx; }); return answer; } ================================================ FILE: programmers/부스트캠프/eyabc_2_2.js ================================================ const graph = [ [0, 1, 2, 0, 0, 4, 0, 0, 0, 0, 0], [0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2], [0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ]; const dic = { 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, }; let end; const ans = []; const action = (nowIdx, cnt) => { if (nowIdx === end) { ans.push(cnt + 1); return; } graph[nowIdx].forEach((v, k) => { if (v !== 0 && k <= end) { cnt++; action(k, cnt); }; }); return; }; function solution (origin, dest) { if (origin === dest) return [0]; const nowIdx = dic[origin]; end = dic[dest]; action(nowIdx, 0); return ans.length ? ans : [-1]; } ================================================ FILE: programmers/썸머코딩_2020/아름다운연도/JunilHwang.java ================================================ package programmers.썸머코딩_2020.아름다운연도; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class JunilHwang { public static int solution(int p) { for(int answer = p + 1; answer < 100000; answer++){ String years = Integer.toString(answer); Set set = new HashSet(years.chars().boxed().collect(Collectors.toList())); if (set.size() == years.length()) return answer; } return -1; } public static void main(String[] args){ System.out.println(solution(1989) == 2013); System.out.println(solution(2015) == 2016); } } ================================================ FILE: programmers/썸머코딩_2020/아름다운연도/pul8219.java ================================================ package programmers.썸머코딩_2020.아름다운연도; import java.util.HashSet; import java.util.Set; import java.util.Iterator; public class pul8219 { public static void main(String[] args){ int p = 1989; Solution s = new Solution(); System.out.println(s.solution(p)); } public static class Solution { public int solution(int p) { int answer = 0; Set set = new HashSet<>(); answer = p + 1; for(;; answer++){ set.clear(); String a_str = Integer.toString(answer); int[] a_arr = new int[a_str.length()]; for(int i = 0; i < a_str.length(); i++){ a_arr[i] = a_str.charAt(i) - '0'; set.add(a_arr[i]); } //Iterator it = set.iterator(); if(set.size() != 4) continue; else if(set.size() == 4){ // while(it.hasNext()) // System.out.println("set: " + it.next()); break; } } //System.out.println(answer); return answer; } } } ================================================ FILE: programmers/쏘카/2.js ================================================ function solution(drum) { const rows = drum.length; const cols = drum[0].length; let count = 0; for (let i = 0; i < cols; i++) { let x = i; let y = 0; let breakCount = 0; while (y < cols) { const point = drum[y][x] if (point === '*') { breakCount += 1; y += 1; if (breakCount === 2) break; } switch (point) { case '#' : y += 1; break; case '>' : x += 1; break; case '<' : x -= 1; break; } } if (y === cols) count += 1; } return count; } console.log( solution(["######",">#*###","####*#","#<#>>#",">#*#*<","######"]) === 4 ) ================================================ FILE: programmers/쏘카/3.js ================================================ function solution(r, delivery) { const memo = new Map(); const maxTime = delivery.reduce((max, [time]) => Math.max(max, time), 0); let max = 0; const f = ([x, y], path, sumTip, time) => { if (time >= maxTime) { max = Math.max(sumTip, max); return } const nextPoints = [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]; const before = path[path.length - 2]; for (const [nextX, nextY] of nextPoints) { if (`${nextX},${nextY}` === before) continue; if (nextX >= r || nextX < 0 || nextY >= r || nextY < 0) continue; const [limit, tip] = delivery[nextY * r + nextX]; const addTip = time <= limit && path.indexOf(`${nextX},${nextY}`) === -1 ? tip : 0; f([nextX, nextY], [ ...path, `${nextX},${nextY}` ],sumTip + addTip, time + 1); } } f([0, 0], ['0,0'], delivery[0][1], 0); return max } console.log( solution(3, [[1, 5],[8, 3],[4, 2],[2, 3],[3, 1],[3, 2],[4, 2],[5, 2],[4, 1]]) === 17, solution(4, [[1,10],[8, 1],[8, 1],[3, 100],[8, 1],[8, 1],[8, 1],[8, 1],[8, 1],[8, 1],[8, 1],[8, 1],[9, 100],[8, 1],[8, 1],[8, 1]]) === 217 ) ================================================ FILE: programmers/우아한캠프 2020 상반기/eyabc_01.js ================================================ function solution(A) { if(A.length === 1) return 1; let res = 1; const f = (arr) => { let curr = arr[0]; const len = arr.length; let cnt = 0; const newArr = []; for(let i = 0 ; i < len + 1 ; i++) { if(curr === arr[i]) cnt++; else { curr = arr[i]; newArr.push(cnt); cnt = 1; } } res++; if (newArr.length === 1) return; f([...newArr]) }; f([...A]); return res; } console.log( solution([1, 1, 3, 3, 2, 2, 4, 5, 1, 1, 1, 3, 3, 3] ) === 6, solution([1,2,3] ) === 3, solution([2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 2, 1, 2] ) === 5, solution([2] ) === 1, ) ================================================ FILE: programmers/우아한캠프 2020 상반기/eyabc_02.js ================================================ function solution (arr) { const res = arr.map(v => [...(v+'')].sort((a, b) => a -b).join('') ); return new Set(res).size; } console.log( solution([112, 1814, 121, 1481, 1184])=== 2, solution([123, 456, 789, 321, 654, 987])=== 3, solution([1, 2, 3, 1, 2, 3, 4])=== 4, solution([123, 234, 213, 432, 234, 1234, 2341, 12345, 324])=== 4, ) ================================================ FILE: programmers/우아한캠프 2020 상반기/eyabc_03.js ================================================ function solution (regs) { const account = []; const action = ([action, id, value]) => { const target = account.find(v => v.id === id); switch (action) { case 'DEPOSIT': return DEPOSIT(id, value, target); case 'CREATE': return CREATE(id, value, target); case 'WITHDRAW': return WITHDRAW(id, value, target); } }; const CREATE = (id, max, target) => { if (target) return 403; account.push({ id, value: 0, max: ~~max }); return 200; }; const DEPOSIT = (id, value, target) => { if (target) { target.value += ~~value; return 200; } return 404; }; const WITHDRAW = (id, value, target) => { if (target) { if (value > target.max) return 403; target.value -= ~~value; target.max -= ~~value; return 200; } return 404; }; return regs.map(v => action(v.split(' '))); } console.log( solution(['DEPOSIT 3a 10000', 'CREATE 3a 300000', 'WITHDRAW 3a 150000', 'WITHDRAW 3a 150001']), // .toString() === [404, 200, 200, 403].toString(), solution(['CREATE 3a 10000', 'CREATE 3a 20000', 'CREATE 2bw 30000']).toString() === [200, 403, 200].toString(), ); ================================================ FILE: programmers/위메프202006/1/eyabc.js ================================================ function solution (N, M, map) { let max = 0; const f = ([x, y], bag) => { console.log({x, y, bag}); if (x < N - 1 && y < M - 1 ) { f([x + 1, y], bag + map[x][y]); f([x, y + 1], bag + map[x][y]); } else if (x === N - 1 && y < M - 1) { f([x, y + 1], bag + map[x][y + 1]); } else if (y === M - 1 && x < N - 1) { f([x + 1, y], bag + map[x + 1][y]); } max = Math.max(bag, max); return; }; f([0, 0], map[0][0]); return max; } console.log(solution(1, 2, [[0, 1]]) === 1); console.log(solution(3, 3, [[2,0,0],[2,0,0],[2,2,2]]) === 10) ================================================ FILE: programmers/위메프202006/2/eyabc.js ================================================ function solution(N, M, arr) { let min = Infinity; const pos = arr.reduce((pos, v, x) => { v.forEach((w, y) => { if (w) pos.push([x, y]); }); return pos; }, []); if (pos.length < 2) return 0.0; for (let i = 0; i < pos.length; i++) { for (let j = i + 1; j < pos.length; j++) { const dist = +Math.sqrt((pos[i][0] - pos[j][0])**2 + (pos[i][1] - pos[j][1])**2).toFixed(2); if (min > dist) min = dist; } } return min; } console.log(solution(3, 4, [[1,0,0,0],[0,0,0,0],[0,0,0,1]]) === 3.61); console.log(solution(3, 4, [[1,1,0,0],[0,0,0,0],[0,0,0,1]]) === 1.0); ================================================ FILE: programmers/위메프202006/3/eyabc.js ================================================ function solution (N, M, map) { var answer = ''; let index const f = ([x, y], space) => { console.log(space) if (map[x][y] === "*") return space; space.push(map[x][y]); f([x+1, y], space) f([x, y+1], space) }; console.log(f([0, 0], [])); } console.log(solution(5, 7, ['--*AB**', 'AB*A*BA', 'B*-A*BB', '*-A*A**', 'BC*BC*C']) === 'A5B5C1'); console.log(solution(9, 6, ['*****Z', '******', 'HH-I*A', '**IH*B', 'C*-***', 'C**---', 'CAZBBA', 'ZZ****', '***F**']) === 'A1B0C3F1H3I0Z1'); ================================================ FILE: programmers/위메프202006/4/eyabc.js ================================================ function solution(text) { const bracketStack = []; const textStack = {}; const openReg = /\(|\{|\[/; const closeReg = /\)|\}|\]/; text = text.replace(/ /g, ""); for(let i = 0 ; i < text.length; i++) { if (openReg.test(text[i])) bracketStack.push(text[i]); else if (closeReg.test(text[i])) { textStack[bracketStack.length] += " "; bracketStack.pop(); } else { if (textStack[bracketStack.length]) { textStack[bracketStack.length] += text[i] } else textStack[bracketStack.length] = text[i] } } return Object.values(textStack).reverse() .join(',').trim() .replace(/ /g, ",") .replace(/,,/g, ",") } console.log(solution("((아디다스) 무료 (나이키 (풋살화)) 배송) 강남점 (축구)(잔디)") === "풋살화,아디다스,나이키,무료배송,축구,잔디,강남점"); console.log(solution("[지이크]신원") === "지이크,신원"); console.log(solution("(냉장고 (양문냉장고 (2형 (삼성전자 {nt3058}))))" )) console.log(solution("(냉장고 (양문냉장고 (2형 (삼성전자 {nt3058}))))" ) === "nt3058,삼성전자,2형,양문냉장고,냉장고") ================================================ FILE: programmers/위클리 챌린지/1주차/6047198844.py ================================================ def solution(price, money, count): need = count * (count + 1) // 2 * price - money return need if need > 0 else 0 ================================================ FILE: programmers/위클리 챌린지/2주차/6047198844.py ================================================ def solution(scores): answer = '' def grade(avg): # print(avg) if avg >= 90: return 'A' elif 80 <= avg < 90: return 'B' elif 70 <= avg < 80: return 'C' elif 50 <= avg < 70: return 'D' else: return 'F' scores = list(zip(*scores)) for idx, score in enumerate(scores): aggre = sum(score) N = len(score) self_score = score[idx] if score.count(self_score) == 1 and (self_score == min(score) or self_score == max(score)): aggre -= self_score N -= 1 answer += grade(aggre // N) return answer ================================================ FILE: programmers/카카오 개발자 겨울 인턴십 2019/불량사용자/불량사용자.py ================================================ def solution(user_id, banned_id): global answer answer= 0 res= [] ban_list= [[] for _ in range(len(banned_id))] # user_id와 banned_id를 매개변수로 받아서 banned_id 기준으로 길이가 같은 user_id 중에서 *인 문자를 제외하고 동일하다면 ban_list에 user_id를 넣어준다. # banned_id의 index에 맞는 user_id가 ban_list에 들어가게 된다. for ban in range(len(banned_id)): for user in user_id: if len(banned_id[ban])==len(user): cnt= 0 for i in range(len(user)): if banned_id[ban][i] == '*': cnt+=1; continue elif banned_id[ban][i] != user[i]: break; cnt+=1 if cnt== len(banned_id[ban]): ban_list[ban].append(user) # ban_list에서 index마다 하나씩 뽑아서 조합을 구성해준다. # 재귀 형태로 구현을 할 것이며 이때 중요한 점은 이 전에 뽑아준 user_id가 중복해서 들어가는 경우는 제외되도록 구현을 해줌. def select(res_list, cnt): global answer if cnt == len(ban_list): if sorted(res_list) not in res: res.append(sorted(res_list)) answer+=1 # print("res_list", res_list); return for i in range(len(ban_list[cnt])): if not ban_list[cnt][i] in res_list: res_list.append(ban_list[cnt][i]) select(res_list, cnt+1) res_list.pop(-1) select([], 0) # print(res) return answer solution(["frodo", "fradi", "crodo", "abc123", "frodoc"], ["fr*d*", "abc1**"]) solution(["frodo", "fradi", "crodo", "abc123", "frodoc"], ["*rodo", "*rodo", "******"]) solution(["frodo", "fradi", "crodo", "abc123", "frodoc"], ["fr*d*", "*rodo", "******", "******"]) ================================================ FILE: programmers/카카오 개발자 겨울 인턴십 2019/크레인 인형뽑기 게임/크레인 인형뽑기 게임.py ================================================ # 뽑으려는 대상의 위치에 가서 0이 아닐 때까지 depth를 증가시켜서 뽑은 뒤 0으로 값을 바꿔주고 # 그 값이 basket 마지막에 있는 값과 같으면 사라지게 해주고 아니면 basket에 append하는 식으로 구현을 하였다. # pick 위치에 아무것도 들어있지 않다면 continue를 해서 생략을 해주었다. def solution(board, moves): basket= [] n= len(board) cnt= 0 for pick in moves: tmp= 0 for idx in range(n): if board[idx][pick-1]!= 0: tmp= board[idx][pick-1] board[idx][pick-1]= 0 break if tmp==0: continue if len(basket)>=1 and basket[-1]== tmp: basket.pop(-1); cnt+=2; continue basket.append(tmp) return cnt solution([[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]], [1,5,3,5,1,2,1,4]) ================================================ FILE: programmers/카카오 개발자 겨울 인턴십 2019/튜플/튜플.py ================================================ def solution(s): # },{ 기준으로 나눠준 다음에 앞에 {{, }}를 떼주어서 list로 만들었다. arr= s.split('},{') arr[0]= arr[0][2:] arr[-1]= arr[-1][:-2] res= [] for i in range(len(arr)): arr[i]= list(map(int, arr[i].split(','))) # print(arr) # 정렬을 리스트의 길이 순서대로 해주어 문자열의 길이가 작은 것부터 값을 추가해 준 뒤 반환 arr.sort(key= len) for i in range(len(arr)): for j in range(len(arr[i])): if not arr[i][j] in res: res.append(arr[i][j]) # print(res) return res solution("{{1,2,3},{2,1},{1,2,4,3},{2}}") solution("{{1,2,3},{2,1},{1,2,4,3},{2}}") solution("{{20,111},{111}}") solution("{{123}}") solution("{{4,2,3},{3},{2,3,4,1},{2,3}}") ================================================ FILE: programmers/카카오_2020_상반기_인턴_코딩테스트/README.md ================================================ # 출처 공개된 문제는 아닙니다. ================================================ FILE: programmers/카카오_2020_상반기_인턴_코딩테스트/junilhwang-01.js ================================================ function solution (board, moves) { const b = [] const arr = board.map((v, x) => { return v.reduce((arr, v2, y) => { const n = board[y][x] if (n !== 0) arr.push(n) return arr }, []) }) let resolve = 0; moves.forEach(v => { const n = arr[v - 1].shift() if (n !== undefined) { const before = b.pop() if (before === undefined) { b.push(n) } else if (before !== n) { b.push(before, n) } else if (before === n) { resolve += 2 } } }) return resolve } console.log( solution( [ [0,0,0,0,0], [0,0,1,0,3], [0,2,5,0,1], [4,2,4,4,2], [3,5,1,3,1] ], [1,5,3,5,1,2,1,4] ) === 4 ) ================================================ FILE: programmers/카카오_2020_상반기_인턴_코딩테스트/junilhwang-02.js ================================================ function solution (s) { const arr = eval(s.replace(/{/g, '[').replace(/}/g, ']')) arr.sort((a, b) => a.length - b.length) const resolve = [arr.shift()[0]] arr.forEach(v => { while (v.length > 1) { const index = v.findIndex(v2 => resolve.includes(v2)) v.splice(index, 1) } resolve.push(v.pop()) }) return resolve } console.log( solution("{{2},{2,1},{2,1,3},{2,1,3,4}}").toString() === [2, 1, 3, 4].toString() ) console.log( solution("{{1,2,3},{2,1},{1,2,4,3},{2}}").toString() === [2, 1, 3, 4].toString() ) console.log( solution("{{20,111},{111}}").toString() === [111, 20].toString() ) console.log( solution("{{123}}").toString() === [123].toString() ) console.log( solution("{{4,2,3},{3},{2,3,4,1},{2,3}}").toString() === [3, 2, 4, 1].toString() ) console.log( solution("{{2},{2,1},{2,1,3},{2,1,3,4},{2,1,3,4,2}}").toString() === [2, 1, 3, 4, 2].toString() ) console.log( solution("{{2},{22},}").toString() === [2, 1, 3, 4, 2].toString() ) ================================================ FILE: programmers/카카오_2020_상반기_인턴_코딩테스트/junilhwang-03.js ================================================ function solution (user_id, banned_id) { const regs = banned_id.map(v => new RegExp('^' + v.replace(/\*/g, '.') + '$')) const set = new Set() const arr = regs.map(v => user_id.filter(v2 => v.test(v2))) const len = arr.length const resolve = [] const f = (index, stack) => { if (stack.length === arr.length) { const res = stack.sort((a, b) => a > b ? 1 : -1).join(',') if (!resolve.includes(res)) { resolve.push(res) } } if (index === len) return arr[index].forEach(v => { if (!stack.includes(v)) { f(index + 1, [...stack, v]) } }) } f(0, []) return resolve.length } console.log(solution(["frodo", "fradi", "crodo", "abc123", "frodoc"],["fr*d*", "abc1**"]) === 2) console.log(solution(["frodo", "fradi", "crodo", "abc123", "frodoc"],["*rodo", "*rodo", "******"]) === 2) console.log(solution(["frodo", "fradi", "crodo", "abc123", "frodoc"],["fr*d*", "*rodo", "******", "******"]) === 3) ================================================ FILE: programmers/카카오_2020_상반기_인턴_코딩테스트/junilhwang-04.js ================================================ function solution(k, room_number) { const root = { min: 0, arr: [], max: 0, next: null } const listFind = k => { console.log('\nroot', root) if (root.max === 0) { root.min = k root.arr = [k] root.max = k + 1 root.next = null return k } let node = root while (true) { if (node.min <= k && k <= node.max) break if (node.next === null) { node.next = { min: k, arr: [k], max: k + 1, next: null } return k } node = node.next } console.log('Selected Node', k, node) if (node.arr.indexOf(k) === -1) { node.arr.push(k) if (k === node.max) node.max += 1 return k } let max = node.max node.max += 1 node.arr.push(max) if (node.next !== null && node.max === node.next.min) { node.arr.push(...node.next.arr) node.max = node.next.max node.next = node.next.next } return max } const arr = room_number.map(v => listFind(v)) console.log(arr) return arr } // console.log(solution(10, [1,3,4,1,3,1]).toString() === [1,3,4,2,5,6].toString()) // console.log(solution(10, [1,1,1,3,3,3]).toString() === [1,2,3,4,5,6].toString()) // console.log(solution(200000, [1,1,1,10,10,10]).toString() === [1,2,3,10,11,12].toString()) const max = 10 ** 10 console.log(solution(200000, [1,1,1,max,max,max]).toString() === [1,2,3,max,max+1,max+2].toString()) ================================================ FILE: programmers/카카오_2020_상반기_인턴_코딩테스트_2/1.js ================================================ function solution(numbers, hand) { const table = { '1': { value: [0, 0], type: 'L' }, '2': { value: [0, 1], type: 'C' }, '3': { value: [0, 2], type: 'R' }, '4': { value: [1, 0], type: 'L' }, '5': { value: [1, 1], type: 'C' }, '6': { value: [1, 2], type: 'R' }, '7': { value: [2, 0], type: 'L' }, '8': { value: [2, 1], type: 'C' }, '9': { value: [2, 2], type: 'R' }, '*': { value: [3, 0], type: 'L' }, '0': { value: [3, 1], type: 'C' }, '#': { value: [3, 2], type: 'R' }, } const pos = ['*', '#'] const answer = numbers.map(n => { console.log('n', n) const { type, value } = table[n] switch(type) { case 'L': pos[0] = n; return 'L'; case 'R': pos[1] = n; return 'R'; default: const left = table[pos[0]].value const right = table[pos[1]].value const leftType = Math.abs(Math.abs(left[0] - value[0]) + Math.abs(left[1] - value[1])) ** 2 const rightType = Math.abs(Math.abs(right[0] - value[0]) + Math.abs(right[1] - value[1])) ** 2 if (leftType < rightType) { pos[0] = n; return 'L' } if (rightType < leftType) { pos[1] = n; return 'R' } const chk = hand === 'left' pos[chk ? 0 : 1] = n return chk ? 'L' : 'R' } }).join('') console.log(answer) return answer; } console.log( solution([1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5], "right") === "LRLLLRLLRRL", solution([7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2], "left") === "LRLLRRLLLRR", solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], "right") === "LLRLLRLLRL", ) ================================================ FILE: programmers/카카오_2020_상반기_인턴_코딩테스트_2/2.js ================================================ function solution(expression) { const numberStack = [] const operStack = [] const opers = ['+', '-', '*'] const len = expression.length let n = 0 let token = '' while (n < len) { const c = expression.charAt(n) if (opers.indexOf(c) !== -1) { if (token.length) { numberStack.push(token) token = '' } operStack.push(c) } else { token += c } n++ } if (token.length) numberStack.push(token) const sums = ['+*-','+-*','-*+','-+*','*-+','*+-'].map(v => { const opers = [ ...v ] const oStack = [ ...operStack ] const nStack = [ ...numberStack ] while (opers.length !== 0) { const oper = opers.shift() let idx = oStack.indexOf(oper) while (idx !== -1) { const exp = `${nStack[idx]} ${oper} ${nStack[idx + 1]}` nStack[idx] = eval(exp) nStack.splice(idx + 1, 1) oStack.splice(idx, 1) idx = oStack.indexOf(oper) } } return Math.abs(nStack.pop()) }) return Math.max(...sums) } console.log( solution("100-200*300-500+20") ===60420, solution("50*6-3*2") === 300, ) ================================================ FILE: programmers/카카오_2020_상반기_인턴_코딩테스트_2/3.js ================================================ function solution(board) { const set = [ ...new Set(board) ] const setSize = set.length const place = set.map(v => [board.indexOf(v), board.lastIndexOf(v)]) const last = Math.min(...place.pop()) let start = 0 for (let i = 0; place[i] !== undefined; i++) { const [min, max] = place[i] if (new Set(board.slice(min, last + 1)).size !== setSize) break start = Math.max(min, start) if (max <= last && new Set(board.slice(max, last + 1)).size === setSize) { start = Math.max(max, start) } } return [ start + 1, last + 1] } console.log( solution(["DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"]).toString() === [3, 7].toString(), solution(["AA", "AB", "AC", "AA", "AC"]).toString() === [1, 3].toString(), solution(["XYZ", "XYZ", "XYZ"]).toString() === [1, 1].toString(), solution(["ZZZ", "YYY", "NNNN", "YYY", "BBB"]).toString() === [1, 5].toString(), ) ================================================ FILE: programmers/카카오_2020_상반기_인턴_코딩테스트_2/4.js ================================================ function solution(board) { var answer = 0; return answer; } console.log( solution([[0,0,0],[0,0,0],[0,0,0]]) === 900, solution([[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,0],[0,0,0,1,0,0,0,1],[0,0,1,0,0,0,1,0],[0,1,0,0,0,1,0,0],[1,0,0,0,0,0,0,0]]) === 3800, solution([[0,0,1,0],[0,0,0,0],[0,1,0,1],[1,0,0,0]]) === 2100, solution([[0,0,0,0,0,0],[0,1,1,1,1,0],[0,0,1,0,0,0],[1,0,0,1,0,1],[0,1,0,0,0,1],[0,0,0,0,0,0]]) === 3200, ) ================================================ FILE: programmers/카카오_프런트엔드_경력직_챌린지/junilhwang/1.js ================================================ function solution(offers) { return offers .map(v => v.replace(/\//gi, "").split(" ").map(v => ~~v)) .reduce((max, v) => { if (max[2] === v[2]) { return max[1] < v[1] ? v : max; } if (max[2] < v[2] && max[1] >= v[0]) { return v; } return max; })[2]; } console.log( solution([ "10/05 10/12 2400", "10/05 10/10 2500", "10/07 10/15 2300", "10/08 10/30 3000", "10/15 11/03 3000", "10/20 11/01 3500", "11/02 11/11 4000"]) === 3500, solution(["07/01 07/30 2000", "07/01 07/15 2000", "07/01 07/30 2000", "07/01 07/30 1500", "07/05 07/30 2100", "07/20 08/01 2400", "07/20 07/31 2400", "07/31 09/01 2900", "08/01 08/15 3000", "08/14 08/19 2000", "08/17 08/30 4000"]) === 3000 ) ================================================ FILE: programmers/카카오_프런트엔드_경력직_챌린지/junilhwang/2.js ================================================ function solution(N, facility) { if (facility.length === 1) return 0; let min = Infinity; for (let i = 0; i < N; i++ ) { for (let j = 0; j < N; j++) { const max = facility.reduce((max, v) => Math.max( (Math.abs(i - v[0]) + Math.abs(j - v[1])) * v[2], max ), 0) min = Math.min(min, max) } } return min; } console.log( solution(3, [[1,3,1],[3,1,1]]) === 2, solution(3, [[1,3,2],[3,1,1]]) === 3, solution(3, [[1,1,1]]) === 0, ) ================================================ FILE: programmers/카카오_프런트엔드_경력직_챌린지/junilhwang/3.js ================================================ function solution (board) { const len = board.length; const isDia = (depth, i, j) => { const startI = i - depth; const endI = i + depth; const startJ = j - depth; const endJ = j + depth; if (startI < 0 || endI >= len) return false; if (startJ < 0 || endJ >= len) return false; if (board[startI][j] !== 1 || board[endI][j] !== 1) return false; if (board[i][startJ] !== 1 || board[i][endJ] !== 1) return false; return true; } let cnt = 0; for (let i = 0; i < len; i++) { for (let j = 0; j < len; j++) { const v = board[i][j]; let depth = 1; if (v === 0) { cnt += isDia(1, i, j) } } } return cnt; }; console.log( solution([[0,0,1,0,0],[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0],[0,0,1,0,0]]) === 4, solution([[0,0,0,1,0,0,0],[0,0,1,0,1,1,0],[0,1,0,1,0,0,1],[1,0,0,0,1,1,0],[0,1,0,1,0,1,0],[1,0,1,0,0,0,1],[0,1,0,1,0,1,0]]) === 3, ) ================================================ FILE: programmers/쿠팡/junilhwang/2.js ================================================ function solution (n, customers) { const kiosks = Array(n).fill(0); const matches = Array(n).fill(0); let beforeDate = null; let year = 1970; for (const customer of customers ) { const [date, start, minute] = customer.split(' '); if (beforeDate && beforeDate !== date && date === '01/01') { year += 1; } const timestamp = new Date(`${year}/${date} ${start}`).getTime(); const end = timestamp + (1000 * 60 * minute); const selectedIndex = kiosks.reduce(([min, minK], v, k) => { return v < min ? [v, k] : [min, minK]; }, [Infinity, -1])[1]; kiosks[selectedIndex] = end; matches[selectedIndex] += 1; beforeDate = date; } return Math.max(...matches); } console.log( solution(3, ['10/01 23:20:25 30', '10/01 23:25:50 26', '10/01 23:31:00 05', '10/01 23:33:17 24', '10/01 23:50:25 13', '10/01 23:55:45 20', '10/01 23:59:39 03', '10/02 00:10:00 10']), 4); console.log( solution(2, ['02/28 23:59:00 03', '03/01 00:00:00 02', '03/01 00:05:00 01']), 2); console.log( solution(2, ['12/31 23:59:00 03', '01/01 00:00:00 02', '01/01 00:05:00 01']), 2); ================================================ FILE: programmers/쿠팡/junilhwang/3.js ================================================ function solution (k, score) { const subMap = {}; const subMapCnt = {}; let iterated = 0; for (let i = 1, len = score.length; i < len; i++) { const key = score[i - 1] - score[i]; subMap[key] = subMap[key] || new Set(); subMap[key].add(i); subMap[key].add(i - 1); subMapCnt[key] = (subMapCnt[key] || 0) + 1; } return score.length - Object.entries(subMapCnt).reduce((set, [key, cnt]) => { if (cnt >= k) { return new Set([ ...set, ...subMap[key] ]) } return set; }, new Set()).size; } console.log( solution(3, [24,22,20,10,5,3,2,1]), 3 ) console.log( solution(2, [1300000000,700000000,668239490,618239490,568239490,568239486,518239486,157658638,157658634,100000000,100]), 4 ) ================================================ FILE: programmers/쿠팡/junilhwang/4.js ================================================ function solution (depar, hub, dest, roads) { const graph = roads.reduce((path, [start, end]) => { path[start] = path[start] || []; path[start].push(end); return path; }, {}); let result = 0; const f = (paths, last) => { if (last === dest) { result += paths.includes(hub); return; } graph[last].forEach(v => { f(paths.concat([ v ]), v); }); } f([ depar ], depar); return result; } console.log( solution( "SEOUL", "DAEGU", "YEOSU", [["ULSAN","BUSAN"],["DAEJEON","ULSAN"],["DAEJEON","GWANGJU"],["SEOUL","DAEJEON"],["SEOUL","ULSAN"],["DAEJEON","DAEGU"],["GWANGJU","BUSAN"],["DAEGU","GWANGJU"],["DAEGU","BUSAN"],["ULSAN","DAEGU"],["GWANGJU","YEOSU"],["BUSAN","YEOSU"]] ), 9 ); console.log( solution( "ULSAN", "SEOUL", "BUSAN", [["SEOUL","DAEJEON"],["ULSAN","BUSAN"],["DAEJEON","ULSAN"],["DAEJEON","GWANGJU"],["SEOUL","ULSAN"],["DAEJEON","BUSAN"],["GWANGJU","BUSAN"]] ), 0 ); ================================================ FILE: programmers/토스/1.js ================================================ /** * @param {string} name 마스킹할 이름 * @returns {string} 마스킹된 이름 */ function getMaskedName(name) { // 함수를 작성해주세요 const len = name.length; const nameArr = new Array(len).fill('*'); console.log({nameArr}); nameArr[0] = name.charAt(0); nameArr[1] = name.charAt(1); console.log({nameArr}); return nameArr.join(''); } console.log(getMaskedName('제갈도건')); ================================================ FILE: programmers/토스/2.js ================================================ /** * @param {number} peopleCount 금액을 나눌 사람의 수 * @param {number} amount 나눌 금액 * @returns {number[]} 각자가 부담할 금액을 나타내는 숫자의 배열 */ function splitDutchPayAmount(peopleCount, amount) { const div = ~~(amount / peopleCount); const remain = amount % peopleCount; const res = new Array(peopleCount).fill(div); res[0] += remain; return res; } console.log( splitDutchPayAmount(3, 4) ) ================================================ FILE: programmers/토스/3.js ================================================ // commaizeNumber 함수를 구현하세요. // num은 Number 타입으로 들어온다고 가정합니다. function commaizeNumber(num) { const numArr = (num + '').split(''); const len = numArr.length; let newNumber = ''; for (let i = len - 1 ; i > -1 ; i--) { newNumber = numArr[i] + newNumber; if (i !== 0 && (len - i) % 3 === 0) newNumber = ',' + newNumber; } return newNumber } console.log(commaizeNumber(1234567) === '1,234,567'); console.log(commaizeNumber(1) === '1'); console.log(commaizeNumber(12) === '12'); console.log(commaizeNumber(123) === '123'); ================================================ FILE: programmers/프로그래머스_챌린지/2020_상반기_백엔드개발자_코딩테스트.01/README.md ================================================ # 출처 https://programmers.co.kr/competitions/144/2020-web-be-first ================================================ FILE: programmers/프로그래머스_챌린지/2020_상반기_백엔드개발자_코딩테스트.01/junilhwang.js ================================================ function solution (P, S) { return [ ...P ].reduce((sum, p, k) => { const s = S.charAt(k) const [big, small] = [ Math.max(p, s), Math.min(p, s) ] return sum + Math.min(big - small, (small + 10) - big) }, 0) } console.log(solution("82195", "64723") === 13) console.log(solution("00000000000000000000", "91919191919191919191") === 20) ================================================ FILE: programmers/프로그래머스_챌린지/2020_상반기_백엔드개발자_코딩테스트.02/README.md ================================================ # 출처 https://programmers.co.kr/competitions/144/2020-web-be-first ================================================ FILE: programmers/프로그래머스_챌린지/2020_상반기_백엔드개발자_코딩테스트.02/junilhwang.js ================================================ function solution (office, r, c, move) { let direction = 0 const len = office.length const go = () => { const tmp = [r, c] switch (direction) { case 0: r -= 1; break; case 1: c += 1; break; case 2: r += 1; break; case 3: c -= 1; break; } if (Math.max(r, c) >= len || Math.min(r, c) < 0 || office[r][c] < 0) { ([r, c] = tmp) } } const left = () => direction = direction === 0 ? 3 : direction - 1 const right = () => direction = (direction + 1) % 4 return move .reduce((stack, v) => { ({ go, left, right })[v](); const pos = `${r},${c}` if (stack.indexOf(pos) === -1) stack.push(pos) return stack }, [ `${r},${c}` ]) .reduce((sum, v) => { const [r, c] = v.split(',') return sum + office[r][c] }, 0) } console.log( solution([[5,-1,4],[6,3,-1],[2,-1,1]], 1, 0, ['go','go','right','go','right','go','left','go']) === 14 ) ================================================ FILE: programmers/프로그래머스_챌린지/2020_상반기_백엔드개발자_코딩테스트.03/README.md ================================================ # 출처 https://programmers.co.kr/competitions/144/2020-web-be-first ================================================ FILE: programmers/프로그래머스_챌린지/2020_상반기_백엔드개발자_코딩테스트.03/junilhwang.js ================================================ function solution (numbers, k) { const len = numbers.length if (len === 1) return -1 const check = arr => { let prev = arr.shift() for (const v of arr) { if (Math.abs(prev - v) > k) return false prev = v } return true } const sorted = [ ...numbers ].sort((a, b) => a - b) if (check(sorted) === false) return -1 for (let i = 0; i < len; i++) { for (let j = 0; j < len; j++) { if (i === j) continue if (Math.abs(numbers[i] - numbers[j]) <= k) { console.log(numbers[i], numbers[j]) } } } } console.log(solution([10, 40, 30, 20], 20) === 1) // console.log(solution([3, 7, 2, 8, 6, 4, 5, 1], 3) === 2) // console.log(solution([0, 100, 200, 300, 400], 40) === -1) // console.log(solution([0, 11, 20, 30, 40], 10) === -1) // console.log(solution([0, 1, 2, 3, 10], 6) === -1) ================================================ FILE: programmers/프로그래머스_챌린지/2020_하반기_겨울방학인턴십_코딩테스트/JeongShin1.js ================================================ function solution(n, delivery) { let answer = new Array(n+1).fill(undefined); const needCheck = []; for (const [p1, p2, result] of delivery) { if (result) { answer[p1] = answer[p2] = "O"; continue; } needCheck.push([p1, p2]); } for (const [p1, p2] of needCheck) { if (answer[p1]==="O"){ answer[p2] = "X"; continue; } if (answer[p2] === "O") { answer[p1] = "X"; continue; } answer[p1] = answer[p1] || "?"; answer[p2] = answer[p2] || "?"; } return answer.slice(1).map((v)=> !v ? "?" : v).join(""); } solution(6, [[1, 3, 1], [3, 5, 0], [5, 4, 0], [2, 5, 0]]); ================================================ FILE: programmers/프로그래머스_챌린지/2020_하반기_겨울방학인턴십_코딩테스트/JeongShin3.js ================================================ function solution(v) { const [row, col] = [v.length, v[0].length]; const visited = new Map(); const area = []; let val; for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { if (!visited.has(`${i},${j}`)) { val = v[i][j]; dfs(v, i, j, val, visited); area[val] = (area[val] || 0) + 1; } } } return area; } function dfs(v, i, j, val, visited) { const stack = [[i, j]]; visited.set(`${i},${j}`, true); while (stack[0]) { let [i, j] = stack.shift(); const p = [[i - 1, j], [i + 1, j], [i, j + 1], [i, j - 1]]; for (let [i, j] of p) { if (v[i] === undefined || v[i][j] === undefined || visited.has(`${i},${j}`) || v[i][j] !== val) continue; stack.push([i, j]); visited.set(`${i},${j}`, true); } } } // solution([[0, 0, 1, 1], [1, 1, 1, 1], [2, 2, 2, 1], [0, 0, 0, 2]]); ================================================ FILE: programmers/프로그래머스_챌린지/README.md ================================================ # 프로그래머스 챌린지 - [챌린지 홈](https://programmers.co.kr/competitions) - [2020 상반기 백엔드개발자 챌린지](https://programmers.co.kr/competitions/144/2020-web-be-first) ================================================ FILE: programmers/프로그래머스_챌린지/est/2.js ================================================ function solution (scores, k) { const arr = []; const len = scores.length; if (scores.length === 1) { return 0; } for (let i = 1; i < len; i++) { arr.push({ k: i, v: scores[i] - scores[i - 1], }) } const slicePoint = arr.sort((a, b) => b.v - a.v) .slice(0, k - 1) .sort((a, b) => Number(a.k) - Number(b.k)); let before = 0; let sum = 0; for (const v of slicePoint) { sum += scores[v.k - 1] - scores[before]; before = v.k; } return sum + scores[len - 1] - scores[before] } console.log( solution([1,3,7,8,10,15],3) === 5, solution([1,2,12,14,15],2) === 4, ) ================================================ FILE: programmers/프로그래머스_챌린지/est/3.js ================================================ function diff (maps, x, y, r, range) { let cnt = 0; const h = r / 2; for (let i = 0; i < r; i++) { for (let j = 0; j < r; j++) { if (!maps[x + i - h]) continue; if (!maps[x + i - h][y + j - h]) continue; if (maps[x + i - h][y + j - h] <= range[i][j]) { cnt += 1; } } } return cnt; } function solution (maps, p, r) { const range = new Array(r); for (let i = 0; i < r; i++) { range[i] = new Array(r).fill(0); } const h = r / 2; const hh = ~~(h / 2) for (let i = 0; i < h; i++) { range[i][h - i - 1] = p / 2; range[i][h + i] = p / 2; for (let j = h - i; j < h + i; j++) { range[i][j] = p; } range[h + i][i] = p / 2; range[h + i][r - i - 1] = p / 2; for (let j = i + 1; j < r - i - 1; j++) { range[h + i][j] = p; } } let max = -Infinity; const mapsLen = maps.length; for (let i = 0; i < mapsLen; i++) { for (let j = 0; j < mapsLen; j++) { max = Math.max(diff(maps, i, j, r, range), max); } } return max; } console.log( solution([[1, 28, 41, 22, 25, 79, 4], [39, 20, 10, 17, 19, 18, 8], [21, 4, 13, 12, 9, 29, 19], [58, 1, 20, 5, 8, 16, 9], [5, 6, 15, 2, 39, 8, 29],[39, 7, 17, 5, 4, 49, 5], [74, 46, 8, 11, 25, 2, 11]], 19, 6) === 17, // solution([[47, 8, 99, 9, 85, 3, 8], [90, 93, 8, 25, 98, 15, 97], [9, 95, 91, 87, 8, 81, 9], [98, 88, 82, 89, 79, 81, 97], [97, 35, 31, 97, 81, 2, 92], [32, 16, 49, 9, 91, 89, 17], [53, 6, 35, 12, 13, 98, 5]], 78, 6) === 11, // solution([[9, 8, 17, 55, 19, 7], [1, 25, 5, 39, 28, 8], [88, 19, 28, 3, 2, 9], [76, 73, 7, 18, 16, 14], [99, 8, 8, 7, 11, 9], [1, 18, 4, 10, 3, 6]], 16, 4) === 8, // solution([[6, 3, 2, 7, 3], [7, 2, 1, 6, 8], [8, 9, 8, 4, 9], [7, 9, 2, 7, 1], [6, 3, 6, 8, 4]], 5, 2) === 3, ) ================================================ FILE: programmers/프로그래머스_챌린지/카카오_커머스/junilhwang/1.js ================================================ function solution(n, record) { return record.reduce((serverMap, v) => { const [serverKey, nickName] = v.split(' '); const server = serverMap[serverKey] || []; if (server.includes(nickName)) return serverMap; server.push(nickName); serverMap[serverKey] = server.slice(-5); return serverMap; }, []).flatMap(server => server); } console.log( solution(1, ["1 fracta", "1 sina","1 hana","1 robel","1 abc", "1 sina", "1 lynn"]), solution(4, ["1 a","1 b","1 abc","3 b","3 a","1 abcd","1 abc","1 aaa","1 a","1 z","1 q", "3 k", "3 q", "3 z", "3 m", "3 b"]), ) ================================================ FILE: programmers/프로그래머스_챌린지/카카오_커머스/junilhwang/2.js ================================================ /* 실패 function solution(m, values) { const arr = []; for (const value of values) { const index = arr.findIndex(sum => sum + value <= m) if (index === -1) { arr.push(value); } else { arr[index] += value; } } return arr.length; } */ function solution(m, values) { const arr = []; for (const value of values) { let index = -1; if (arr.length === 0) { arr.push(value); continue; } for (let i = arr.length - 1; i >= 0; i--) { if (arr[i] + value > m) break; index = i; } if (index === -1) { arr.push(value); continue; } arr[index] += value; } return arr.length; } console.log( // [solution(4, [2,3,1]), 2], // [solution(4, [3,2,3,1]), 3], // [solution(4, [3,2,3,1,2]), 4], ) ================================================ FILE: programmers/프로그래머스_챌린지/카카오_커머스/junilhwang/3.js ================================================ function solution(next_student) { const pathMap = next_student.map((v, k) => { const arr = Array(next_student.length).fill(0); arr[k] = 1; return arr; }); const nextStudent = next_student.map(v => v - 1); const circle = (start) => { let now = start; let next; while (true) { next = nextStudent[now]; if (next === start || next === -1) return; if (pathMap[start][next]) return; pathMap[now][next] = 1; pathMap[start][next] = 1; now = nextStudent[now]; } } nextStudent.forEach((v, k) => circle(k)); const arr = pathMap.map(arr => arr.reduce((sum, v) => sum + v, 0)); const max = Math.max(...arr); return arr.lastIndexOf(max) + 1; } console.log( [solution([5, 9, 13, 1, 0, 0, 11, 1, 7, 12, 9, 9, 2]), 3], [solution([6, 10, 8, 5, 8, 10, 5, 1, 6, 7]), 9] ); ================================================ FILE: programmers/학점연계인턴십_2020_하반기/1.js ================================================ /* * 반에 아이들의 키가 다음과 같을때 * height = [1, 1, 3, 3, 4, 1] * 키 순으로 정렬하여 원래 배열과 비교 했을때 * 제자리에 서있지 않은 학생의 수를 반환하는 문제 * [1, 1, 3, 3, 4, 1] => [1, 1, 1, 3, 3, 4] 3을 반환 해야함 */ function countStudents(height) { const sorted = [...height].sort((a, b) => a - b); return sorted.reduce((acc, curr, idx) => acc + (curr !== height[idx]), 0) } ================================================ FILE: programmers/학점연계인턴십_2020_하반기/2.js ================================================ /* * a = ['ab','cd','ef'] * b = ['af', 'ee', 'ef'] * 다음과 같이 배열이 있을때 각 인덱스 별로 a[i] 와 b[i] 에 substring 이 있는지 여부 검사. * 'YES', 'NO', 'YES' 를 순서대로 출력해야함. * */ function commonSubstring(a, b) { const len = a.length; for (let i = 0; i < len; i++) { const [A, B] = [new Set(a[i]), new Set(b[i])]; let found = false for (const w of A) { if (B.has(w)) { found = true; console.log('YES'); break } } if (!found) console.log('NO'); } } ================================================ FILE: programmers/학점연계인턴십_2020_하반기/3.js ================================================ /* * 서로 아는 사이일 경우 1을 가지는 이차원 배열 정보를 주어졌을때 * 서로 건너건너 아는 사이일 경우 하나의 그룹으로 지정하여 그룹의 개수를 반환하는 문제 * 지금 다시보면 Union-find 문제 같지만 그냥 dfs로 풀이 했습니다. * */ function countGroups(related) { const graph = {}; const visited = {}; const len = related.length; let groups = 0; const dfs = (start) => { graph[start].forEach((n)=>{ if (!visited[n]) { visited[n] = true; dfs(n) } }) }; related.forEach((el, i) => { for (let j = 0; j < len; j++) { graph[i] = (graph[i] || []); if (el[j] === '1' && i !== j) { graph[i].push(j) } } }); for (const v of Object.keys(graph)) { if (!visited[v]) { visited[v] = true; dfs(v); groups++; } } return groups; } ================================================ FILE: programmers/학점연계인턴십_2020_하반기/4.js ================================================ /* * stocksProfit = [ 6, 6, 3, 9 ,3, 5, 1 ], target = 12 과 같이 주어졌을때 * target, 12, 을 만드는 유니크한 pair 의 개수를 구하는 문제 * (6, 6), (3, 9) 2 개의 유니크한 페어가 존재 하므로 2를 반환 * */ function stockPairs(stocksProfit, target) { const pairs = {}; const len = stocksProfit.length; stocksProfit.sort((a, b) => a - b); const checkDuplicate = (v1, v2) => { if (!pairs[v1 + ',' + v2] && !pairs[v2 + ',' + v1]) { pairs[v1 + ',' + v2] = true } }; const binSearch = (tar, idx) => { let [low, high] = [0, len]; while (low <= high) { const mid = ~~((low + high) / 2); if (stocksProfit[mid] === tar) { if (mid !== idx || (stocksProfit[mid - 1] === tar || stocksProfit[mid + 1] === tar)) { checkDuplicate(stocksProfit[idx], tar) } break; } else if (stocksProfit[mid] < tar) low = mid + 1; else high = mid - 1; } }; stocksProfit.forEach((val, idx) => { binSearch(target - val, idx); }); return Object.keys(pairs).length } ================================================ FILE: programmers/학점연계인턴십_2020_하반기/5.js ================================================ /* * 노드의 개수 n 과 edge 정보 edges 가 주어졌을 때 * 서로 연결된 노드 끼리를 하나의 집합이라 가정할때 집합의 노드 개수의 sqrt 를 구하여 * 모든 집합들의 sqrt 값들의 총합을 구하는 문제 * */ function connectedSum(n, edges) { const graph = {}, visited = {}; const dfs = (start) => { const stack = []; stack.push(start); visited[start] = true; let weight = 0; while (stack.length) { const v = stack.pop(); weight++; graph[v].forEach((n) => { if (!visited[n]) { visited[n] = true; stack.push(n) } }) } return weight }; for (const e of edges) { const [from, to] = e.split(' '); graph[from] = (graph[from] || []); graph[to] = (graph[to] || []); graph[to].push(from); graph[from].push(to); } let sum = 0; for (const v of Object.keys(graph)) { if (!visited[v]) sum += Math.ceil(Math.sqrt(dfs(v))) } for (let i = 1; i <= n; i++) { if (!visited[i]) sum++; } return sum; } ================================================ FILE: 라이브러리/Trie.js ================================================ // https://www.youtube.com/watch?v=7e1b70dTAd4 class Trie { constructor() { } head = {}; add(word) { let currNode = this.head; for (const char of word) { if (currNode[char] === undefined) { currNode[char] = {} } currNode = currNode[char]; } currNode['*'] = true; } search(word) { let currNode = this.head; for(const char of word) { if (currNode[char] === undefined) { return false; } currNode = currNode[char]; } return !!currNode['*']; } } const dic = new Trie(); dic.add('hi'); dic.add('abc'); dic.add('abcasasa'); console.log(dic.search('ac')); console.log(dic.search('ab')); ================================================ FILE: 라이브러리/lowerBound.js ================================================ const lowerBound = (arr, key) => { let [start, end, mid] = [0, arr.length, arr.length]; while (end - start > 0) { // start 가 end 와 같지 않고, 넘지 않을 때 mid = ~~((start + end) / 2); //중앙 index (arr[mid] < key) ? (start = mid + 1) : (end = mid); } return end + 1; }; /* https://blockdmask.tistory.com/168 C++ lower_bound 란? - 이진탐색(Binary Search)기반의 탐색 방법입니다. (배열 또는 리스트가 정렬 되어있어야 한다.) - @return 찾으려 하는 key 값이 "없으면" key 값보다 큰, 가장 작은 정수 값을 찾습니다. - 같은 원소가 여러개 있어도 상관 없으며, 항상 유일한 해를 구할 수 있습니다. - 구간이 [start, end]인 배열이 있을때, 중간위치의 index 를 mid 라고 하면, arr[mid-1] < key 이면서 arr[mid] >= key 인 최소의 m 값을 찾으면 됩니다. (m>=2) */ ================================================ FILE: 라이브러리/prefixSum.js ================================================ const getPrefixSum = (originArr) => { return originArr.reduce((prefixSum, num, key) => { prefixSum.push((num + prefixSum[key])); return prefixSum; }, [0]); }; ================================================ FILE: 라이브러리/topology.js ================================================ /** * https://leetcode.com/problems/course-schedule/ * @param numCourses : courses you have to take / 들을 수 있는 course 의 수 * 코스의 라벨은 0 부터 numCourses - 1 까지임. * @param prerequisites 선수 과목을 담고 있는 배열 * [0,1] : 0 이 1의 선수 과목임 * @return 모든 코스를 수강을 할 수 있으면 true 리턴 * * Topological Sort 위상 정렬을 이용해 풀 수 있다. * https://blog.naver.com/ndb796/221236874984 * 순서가 정해져 있는 작업을 차례로 수행해야 할 때 그 순서를 결정해 주기 위해 사용하는 알고리즘 * 사이클이 발생하지 않는 방향 그래프에서만 가능하다. 사이클이 있으면 시작점을 찾을 수 없기 때문. * * 후기: topology 알고리즘 이라는 힌트를 얻어서 아이디어는 쉽게 얻을 수 있었으나 대부분의 테스트 케이스에서 오답이 나왔다. * 테스트 케이스를 보고 알고리즘을 수정하였습니다. */ // 정점별 진입차수 count const inDegree = (prerequisites) => ( prerequisites.reduce((hash, prerequisite) => { prerequisite.forEach((vertex, j) => { // 초기화 if (!hash[vertex]) { const vertexObj = hash[vertex] = {}; vertexObj.after = []; vertexObj.before = 0; } const vertexObj = hash[vertex]; const [before, after] = [prerequisite[j - 1], prerequisite[j + 1]]; after !== undefined && vertexObj.after.push(after); before !== undefined && (vertexObj.before += 1); }); return hash; }, {}) ); const canFinish = function(numCourses, prerequisites) { if (prerequisites.length === 0) return true; /* { '0': { after: [], before: 2 }, '1': { after: [ 0 ], before: 0 }, '2': { after: [ 0 ], before: 0 } } */ const hash = inDegree(prerequisites); // 정점의 방문을 check 한다. const check = new Array(numCourses).fill(false); let queue = []; // 진입차수가 0 인 것(before 가 없는것) 을 큐에 넣고 방문처리 한다.. // { queue: [ '1', '2' ], check: [ false, true, true ] } Object.entries(hash).forEach(([key, { before }]) => { if (before !== 0) return; queue.push(key); check[key] = true; }); // 큐가 빌때까지 반복 while (queue.length > 0) { // 큐에서 꺼낸다음. const shifted = queue.shift(); hash[shifted].after.forEach((vertex) => { // 연결되어 있던 간선을 다 제거해 준다. hash[vertex].before -= 1; // 진입차수가 0 인 것을 큐에 넣고 반복처리 if (hash[vertex].before !== 0) return; queue.push(vertex); check[vertex] = true; }); } // 모든 정점을 방문하기 전에 큐가 빈다면 사이클이 존재하는 것임. // 만약 선수 과목의 대상이 아닌 정점들은 false 로 표시될 것임. 하지만 선수 과목이 아니기 때문에 false 여도 상관없는 문제의 케이스도 고려함. // check [ true, true, true ] 모든 정점을 방문함 return !check.some((c, k) => !c && hash[k]); }; console.log( canFinish(1, []) === true, canFinish(2, [[1, 0]]) === true, canFinish(2, [[1, 0], [0, 1]]) === false, canFinish(3, [[0, 2], [1, 2], [2, 0]]) === false, canFinish(7, [[1, 0], [0, 3], [0, 2], [3, 2], [2, 5], [4, 5], [5, 6], [2, 4]]) === true, canFinish(3, [[1, 0], [2, 0], [0, 2]]) === false, canFinish(3, [[1, 0]]) === true, canFinish(3, [[1, 0], [2, 0]]) === true, canFinish(4, [[3, 0], [0, 1]]), ); ================================================ FILE: 모든경우의수/all.java ================================================ package 모든경우의수; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class all { public static void f (List stack, List list) { if (stack.size() == list.size()) { System.out.println(stack); return; } for (int v : list) { if (!stack.contains(v)) { List temp = stack.stream().collect(Collectors.toList()); temp.add(v); f(temp, list); } } } public static void solution (int[] arr) { List list = Arrays.stream(arr).boxed().collect(Collectors.toList()); List stack = new ArrayList(); f(stack, list); } public static void main(String[] args) { int[] arr = { 1, 2, 3 }; solution(arr); /* answer [ 1, 2, 3 ] [ 1, 3, 2 ] [ 2, 1, 3 ] [ 2, 3, 1 ] [ 3, 1, 2 ] [ 3, 2, 1 ] */ } } ================================================ FILE: 모든경우의수/all.js ================================================ function solution (arr) { const len = arr.length const f = stack => { if (stack.length === len) { console.log(stack) return } arr.forEach(v => { if (stack.indexOf(v) === -1) f([ ...stack, v ]) }) } f([]) } solution([1, 2, 3]) /* answer [ 1, 2, 3 ] [ 1, 3, 2 ] [ 2, 1, 3 ] [ 2, 3, 1 ] [ 3, 1, 2 ] [ 3, 2, 1 ] */ ================================================ FILE: 모든경우의수/all.py ================================================ def solution (arr): f([], arr, len(arr)) def f (stack, arr, last): if len(stack) == last: print(stack) return for v in arr: if not v in stack: f(stack[:] + [v], arr, last) solution([ 1, 2, 3 ]) # answer # [ 1, 2, 3 ] # [ 1, 3, 2 ] # [ 2, 1, 3 ] # [ 2, 3, 1 ] # [ 3, 1, 2 ] # [ 3, 2, 1 ] ================================================ FILE: 알고스팟/Mismatched Brackets/6047198844.cpp ================================================ #include #include #include using namespace std; bool inbalanceStack(string s) { stack st; for (char c : s) { if (c == '(' || c == '{' || c == '[') st.push(c); else { if (st.empty() || (st.top() != c - 1 && st.top() != c - 2)) return false; st.pop(); } } return st.empty(); } int main() { int C; cin >> C; string s; while (C--) { cin >> s; inbalanceStack(s) ? cout << "YES" << "\n" : cout << "NO" << "\n"; } } ================================================ FILE: 알고스팟/QUANTIZE/6047198844.cpp ================================================ #include #include #include using namespace std; const int INF = 987654321; int length; int arr[100], partSum[100], partSquareSum[100]; int cache[100][10]; void preCalculate(void){ sort(arr, arr + length); partSum[0] = arr[0]; partSquareSum[0] = arr[0] * arr[0]; for (int i = 1; i < length; i++){ partSum[i] = partSum[i - 1] + arr[i]; partSquareSum[i] = partSquareSum[i - 1] + arr[i] * arr[i]; } } int minDiffrence(int low, int high){ int sum = partSum[high] - (low == 0 ? 0 : partSum[low - 1]); int squareSum = partSquareSum[high] - (low == 0 ? 0 : partSquareSum[low - 1]); int mean = (int)(0.5 + (double)sum / (high - low + 1)); int result = squareSum - (2 * mean * sum) + (mean * mean * (high - low + 1)); return result; } int quantize(int from, int parts) { if (from == length) return 0; if (parts == 0) return INF; int& result = cache[from][parts]; if (result != -1) return result; result = INF; for (int partSize = 1; from + partSize <= length; partSize++) result = min(result, minDiffrence(from, from + partSize - 1) + quantize(from + partSize, parts - 1)); return result; } int main(void){ int s; cin >> s; for (int i = 0; i < s; i++){ int useNum; cin >> length >> useNum; for (int i = 0; i < length; i++) cin >> arr[i]; preCalculate(); memset(cache, -1, sizeof(cache)); cout << quantize(0, useNum) << endl << endl; } return 0; } ================================================ FILE: 알고스팟/고대어 사전/6047198844.cpp ================================================ #include #include #include using namespace std; vector> adj; void makeGraph(const vector& words) { adj = vector >(26, vector(26, 0)); for (int j = 1; j < words.size(); j++) { int i = j - 1; int len = min(words[j].length(), words[i].length()); for (int k = 0; k < len; k++) { if (words[i][k] != words[j][k]) { int a = words[i][k] - 'a'; int b = words[j][k] - 'a'; adj[a][b] = 1; break; } } } } vector seen, order; void dfs(int here) { seen[here] = 1; for (int there = 0; there < adj.size(); ++there) if (adj[here][there] && !seen[there]) dfs(there); order.push_back(here); } vector topologicalSort() { int m = adj.size(); seen = vector(m, 0); order.clear(); for (int i = 0; i < m; i++) if (!seen[i]) dfs(i); reverse(order.begin(), order.end()); for (int i = 0; i < m; ++i) for (int j = i + 1; j < m; ++j) if (adj[order[j]][order[i]]) return vector(); return order; } int main() { int C; cin >> C; while (C--) { int N; cin >> N; vector words(N); for (int i = 0; i < N; i++) cin >> words[i]; makeGraph(words); vector res = topologicalSort(); if (!res.empty()) for (int i : res) cout << (char)(i + 'a'); else cout << "INVALID HYPOTHESIS"; cout << "\n"; } } ================================================ FILE: 알고스팟/너드인가, 너드가 아닌가 2/6047198844.cpp ================================================ #include #include using namespace std; map nerds; //정복되었으면 true, 정복되지 않았으면 false를 반환한다. bool isDonimated(int x, int y) { map ::iterator it = nerds.lower_bound(x); //맨오른쪽에 있는 경우는 항상 정복되지 않은 경우이다. if (nerds.end() == it) return false; //오른쪽에 값이 있는 경우. 오른쪽 값이 크다면(true) 정복된것이다. return y < it->second; } //기존 너드를 삭제한다. //정복되지 않은 경우이다. //x가 큰데, y가 작은 경우 삭제한다. void removeNerds(int x, int y) { //it은 현재 x 오른쪽을 가리키고 있다. map ::iterator it = nerds.lower_bound(x); //왼쪽이 없으므로 . 삭제할것이 없다. //왼쪽만 삭제 가능하다. 오른쪽은 x가 크므로 , nerd이다. if (it == nerds.begin()) return; //왼쪽이 있는 경우이다. 현재 왼쪽을 가르킨다. --it; while (1) { //왼쪽이 점령당하지 않는 경우 if (y < it->second) return; //끝에 도달한 경우 if (it == nerds.begin()) { nerds.erase(it); return; } else { map ::iterator tit = it; --it; nerds.erase(tit); return; } } } //새로운 너드의 등록여부를 판단. 등록가능하면 기존 너드의 삭제가 가능할경우 삭제 후 등록, 등록불가능하면 등록하지 않고 기존의 크기 반환. int registerNerds(int x, int y) { if (isDonimated(x, y)) return nerds.size(); removeNerds(x, y); nerds[x] = y; return nerds.size(); } int main() { int C; cin >> C; while (C--) { int N; cin >> N; int result = 0; nerds.clear(); while (N--) { int x, y; cin >> x >> y; result += registerNerds(x, y); } cout << result << "\n"; } } ================================================ FILE: 알고스팟/단어 제한 끝말잇기/6047198844.cpp ================================================ /* 요구사항 : 단어들의 목록이 주어질 때, 단어들을 전부 사용하고 게임이 끝나는지 여부 확인. 단어를 전부 사용한다면 어떤 순서로 사용하는지 입력 : 테스트 케이스의 수 C (1<=C<=50), 게임에서 사용할 수 있는 단어의 수 n (1<=n<=100) 출력 : 게임이 끝나는 방법이 없는 경우 : IMPOSSIBLE / 방법이 있는 경우 : 사용할 단어들을 빈 칸 하나씩을 사이에 두고 순서대로 출력. */ #include #include #include #include using namespace std; int outadj[26]; int inadj[26]; int adj[26][26]; vector wordAdj[26][26]; /* 그래프가 오일러 서킷이나 오일러 트레일일때 해당 경로로 단어를 생성함. */ void makeWords(vector &EulerCircuit) { for (int i = 1; i < EulerCircuit.size(); i++) { if (i > 1) cout << " "; cout << wordAdj[EulerCircuit[i - 1]][EulerCircuit[i]].back(); wordAdj[EulerCircuit[i - 1]][EulerCircuit[i]].pop_back(); } return; } /* 그래프가 오일러 서킷인지 오일러 트레일인지 둘다 아닌지를 판단 하는 함수 */ bool isEulerCheck() { int plus = 0; int minus = 0; for (int i = 0; i < 26; i++) { int diff = outadj[i] - inadj[i]; if (diff < -1 || diff > 1) return false; if (diff == -1) minus++; else if (diff == +1) plus++; } return (plus == 0 && minus == 0) || (plus == 1 && minus == 1); } /* 오일러 서킷 무향 그래프 : 각 정점에 인접한 간선이 짝수개 방향 그래프 : 각 정점에서의 들어가는 간선과 나가는 간선의 수가 같아야한다. 오일러 트레일 (a에서 시작하고 b에서 끝나는) a는 나가는 간선의 수가 들어오는 간선보다 하나 많다. b는 들어오는 간선의 수가 나가는 간선보다 하나 많다. 다른 정점에서는 나가는 간선과 들어오는 간선의 수가 같다. 오일러 서킷과 오일러 트레일을 찾아서 반환하는 함수 */ void makeEulerCircuit(vector &EulerCircuit, int here) { for (int there = 0; there < 26; there++) { while (adj[here][there]) { adj[here][there]--; makeEulerCircuit(EulerCircuit,there); } } EulerCircuit.push_back(here); } vector getEulerCircuit() { vector EulerCircuit; //오일러 트레일인 경우 for (int i = 0; i < 26; i++) { if (outadj[i] - inadj[i] == 1) { makeEulerCircuit(EulerCircuit,i); reverse(EulerCircuit.begin(), EulerCircuit.end()); return EulerCircuit; } } //오일러 서킷인 경우 for (int i = 0; i < 26; i++) { if (outadj[i] == inadj[i]&&outadj[i]>0) { makeEulerCircuit(EulerCircuit, i); reverse(EulerCircuit.begin(), EulerCircuit.end()); return EulerCircuit; } } //아무것도 아닌경우 빈 서킷반환 return EulerCircuit; } /* 그래프를 만드는 함수. i로 시작해서 j로 끝나는 단어들의 목록 그래프의 인접 행렬 표현 i와 j 사이의 간선수 i로 시작하는 단어의 수 == > i에서 나가는 간선의 수 j로 끝나는 단어의 수 == > j로 들어가는 간선의 수 */ void makeGraph(vector& words) { for (int i = 0; i < 26; i++) for (int j = 0; j < 26; j++) wordAdj[i][j].clear(); memset(outadj, 0, sizeof(outadj)); memset(inadj, 0, sizeof(inadj)); for (int i = 0; i < words.size(); i++) { string word = words[i]; int first = word[0] - 'a'; int last = word.back() - 'a'; outadj[first]++; inadj[last]++; adj[first][last]++; wordAdj[first][last].push_back(word); } return; } void solution() { int N; cin >> N; vector words(N); for (int i = 0; i < N; i++) cin >> words[i]; makeGraph(words); if (!isEulerCheck()) { cout << "IMPOSSIBLE"; return; } vector EulerCircuit = getEulerCircuit(); //모든 단어가 연결되어야함 if (EulerCircuit.size() != words.size() + 1) { cout << "IMPOSSIBLE"; return; } makeWords(EulerCircuit); return; } int main() { int C; cin >> C; while (C--) { solution(); cout << "\n"; } } ================================================ FILE: 알고스팟/두니발 박사의 탈옥/6047198844.cpp ================================================ #include #include using namespace std; double cache[51][101]; double findDuni(int here, int where,int remDay,vector> &road) { if (remDay == 0) return here == where; double& res = cache[here][remDay]; if (res != 0) return res; int roadNum = road[here].size(); double mul = 1 / (double)roadNum; for (int i = 0; i < roadNum; i++) { res += (mul) * findDuni(road[here][i], where, remDay - 1, road); } return res; } int main() { cout.precision(10); int c; cin >> c; while (c--) { // , ݱ ϼ, Ұ ִ ȣ int n, d, p; cin >> n >> d >> p; vector > road(n); int to_town; int from_town; int temp; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> temp; if (temp) road[i].push_back(j); } } int t; cin >> t; while (t--) { int q; cin >> q; for (int i = 0; i < n; i++) for (int j = 0; j <= d; j++) cache[i][j] = 0; cout << findDuni(p, q, d, road) << " "; } cout << "\n"; } } ================================================ FILE: 알고스팟/변화하는 중간 값/6047198844.cpp ================================================ #include #include using namespace std; class make_value { private: int a; int b; long long current_value=1983; public: make_value(int a, int b) { this->a = a; this->b = b; } int nextvalue() { long long res = current_value; current_value = (current_value * a + b) % 20090711; return res; } }; //N개의 배열을 생성하면서 중간값을 계속 더한다. int Changing_value(int a, int b, int N) { int res = 0; //최소힙 priority_queue,less> left; //최대힙 priority_queue,greater> right; //생성기 make_value* mv = new make_value(a, b); for (int i = 0; i < N; i++) { int left_size = left.size(); int right_size = right.size(); int insert_value = mv->nextvalue(); if (left_size == right_size) { if (left.empty() || left.top() <= insert_value) { right.push(insert_value); } else { right.push(left.top()); left.pop(); left.push(insert_value); } res = (res + right.top()) % 20090711; } else { if (right.top() < insert_value) { left.push(right.top()); right.pop(); right.push(insert_value); } else { left.push(insert_value); } res = (res + left.top()) % 20090711; } } return res % 20090711; } int main() { int C; cin >> C; while (C--) { int N, a, b; cin >> N >> a >> b; cout << Changing_value(a, b, N) << "\n"; } } ================================================ FILE: 알고스팟/비대칭 타일링/6047198844.cpp ================================================ #include #include #define MOD 1000000007 using namespace std; long long cache[101]; long long tile(int n) { if (n <= 1) return 1; long long& res = cache[n]; if (res != -1) return res; return res = (tile(n - 1) % MOD + tile(n - 2) % MOD) % MOD; } int main() { int C; cin >> C; int n; memset(cache, -1, sizeof(cache)); while (C--) { cin >> n; tile(100); if (n % 2) cout << (tile(n) + MOD - tile(n / 2) + MOD) % MOD; else cout << (tile(n) + MOD - tile(n / 2) + MOD - tile(n / 2 - 1) + MOD) % MOD; cout << "\n"; } } ================================================ FILE: 알고스팟/삼각형 위의 최대 경로/6047198844.cpp ================================================ #include #include #include using namespace std; int dp(int y, int x,int N, vector > &triangle, vector >& memo) { if (y == N - 1) return triangle[y][x]; int& res = memo[y][x]; if (res != -1) return res; return res = triangle[y][x] + max(dp(y + 1, x, N, triangle, memo), dp(y + 1, x + 1, N, triangle, memo)); } int main() { int C; cin >> C; while (C--) { int N; cin >> N; vector > triangle(N, vector(N)); vector > memo(N, vector(N, -1)); for (int y = 0; y < N; y++) { for (int x = 0; x <= y; x++) { cin >> triangle[y][x]; } } cout << dp(0, 0, N, triangle, memo) << "\n"; } } ================================================ FILE: 알고스팟/삼각형 위의 최대 경로/삼각형 위의 최대 경로.py ================================================ from sys import stdin def compute_sum(location): global triang_list global memo line, number = location if line == len(triang_list) - 1: if location in memo: return memo[location] return_val = triang_list[line][number] memo[location] = return_val # print(f'return: {return_val}') return return_val if number == len(triang_list[line]): if (line + 1, number) in memo: return triang_list[line][number] + memo[(line + 1, number)] return_val = compute_sum((line + 1, number)) memo[line + 1, number] = return_val # print(f'return: {return_val}') return triang_list[line][number] + return_val if (line + 1, number) in memo: left_sum = memo[(line + 1, number)] else: left_sum = compute_sum((line + 1, number)) memo[(line + 1, number)] = left_sum if (line + 1, number + 1) in memo: right_sum = memo[(line + 1, number + 1)] else: right_sum = compute_sum((line + 1, number + 1)) memo[(line + 1, number + 1)] = right_sum return_val = triang_list[line][number] + max(left_sum, right_sum) # print(f'return: {return_val}') return return_val def sol(): C = int(stdin.readline()) for _ in range(C): n = int(stdin.readline()) global triang_list global memo triang_list = [] memo = {} for __ in range(n): triang_list.append(list(map(int, stdin.readline().split()))) print(compute_sum((0, 0))) # print(memo) sol() ================================================ FILE: 알고스팟/삼각형 위의 최대 경로수 세기/6047198844.cpp ================================================ #include #include #include #include using namespace std; int maxPathMemo[100][100]; int pathNumMemo[100][100]; int path[100][100]; //n ִ y. int MaxPath(int y, int x,int n) { int &res = maxPathMemo[y][x]; if (y == n) return path[y][x]; if (res != -1) return res; return res = path[y][x] + max(MaxPath(y + 1, x, n), MaxPath(y + 1, x + 1, n)); } int PathNum(int y, int x,int n) { int& res = pathNumMemo[y][x]; if (y == n) return 1; if (res != -1) return res; int leftMaxPath = MaxPath(y + 1, x, n); int RightMaxPath = MaxPath(y + 1, x + 1, n); if (leftMaxPath == RightMaxPath) return res = PathNum(y + 1, x, n) + PathNum(y + 1, x + 1, n); else if (leftMaxPath > RightMaxPath) return res = PathNum(y + 1, x, n); else return res = PathNum(y + 1, x + 1, n); } int main() { int C; cin >> C; int n; while (C--) { memset(maxPathMemo, -1, sizeof(maxPathMemo)); memset(pathNumMemo, -1, sizeof(pathNumMemo)); memset(path, -1, sizeof(path)); cin >> n; for (int y = 0; y < n; y++) { for (int x = 0; x <= y; x++) { cin >> path[y][x]; } } cout << PathNum(0, 0, n - 1) << "\n"; } } ================================================ FILE: 알고스팟/삽입 정렬 뒤집기/6047198844.cpp ================================================ #include #include #include using namespace std; int C, N, A[50001], shifted[50001]; struct Node { int key; int priority, size; Node* left, * right; Node(const int& _key) : key(_key), priority(rand()), size(1), left(NULL), right(NULL) {} void setLeft(Node* newLeft) { left = newLeft; calcSize(); } void setRight(Node* newRight) { right = newRight; calcSize(); } void calcSize() { size = 1; if (left) size += left->size; if (right) size += right->size; } }; typedef pair NodePair; NodePair split(Node* root, int key) { if (root == NULL) return NodePair(NULL, NULL); if (root->key < key) { NodePair rs = split(root->right, key); root->setRight(rs.first); return NodePair(root, rs.second); } else { NodePair ls = split(root->left, key); root->setLeft(ls.second); return NodePair(ls.first, root); } } Node* insert(Node* root, Node* node) { if (root == NULL) return node; if (root->priority < node->priority) { NodePair splitted = split(root, node->key); node->setLeft(splitted.first); node->setRight(splitted.second); return node; } else if (node->key < root->key) { root->setLeft(insert(root->left, node)); } else root->setRight(insert(root->right, node)); return root; } Node* merge(Node* a, Node* b) { if (a == NULL) return b; if (b == NULL) return a; if (a->priority < b->priority) { b->setLeft(merge(a, b->left)); return b; } else { a->setRight(merge(a->right, b)); return a; } } Node* erase(Node* root, int key) { if (root == NULL) return root; if (root->key == key) { Node* ret = merge(root->left, root->right); delete root; return ret; } if (key < root->key) root->setLeft(erase(root->left, key)); else root->setRight(erase(root->right, key)); return root; } Node* kth(Node* root, int k) { int leftSize = 0; if (root->left != NULL) leftSize = root->left->size; if (k <= leftSize) return kth(root->left, k); if (k == leftSize + 1) return root; return kth(root->right, k - leftSize - 1); } int countLessThan(Node* root, int key) { if (root == NULL) return 0; if (root->key >= key) return countLessThan(root->left, key); int ls = (root->left ? root->left->size : 0); return ls + 1 + countLessThan(root->right, key); } void solve() { Node* candidate = NULL; for (int i = 0; i < N; i++) candidate = insert(candidate, new Node(i + 1)); for (int i = N - 1; i >= 0; i--) { int large = shifted[i]; Node* k = kth(candidate, i + 1 - large); A[i] = k->key; candidate = erase(candidate, k->key); } } int main() { cin >> C; while (C--) { cin >> N; for (int i = 0; i < N; i++) cin >> shifted[i]; solve(); for (int i = 0; i < N; i++) cout << A[i] << " "; cout << endl; } } ================================================ FILE: 알고스팟/시계맞추기/dkdlelk99.cpp ================================================ #include #include #include #include using namespace std; const int CLOCKS = 16, SWICHES = 10, INF = 9999; // 연결된 스위치들 0~9 int swiches[10][5] = { {0, 1, 2, -1, -1}, {3, 7, 9, 11, -1}, {4, 10, 14, 15, -1}, {0, 4, 5, 6, 7}, {6, 7, 8, 10, 12}, {0, 2, 14, 15, -1}, {3, 14, 15, -1, -1}, {4, 5, 7, 14, 15},{1, 2, 3, 4, 5}, {3, 4, 5, 9, 13} }; //모든 시계가 12시를 가르키는지 검사 bool areAlined(vector clocks) { for (int i = 0; i < CLOCKS; i++) if (clocks[i] != 0) return false; return true; } //swich번 스위치를 누름 void push(vector& clocks, int swich) { int clock = -1, i = 0; for (i = 0; i < 5; i++) { if(swiches[swich][i] == -1) break; clock = swiches[swich][i]; clocks[clock]++; if (clocks[clock] == 4) clocks[clock] = 0; } } int solve(vector& clocks, int swich) { if (clocks[8] != clocks[12]) return -1; else if (swich == SWICHES) return areAlined(clocks) ? 0 : INF; int ret = INF; for (int i = 0; i < 4; i++) { ret = min(ret, solve(clocks, swich + 1) + i); push(clocks, swich); } return ret; } int main() { vector clocks; int testCase, clock, answer; cin >> testCase; while (testCase--) { //시계 입력 clocks.clear(); for (int i = 0; i < 16; i++) { cin >> clock; if (clock == 12) clocks.push_back(0); else clocks.push_back(int(clock / 3)); } answer = solve(clocks, 0); if (answer >= INF) cout << -1 << endl; else cout << answer << endl; } return 0; } ================================================ FILE: 알고스팟/와일드카드/6047198844.cpp ================================================ #include #include #include #include using namespace std; //memo[W][S] //W , S ־ ڿ //res == -1 , 湮. res == 0 ȵǴ res == 1 Ǵ . bool dp(string& w, string& s,int w_idx,int s_idx,vector > &memo) { int& res = memo[w_idx][s_idx]; if (res != -1) return res; int w_size = w.size(); int s_size = s.size(); while (w_idx < w_size && s_idx < s_size && (w[w_idx]==s[s_idx]||w[w_idx]=='?')) { w_idx++; s_idx++; } if (w_idx == w_size) return res = (s_idx == s_size); if (w[w_idx] == '*') for (int i = s_idx; i <= s_size; i++) if (dp(w, s, w_idx + 1, i, memo)) return res = 1; return res = 0; }l // ̽ Ѵ. int main() { int C; cin >> C; string W; string S; int N; while (C--) { cin >> W; cin >> N; vector res; while (N--) { cin >> S; vector > memo(W.size() + 1, vector(S.size() + 1, -1)); if (dp(W, S, 0, 0, memo)) res.push_back(S); } sort(res.begin(), res.end()); for (auto s : res) cout << s << "\n"; } } ================================================ FILE: 알고스팟/와일드카드/와일드카드.py ================================================ from sys import stdin def match(w_idx, s_idx): global w global s global memo w_start_idx = w_idx s_start_idx = s_idx # print(f'input_list -> {w[w_start_idx:]} matching : {s[s_start_idx:]}') if (w_start_idx, s_start_idx) in memo: # print(f'in memo\nreturn_value ->{memo[(w_start_idx, s_start_idx)]}') return memo[(w_start_idx, s_start_idx)] idx = 0 # print(f'start_matching at {idx} < {len(w[w_start_idx:]) - 1} or {idx} < {len(s[s_start_idx:]) - 1}') while idx < len(w[w_start_idx:]) and idx < len(s[s_start_idx:]): if w[w_start_idx + idx] == s[s_start_idx + idx] or w[w_start_idx + idx] == '?': idx += 1 # print(f' list: {w[w_start_idx + idx:]} matching: {s[s_start_idx + idx:]}') continue break if w_start_idx + idx == len(w) and s_start_idx + idx == len(s): memo[(w_start_idx, s_start_idx)] = True # print(f' case {w[w_start_idx + idx:]} -> {s[s_start_idx + idx:]} is True') return True if len(w[w_start_idx + idx:]) >= 1 and w[w_start_idx + idx] == '*': # print(f'fst letter is "*"') for jdx in range(0, len(s[s_start_idx:]) - idx + 1): # print(f'match( {w[w_start_idx + idx + 1:]} , {s[s_start_idx + idx + jdx:]} ) ') if match(w_start_idx + idx + 1, s_start_idx + idx + jdx): memo[(w_start_idx + idx + 1, s_start_idx + idx + jdx)] = True return True memo[(w_start_idx, s_start_idx)] = False return False def sol(): global w global s global memo w = stdin.readline().strip('\n') n = int(stdin.readline()) return_li = [] for __ in range(n): s = stdin.readline().strip('\n') memo = {} if match(0, 0): return_li.append(s) # print(f'memo: {memo}\n\n') return_li.sort() for li in return_li: print(li) C = int(stdin.readline()) for _ in range(C): sol() ================================================ FILE: 알고스팟/외계 신호 분석/6047198844.cpp ================================================ #include #include #include #define LL long long using namespace std; int analysisAlien(int K, int N) { queue q; int qSum = 0; // Q에 들어있는 신호의 합을 모두 저장한다. LL resentArrayValue = 1983; // A[i-1]을 저장한다. LL signalValue; int cnt = 0; for (int i = 1; i <= N; i++) { //Q에 있는 값과 K가 동일한 경우 -> Q에서 덜어내야함. cnt ++해야함. //Q에 있는 값이 큰경우 -> Q에서 덜어내야함. while (qSum >= K) { if (qSum == K) cnt++; qSum -= q.front(); q.pop(); } //Q에 있는 값이 작은 경우 signalValue = resentArrayValue % 10000 + 1; resentArrayValue = (resentArrayValue * 214013 + 2531011) % (LL)pow(2, 32); qSum += signalValue; q.push(signalValue); } return cnt; } int main() { int C; cin >> C; int K, N; while (C--) { cin >> K >> N; cout << analysisAlien(K, N) << "\n"; } } ================================================ FILE: 알고스팟/외발뛰기/6047198844.cpp ================================================ #include #include #define VI vector using namespace std; int dp(int x, int y, vector &memo, vector &game_board, int end_pos) { if (x > end_pos || y > end_pos) return 0; if (x == end_pos && y == end_pos) return 1; int& res = memo[y][x]; if (res != -1) return res; int cur_pos_value = game_board[y][x]; return res = dp(x + cur_pos_value, y, memo, game_board, end_pos) || dp(x, y + cur_pos_value, memo, game_board, end_pos); } int main() { int C; cin >> C; while (C--) { int N; cin >> N; vector game_board(N, VI(N, 0)); for (int y = 0; y < N; y++) for (int x = 0; x < N; x++) cin >> game_board[y][x]; vector memo(N, VI(N, -1)); if (dp(0, 0, memo, game_board, N - 1) != 0) { cout << "YES" << "\n"; continue; } cout << "NO" << "\n"; } } ================================================ FILE: 알고스팟/외발뛰기/외발뛰기.py ================================================ from sys import stdin def recursive_jump(mat, location): # print(f'cache : {cache}') if mat[location[0]][location[1]] == 0: return True if location in cache: return cache[location] current_num = mat[location[0]][location[1]] case_01, case_02 = False, False if location[0] + current_num <= len(mat) - 1: case_01 = recursive_jump(mat, (location[0] + current_num, location[1])) cache[(location[0] + current_num, location[1])] = case_01 if location[1] + current_num <= len(mat) - 1: case_02 = recursive_jump(mat, (location[0], location[1] + current_num)) cache[location[0], location[1] + current_num] = case_02 if case_01 or case_02: return True else: return False def sol(): n = int(stdin.readline()) mat = [list(map(int, stdin.readline().split())) for _ in range(n)] '''for line in mat: print(line)''' if recursive_jump(mat, (0, 0)): print('YES') else: print('NO') C = int(stdin.readline()) for _ in range(C): cache = {} sol() ================================================ FILE: 알고스팟/요새/6047198844.cpp ================================================ #include #include #include #include using namespace std; struct fortress_tree { vector my_node = { 0,0,0 }; vector child; bool operator < (const fortress_tree &fortress_tree) { return fortress_tree.my_node[2] < this->my_node[2]; } }; int sqr(int x) { return x * x; } int height(fortress_tree& side_wall) { int res = 0; int size = side_wall.child.size(); for (int i = 0; i < size; i++) { res = max(res, 1 + height(*side_wall.child[i])); } return res; } bool make_tree(fortress_tree &side_wall, fortress_tree &circle) { //만약에 이 서클이 side_wall 내부에 존재하고 child의 내부에 존재하지 않을때 child에 넣는다. //만약 이 서클이 side_wall 외부에 존재하는 경우 parent의 child를 이 서클로 바꾸고 이 서클의 child를 side_wall로 한다. int side_wall_x = side_wall.my_node[0]; int side_wall_y = side_wall.my_node[1]; int side_wall_r = side_wall.my_node[2]; int circle_x = circle.my_node[0]; int circle_y = circle.my_node[1]; int circle_r = circle.my_node[2]; //side_wall은 기존의 원이고 circle은 삽입하고자하는 원임 int d = sqr(side_wall_y - circle_y) + sqr(side_wall_x - circle_x); int r = sqr(side_wall_r - circle_r); //원의 내부에 존재한다. if (r > d) { int child_size = side_wall.child.size(); for (int i = 0; i < child_size; i++) { if (make_tree(*side_wall.child[i], circle)) { return true; } } side_wall.child.push_back(&circle); return true; } return false; } //루트 노드를 거치는 노드와 노드사이 가장 긴 길이를 구한다. int nodeToNode(fortress_tree& side_wall) { vector child_node = { 0,0 }; int res = 0; int child_size = side_wall.child.size(); for (int i = 0; i < child_size; i++) { child_node.push_back(1 + height(*side_wall.child[i])); } sort(child_node.begin(), child_node.end(), greater()); res = child_node[0] + child_node[1]; for (int i = 0; i < child_size; i++) { res = max(res, nodeToNode(*side_wall.child[i])); } return res; } int main() { int C; cin >> C; while (C--) { int N; cin >> N; vector circle(N); for (int i = 0; i < N; i++) cin >> circle[i].my_node[0] >> circle[i].my_node[1] >> circle[i].my_node[2]; fortress_tree side_wall; side_wall = circle[0]; sort(circle.begin(), circle.end()); for (int i = 1; i < circle.size(); i++) { make_tree(side_wall, circle[i]); } //vector res{ 0,0 }; //int root_child_size = side_wall.child.size(); //for (int i = 0; i < root_child_size; i++) { // res.push_back(dfs(*side_wall.child[i])); //} //sort(res.begin(), res.end(),greater()); //cout << res[0] + res[1] << "\n"; int res = nodeToNode(side_wall); cout << res << "\n"; } } ================================================ FILE: 알고스팟/울타리 잘라내기/6047198844.cpp ================================================ #include #include #include #include using namespace std; int divide_and_conquer(int left, int right, vector &board) { if (left == right) return board[left]; int mid = (left + right) / 2; int res = max(divide_and_conquer(left, mid, board), divide_and_conquer(mid + 1, right, board)); int lb = mid; int rb = mid + 1; int height = min(board[lb], board[rb]); res = max(res, height * 2); while (left < lb || right > rb) { if (left == lb || ((rb < right) && (board[lb - 1] < board[rb + 1]))) { ++rb; height = min(height, board[rb]); } else { --lb; height = min(height, board[lb]); } res = max(res, height * (rb - lb + 1)); } return res; } int main() { int C; cin >> C; while (C--) { int N; cin >> N; vector board; int fence; while (N--) { cin >> fence; board.push_back(fence); } cout << divide_and_conquer(0, board.size() - 1, board) << "\n"; } } ================================================ FILE: 알고스팟/울타리 잘라내기/sAp00n.py ================================================ """ N 개의 늘어져 있는 각자 다른높이의 울타리에서 잘라낼 수 있는 가장 큰 넓이를 구하는 문제. N = 2 * 10^4 시간제한은 1sec 이므로, 1 * 10^8 / 2 * 10^4(N) = 대락 O(N^2)복잡도 이하로 작성되어야 한다 하지만.... O(N!*N) 밖에 생각나지 않는다.. -- 이해 완료 -- 이해 후에 해답 안보고 다시 코드 작성하다가 머리 터질뻔함;; idx의 오른쪽만 열린방향으로 코드를 작성하기가 왤캐 힘드냐 """ from sys import stdin def recursion_slice(left, right): global list_of_fence if left == right: return list_of_fence[left] mid_idx = (left + right) // 2 recursion_max = max(recursion_slice(left, mid_idx), recursion_slice(mid_idx + 1, right)) height = min(list_of_fence[mid_idx], list_of_fence[mid_idx + 1]) mid_max = height left_idx, right_idx = mid_idx, mid_idx + 1 while left < left_idx and right_idx < right: if right_idx < right: if list_of_fence[right_idx + 1] >= list_of_fence[left_idx - 1]: right_idx += 1 height = min(height, list_of_fence[right_idx]) mid_max = max(mid_max, height * (right_idx + 1 - left_idx)) continue left_idx -= 1 height = min(height, list_of_fence[left_idx]) mid_max = max(mid_max, height * (right_idx + 1 - left_idx)) return max(recursion_max, mid_max) C = int(stdin.readline()) # test case 의 개수 for i in range(C): N = int(stdin.readline()) # 판자의 개수 global list_of_fence list_of_fence = list(map(int, stdin.readline().split())) print(recursion_slice(0, N - 1)) ================================================ FILE: 알고스팟/울타리 잘라내기 2/6047198844.cpp ================================================ #include #include #include #include using namespace std; ///미션 : 스택을 이용한다. // 내가 하려고 하는게 무엇인가. // 스택을 이용해서 푼다. 구하려는것은 각각의 판자가 만들수있는 최대 사각형의 크기이다. // 다시말해서 한 판자가 자신을 꼭 포함하면서 만들수있는 최대 사각형의 크기이다. // 그 말인 즉슨 자신보다 작은 판자가 양옆으로 나오는 순간 최대 사각형의 크기를 구할수있다는 뜻이다. // 한쪽으로만 나왔을 경우에는 구할수가없다. 한계를 모르기 때문이다. // 아직 값을 구하지못한 사각형을 스택에 넣는다고 생각하자. int fence_stack(vector &height) { height.push_back(0); int N = height.size(); stack st; int res = 0; for (int idx = 0; idx < N; idx++) { //스택이 비엇다는것은 비교가 불가능함을 의미한다. //while문은 스택에 남아있는 판자들을 확인하면서 right를 정해줄수있는지 판단한다. while (!st.empty()&&height[st.top()]>=height[idx]) { int h = height[st.top()]; st.pop(); int width = -1; if (st.empty()) { width = idx; } else { int left = st.top(); width = idx - left - 1; } res = max(res, h * width); } //right값이 정해지지 않았다. 따라서 스택에 넣는다. st.push(idx); } return res; } int main() { int C; cin >> C; while (C--) { int N; cin >> N; vector height(N); for (int i = 0; i < N; i++) cin >> height[i]; cout << fence_stack(height) << "\n"; } } ================================================ FILE: 알고스팟/원주율 외우기/6047198844.cpp ================================================ //(: TopCoder Դϴ.) // // TV  ڸ ܿ ŵ ϰ մϴ.̵ ܿ ϴ ϳ, ڸ ڸ ̻ ܿ ֽϴ.̵ ڸ ڸ ټ ڸ  ܿµ, ϸ 55555 123 ܿ ϴ ϰ մϴ. // // , ̵ ϴ : // // ڰ ( : 333, 5555) ̵ : 1 //ڰ 1 ϰų ( : 23456, 3210) ̵ : 2 // ڰ ( : 323, 54545) ̵ : 4 //ڰ ̷ ( : 147, 8642) ̵ : 5 // ̵ : 10 // Ϻΰ Է ־ , ̵ ּȭϵ ڵ 3ڸ 5ڸ а ͽϴ.ּ ̵ ϴ α׷ ۼϼ. //Է //5 //12341234 //11111222 //12122222 //22222222 //12673939 // // //4 //2 //5 //2 //14 #include #include #include #include #include #define INF 1000000 using namespace std; int check(string s) { int n = s.length(); // ڰ bool flag = false; for (int i = 0; i < n && !flag; i++) { if (s[0] != s[i]) flag = true; } if (!flag) return 1; //flag = true; // for (int i = 1; i < n && flag; i++) { if (s[i] != s[i - 1] + 1) flag = false; } if (flag) return 2; //flag = false; // for (int i = 1; i < n && !flag; i++) { if (s[i] != s[i - 1] - 1) flag = true; } if (!flag) return 2; //ΰ ڰ ư Ÿ //flag == true; for (int i = 2; i < n&&flag; i++) { if (s[i] != s[i % 2]) flag = false; } if (flag) return 4; //ڰ ̷ꋚ //flag == false for (int i = 1; i < n && !flag; i++) { if (s[i] - s[i - 1] != s[1] - s[0]) flag = true; } if (!flag) return 5; return 10; } int dp(int idx, int n ,string& s, vector & m) { int &res = m[idx]; if (res != -1) return res; int remain_lth = n - idx; if (remain_lth < 3) return INF; else if (remain_lth == 3 || remain_lth == 4 || remain_lth == 5) return res = check(s.substr(idx)); res = INF; for (int i = 3; i <= 5; i++) res = min(res, check(s.substr(idx, i)) + dp(idx + i, n, s, m)); return res; } int main() { int C; cin >> C; cin.ignore(); while (C--) { //ڿ ϳϳ ޴¹ string s; getline(cin, s); int n = s.length(); vector m(n, -1); cout << dp(0, n, s, m) << "\n"; } } ================================================ FILE: 알고스팟/장마가 찾아왔다/6047198844.cpp ================================================ // ̴ Ϸ翡 2͸ ö󰥼ִ. // 1͹ۿ ö Ѵ. //mϰ ¥ Ȯ Ȯ 75%̴. //m ȿ ̰ 칰 ö Ȯ? //climb(days, climbed) --> days climbedŭ ö, mϾȿ n̻ ö Ȯ. ޸̼ ؼ ڸ ִ δ. //climb(days, climbed) = 0.75 * climb(days+1, climbed+2) + 0.25 * climb(days+1, climbed+1) // 񰡿Ȯ 75% . Ȯ 25% Ѱ ä Ȯ̴. --> ̴. #include #include #include #define MAX_NUM 1000 using namespace std; int n; int m; double climb(int days, int climbed, vector> &vt) { if (days == m) return climbed >= n ? 1 : 0; double &res = vt[days][climbed]; if (res != -1) return res; return res = 0.75 * climb(days + 1, climbed + 2,vt) + 0.25 * climb(days + 1, climbed + 1,vt); } int main() { int C; cin >> C; while (C--) { cin >> n >> m; vector> vt(MAX_NUM + 1, vector(2 * MAX_NUM + 1, -1)); cout.precision(11); cout << climb(0, 0,vt) << "\n"; } } ================================================ FILE: 알고스팟/조세푸스 문제/6047198844.cpp ================================================ #include #include using namespace std; void josephus(int N, int K) { list survivors; for (int i = 1; i <= N; i++) survivors.push_back(i); list::iterator kill = survivors.begin(); while (N > 2) { kill = survivors.erase(kill); if (kill == survivors.end()) kill = survivors.begin(); N--; for (int cnt = 1; cnt < K; cnt++) { kill++; if (kill == survivors.end()) kill = survivors.begin(); } } cout << survivors.front() << " " << survivors.back() << "\n"; } int main() { int C; cin >> C; int N, K; while (C--) { cin >> N >> K; josephus(N, K); } } ================================================ FILE: 알고스팟/최대 증가 부분 수열/6047198844.cpp ================================================ #include #include #include using namespace std; int lis(int idx, int N, vector &seq, vector &memo) { int& res = memo[idx + 1]; if (res != -1) return res; res = 1; for (int start = idx + 1; start < N; start++) { if (idx == -1 || seq[idx] < seq[start]) res = max(res, 1 + lis(start, N, seq, memo)); } return res; } int main() { int C; cin >> C; while (C--) { int N; cin >> N; vector seq(N); vector memo(N + 1, -1); for (int i = 0; i < N; i++) { cin >> seq[i]; } cout << lis(-1, N, seq, memo) - 1 << "\n"; } } ================================================ FILE: 알고스팟/쿼드트리/6047198844.cpp ================================================ #include #include using namespace std; string quadtree(string s) { if (s[0] == 'w' || s[0] == 'b') { string ret = ""; ret += s[0]; return ret; } else { int idx = 1; string res[4]; for (int i = 0; i < 4; i++) { res[i] = quadtree(s.substr(idx)); idx += res[i].size(); } return s[0] + res[2] + res[3] + res[0] + res[1]; } } int main() { int n; cin >> n; string s; while (n--) { cin >> s; cout << quadtree(s) << "\n"; } } ================================================ FILE: 알고스팟/쿼드트리/sAp00n.py ================================================ # 알고스팟 https://www.algospot.com/judge/problem/read/QUADTREE """ 최대 2^20 * 2^20 크기의 픽셀을 가진 쿼드 트리로 압축된 이미지를 상하로 반전된 이미지를 쿼드트리로 압축시켜 출력하는 문제입니다. n = 테스트케이스의 수이고 이후 n개의 줄에 걸쳐 압축된 이미지가 문자열로서 입력됩니다. """ from sys import stdin from collections import deque def count_ele(case): ele = case.popleft() if ele != 'x': return ele return [count_ele(case), count_ele(case), count_ele(case), count_ele(case)] def reverse_case(section): if len(section) == 1: return str(section) return 'x' + reverse_case(section[2]) + reverse_case(section[3]) + reverse_case(section[0]) + reverse_case(section[1]) n = int(stdin.readline()) test_case = [deque(stdin.readline().strip('\n')) for i in range(n)] for case in test_case: section = count_ele(case) print(reverse_case(section)) ================================================ FILE: 알고스팟/타일링 방법의 수 세기/6047198844.cpp ================================================ //1000000007 #include #include #include using namespace std; int memo[101]; long long dp(int n) { if (n == 1 || n == 2) return n; if (memo[n] != -1) return memo[n] % 1000000007; return memo[n] = (dp(n - 1) % 1000000007 + dp(n - 2) % 1000000007) % 1000000007; } int main() { int C,N; cin >> C; memset(memo, -1, sizeof(memo)); while (C--) { cin >> N; cout << dp(N) << "\n"; } } ================================================ FILE: 알고스팟/트리 순회 순서 변경/6047198844.cpp ================================================ #include #include #include using namespace std; vector slice(const vector & order, int begin, int end) { return vector(order.begin() + begin, order.begin() + end); } //후위 순회를 출력하는 함수. //preorder은 root를 알려준다. //inorder은 preorder에서 얻은 root를 기준으로 좌측 서브 트리와 우측 서브 트리를 구할수있게 한다 void printPost(const vector & preorder, const vector & inorder) { if (preorder.empty()) return; int treeSize = preorder.size(); int root = preorder[0]; const int L = find(inorder.begin(), inorder.end(), root) - inorder.begin(); //좌측 서브 트리 후위 방문 printPost(slice(preorder, 1, L + 1), slice(inorder, 0, L)); //우측 서브 트리 후위 방문 printPost(slice(preorder, L + 1, treeSize), slice(inorder, L + 1, treeSize)); //이제 루트 출력 cout << root << " "; } int main() { int C; cin >> C; while (C--) { int N; int num; cin >> N; vector preorder; for (int i = 0; i < N; i++) { cin >> num; preorder.push_back(num); } vector inorder; for (int i = 0; i < N; i++) { cin >> num; inorder.push_back(num); } printPost(preorder, inorder); cout << "\n"; } } ================================================ FILE: 알고스팟/팬미팅/6047198844.cpp ================================================ #include #include #include using namespace std; //a와 b를 곱한값을 리턴한다. vector multiply(const vector& a, const vector& b) { int an = a.size(); int bn = b.size(); vector res(an + bn + 1, 0); for (int i = 0; i < an; i++) { for (int j = 0; j < bn; j++) { res[i + j] += a[i] * b[j]; } } return res; } //a가 항상 크다고 가정한다. a에서 b를 뺀다. void subFrom(vector& a, vector& b) { int bn = b.size(); for (int i = 0; i < bn; i++) a[i] -= b[i]; } //a + b * (10^k) void addTo(vector& a, vector& b, int k) { //vector bm(k); //int bn = b.size(); //for (int i = 0; i < bn; i++) // bm.push_back(b[i]); //while (a.size() < bm.size()) // a.push_back(0); //for (int i = 0; i < bm.size(); i++) // a[i] += bm[i]; int length = b.size(); a.resize(max(a.size(), b.size() + k)); for (int i = 0; i < length; i++) a[i + k] += b[i]; } vector karatsuba(const vector& a, const vector& b) { int an = a.size(); int bn = b.size(); if (an < bn) karatsuba(b, a); if (an == 0 || bn == 0) return vector(); if (an <= 50) return multiply(a, b); int half = an / 2; vector a0(a.begin(), a.begin() + half); vector a1(a.begin() + half, a.end()); vector b0(b.begin(), b.begin() + min(bn, half)); vector b1(b.begin() + min(bn, half), b.end()); vector z0 = karatsuba(a1, b1); vector z1 = karatsuba(a0, b0); addTo(a1, a0, 0); addTo(b1, b0, 0); vector z2 = karatsuba(a1, b1); subFrom(z2, z0); subFrom(z2, z1); vector res; addTo(res, z0, half + half); addTo(res, z2, half); addTo(res, z1, 0); return res; } int main() { int C; cin >> C; while (C--) { string A; string B; cin >> A >> B; int N = A.size(); vector group(N); for (int i = 0; i < N; i++) group[i] = (A[N - 1 - i] == 'M'); int M = B.size(); vector fan(M); for (int i = B.size() - 1; i >= 0; i--) fan[i] = (B[i] == 'M'); vector res = karatsuba(group, fan); int cnt = 0; //맴버의수는 항상 팬의 수 이하이다. for (int i = N - 1; i < M; i++) if (!res[i]) cnt++; cout << cnt << "\n"; } } ================================================ FILE: 알고스팟/팬미팅/sAp00n.py ================================================ from sys import stdin def simple_mult(list_of_fan, list_of_members): computing_result = [0] * (len(list_of_fan) + len(list_of_members) - 1) for member_idx in range(len(list_of_members)): for fan_idx in range(len(list_of_fan)): computing_result[member_idx + fan_idx] += list_of_members[member_idx] * list_of_fan[fan_idx] # print(f'compute: {computing_result}') computing_result = computing_result[::-1] return computing_result def adder(a, b): if len(b) > len(a): a, b = b, a result = [a[i] + b[i] if i < len(b) else a[i] for i in range(len(a))] return result def kara(list_of_fan, list_of_members): len_of_list = len(list_of_fan) if len_of_list < 50: return simple_mult(list_of_fan, list_of_members) fan_list01, fan_list02 = list_of_fan[:len_of_list // 2], list_of_fan[len_of_list // 2:] mem_list01, mem_list02 = list_of_members[:len_of_list // 2], list_of_members[len_of_list // 2:] z2 = kara(fan_list02, mem_list02) z0 = kara(fan_list01, mem_list01) z1 = kara(adder(fan_list01, fan_list02), adder(mem_list01, mem_list02)) result = adder(adder(z2 + [0] * (len_of_list // 2), z1 + [0] * (len_of_list // 4)), z0) return result def sol(): list_of_members = [1 if member == 'M' else 0 for member in stdin.readline().strip('\n')] list_of_members = list_of_members[::-1] len_of_mem = len(list_of_members) list_of_fan = [1 if fan == 'M' else 0 for fan in stdin.readline().strip('\n')] len_of_fan = len(list_of_fan) diff = len(list_of_fan) - len(list_of_members) list_of_members = [0] * diff + list_of_members result = kara(list_of_fan, list_of_members) result = result[len_of_mem - 1:len_of_fan] counter = 0 for i in result: if i == 0: counter += 1 return counter C = int(stdin.readline()) for _ in range(C): print(sol()) ================================================ FILE: 알고스팟/폴리오미노/6047198844.cpp ================================================ #include #include #define ll long long using namespace std; long long memo[101][101]; ll dp(int used, int remain) { if (remain == 0) return 1; ll &res = memo[used][remain]; if (res != -1) return res; res = 0; for (int cnt = 1; cnt <= remain; cnt++) { int mul = used ? (used + cnt - 1) : 1; res += (mul * dp(cnt, remain - cnt)% 10000000); } return res % 10000000; } int main() { int C; cin >> C; int n; memset(memo, -1, sizeof(memo)); while (C--) { cin >> n; cout << dp(0, n) << "\n"; } } ================================================ FILE: 알고스팟/피크닉/dkdlelk99.cpp ================================================ #include #include #include using namespace std; bool areFriend[10][10]; int n, m; //쌍의 개수 (답) int countPairs(vector& relation) { //짝이 없는 번호가 가장 빠른 학생 찾기 int first = -1; for (int i = 0; i < n; i++) { if (!relation[i]) { first = i; break; } } //기저 사례: 모든 학생이 짝을 찾음. 즉, 한가지 방법을 찾음 if (first == -1) return 1; int ret = 0; for (int pairWith = first + 1; pairWith < n; pairWith++) { if (!relation[pairWith] && areFriend[first][pairWith]) { relation[first] = relation[pairWith] = 1; ret += countPairs(relation); relation[first] = relation[pairWith] = 0; } } return ret; } int main() { int testCase, r1, r2, answer; vector relation; cin >> testCase; while (testCase--) { cin >> n >> m; relation = vector(n, 0); memset(areFriend, 0, sizeof(areFriend)); answer = 0; for (int i = 0; i < m; i++) { cin >> r1 >> r2; areFriend[r1][r2] = areFriend[r1][r2] = true; } answer = countPairs(relation); cout << answer < #include #include #include #include #include using namespace std; int n; int m; int A[100]; int B[100]; int cache[101][101]; const long long NEGINF = numeric_limits::min(); int LIS(int A_idx, int B_idx) { int &res = cache[A_idx + 1][B_idx + 1]; if (res != -1) return res; //A B迭 -Ѵ밡 ƴ ̻ ʴ. //A_idx B_idx ū max_element Ѵ. long long a = A_idx == -1 ? NEGINF : A[A_idx]; long long b = B_idx == -1 ? NEGINF : B[B_idx]; long long maxElement = max(a, b); res = 2; for (int nextAidx = A_idx + 1; nextAidx < n; nextAidx++) if (maxElement < A[nextAidx]) res = max(res, 1 + LIS(nextAidx, B_idx)); for (int nextBidx = B_idx + 1; nextBidx < m; nextBidx++) if (maxElement < B[nextBidx]) res = max(res, 1 + LIS(A_idx, nextBidx)); return res; } int main() { int c; cin >> c; while (c--) { cin >> n >> m; for (int i = 0; i < n; i++) cin >> A[i]; for (int i = 0; i < m; i++) cin >> B[i]; memset(cache, -1, sizeof(cache)); cout << LIS(-1, -1) - 2 << "\n"; } }