diff --git a/problems/week09/Programmers_340210/DaewonKim/340210.cpp b/problems/week09/Programmers_340210/DaewonKim/340210.cpp new file mode 100644 index 0000000..22dec09 --- /dev/null +++ b/problems/week09/Programmers_340210/DaewonKim/340210.cpp @@ -0,0 +1,134 @@ +#include +#include +#include +#include + +using namespace std; + +/* +1. 문자열 파싱 + +2. 수식 탐색. -> 2~9진법 까지 가능한 진법의 후보 추출 +-> for base in 2~9까지 + for e in expres + 숫자를 모두 탐색 + - if (현재 숫자가 base보다 크다면) + 종료 + - 모든 숫자가 base보다 작으므로, + - base 진법에 대한 수식을 실행. + - base 진법을 기반으로 stoi(숫자, nullptr, base)로 해서 10진법 변환 + - 연산자 종료는 +, -만 있으므로 +면 그대로, 아니면 -실행. + - 결과 값과 수식 C의 값(10진법으로 변환한 후의 값)을 비교 + - if( 값이 동일) + - 현재 진법은 가능하다는 뜻이므로, 진법 후보에 추가 + +3. X판별 +- 가능한 진법이 1개라면 그 값을 X에 채움. +- 진법이 여러 개, + - 진법들에 대해서 result를 만듬. + - result가 같으면, 그 result를 반환 + - 다르면, X를 그대로 설정. + + +*/ + +struct Expr { + string a, op, b, c; // A, 연산자(+/-), B, 결과 C ("X"일 수 있음) +}; + + +/* + 10진수 정수 n → base진법 문자열 + stoi의 역방향은 표준 함수가 없으므로 직접 구현 + 예) toBase(6, 6) = "10", toBase(6, 7) = "6" + + + -> 표기를 특정 진법으로 해야하기 때문에. +*/ +string toBase(int n, int base) { + if (n == 0) return "0"; + string s; + while (n > 0) { + s += char('0' + n % base); + n /= base; + } + reverse(s.begin(), s.end()); + return s; +} + +/* + + - stoi는 무효 숫자를 만나면 조용히 멈추므로 -> ex: (stoi("17", nullptr, 7) == 1) + - stoi함수를 사용하기 위해 아래 유효성을 만족하는지 체크하는 함수를 먼저 시행해야함. + - 현재 진법보다 숫자가 더 크다면, 그 진법으로 표현이 안되서 +*/ +bool validDigits(const string& s, int base) { + for (char ch : s) { + if (ch - '0' >= base) return false; + } + return true; +} + +// A op B 를 base진법으로 계산해 10진수로 반환 +int calc(const Expr& e, int base) { + int x = stoi(e.a, nullptr, base); // base진법 문자열 → 10진수 + int y = stoi(e.b, nullptr, base); + return (e.op == "+") ? x + y : x - y; +} + +vector solution(vector expressions) { + // 파싱 + vector exprs; + for (const string& line : expressions) { + stringstream ss(line); + Expr e; + string eq; + ss >> e.a >> e.op >> e.b >> eq >> e.c; + exprs.push_back(e); + } + + // 가능한 진법 후보 찾기 + vector candidates; + for (int base = 2; base <= 9; ++base) { + bool ok = true; + + // 현재 진법에 대해서 모든 수식을 순회하면서 비교. + for (const Expr& e : exprs) { + // base 진법의 숫자가 현재 수식의 숫자보다 더 작거나 같으면 불가. + // -> 6진법인데 숫자 7이 수식에 있다면, 불가능한 경우라고 판단. + if (!validDigits(e.a, base) || !validDigits(e.b, base)) { ok = false; break; } + if (e.c == "X") continue; + if (!validDigits(e.c, base)) { ok = false; break; } + + // 위에서 유효성 검사를 통과했으므로 stoi가 안전하게 전체를 읽음 + // base 진법으로 계산한 결과가 수식과 다르다면? + if (calc(e, base) != stoi(e.c, nullptr, base)) + { + ok = false; + break; + } + } + + // 모든 조건을 만족했으면 후보에 추가. + if (ok) candidates.push_back(base); + } + + // X 채우기 + vector answer; + for (const Expr& e : exprs) { + // X인 것만 보기 위해 x가 아닌 건 건너뜀. + if (e.c != "X") continue; + + // 결과를 각 진법의 "표기 문자열"로 비교 + string result = ""; + bool same = true; + for (int base : candidates) { + string r = toBase(calc(e, base), base); + if (result.empty()) result = r; + else if (result != r) { same = false; break; } + } + + answer.push_back(e.a + " " + e.op + " " + e.b + " = " + (same ? result : "?")); + } + + return answer; +} \ No newline at end of file diff --git a/problems/week09/Programmers_340211/DaewonKim/340211.cpp b/problems/week09/Programmers_340211/DaewonKim/340211.cpp new file mode 100644 index 0000000..5b39f86 --- /dev/null +++ b/problems/week09/Programmers_340211/DaewonKim/340211.cpp @@ -0,0 +1,99 @@ +#include +#include +#include + + +using namespace std; + +int solution(vector> points, vector> routes) { + int robotCount = (int)routes.size(); + + // robotPaths[robot][time] = time초에 robot이 있는 좌표 {row, col} + vector>> robotPaths(robotCount); + + for (int robot = 0; robot < robotCount; ++robot) { + // ---------- 출발 지점 ---------- + int startPointId = routes[robot][0]; // 출발 지점 번호 (1부터 시작) + int startPointIndex = startPointId - 1; // points 벡터 인덱스 (0부터 시작) + + // 시작 지점에 대한 좌표 + int curRow = points[startPointIndex][0]; + int curCol = points[startPointIndex][1]; + robotPaths[robot].push_back({ curRow, curCol }); // time = 0 + + // ---------- 다음 목표 지점들을 차례로 이동 ---------- + int routeLength = (int)routes[robot].size(); + for (int routeOrder = 1; routeOrder < routeLength; ++routeOrder) { + int targetPointId = routes[robot][routeOrder]; + int targetPointIndex = targetPointId - 1; + + int targetRow = points[targetPointIndex][0]; + int targetCol = points[targetPointIndex][1]; + + // row 이동을 먼저 + while (curRow != targetRow) { + if (targetRow > curRow) { + curRow++; + } + else { + curRow--; + } + robotPaths[robot].push_back({ curRow, curCol }); + } + + // 그다음 col 이동 + while (curCol != targetCol) { + if (targetCol > curCol) { + curCol++; + } + else { + curCol--; + } + robotPaths[robot].push_back({ curRow, curCol }); + } + } + } + + + // 가장 긴 거리를 가진 로봇의 이동 시간 만큼 설정. + int maxTime = 0; + for (auto& path : robotPaths) { + maxTime = max(maxTime, (int)path.size()); + } + + // robotsAtCell[row][col] = 현재 시간에 (row, col)에 있는 로봇 수 + vector> robotsAtCell(101, vector(101, 0)); + int dangerCount = 0; + + for (int time = 0; time < maxTime; ++time) { + // 1) 현재 시간의 로봇 위치를 기록하고 위험 상황을 센다 + for (int robot = 0; robot < robotCount; ++robot) { + + // 이미 도착했다면 + if (time >= robotPaths[robot].size()) + continue; + + + int row = robotPaths[robot][time].first; + int col = robotPaths[robot][time].second; + + robotsAtCell[row][col]++; + if (robotsAtCell[row][col] == 2) { + dangerCount++; + } + } + + // 2) 기록한 칸만 0으로 되돌린다 + for (int robot = 0; robot < robotCount; ++robot) { + // 이미 도착한 로봇은 제외 + if (time >= (int)robotPaths[robot].size()) { + continue; + } + int row = robotPaths[robot][time].first; + int col = robotPaths[robot][time].second; + robotsAtCell[row][col] = 0; + } + } + + return dangerCount; +} \ No newline at end of file diff --git a/problems/week09/Programmers_340212/DaewonKim/340212.cpp b/problems/week09/Programmers_340212/DaewonKim/340212.cpp new file mode 100644 index 0000000..52cacb4 --- /dev/null +++ b/problems/week09/Programmers_340212/DaewonKim/340212.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +#include + +using namespace std; + +int n = 0; +long long maxLevel = 0; +long long minLevel = 0; + +// 난이도, 소요 시간은 모두 양의 정수며, 숙련도도 양의 정수 +// diff > level +// diff-level만큼 틀린다. + time_cur만큼의 시간을 사용한다. +// (diff-level) * (time_cur + time_prev) + time_cur + +void binarySearch(int leftIdx, int rightIdx, vector& levels, + vector& diffs, vector& times, long long &limit) +{ + if(leftIdx > rightIdx) + return; + + long long midIdx = (leftIdx + rightIdx) /2; + long long curLevel = levels[midIdx]; + long long totalTime =0; + + for(int i=0; i 0) + prevTime = times[i-1]; + long long curDiff = diffs[i]; + long long curTime = times[i]; + + if(curLevel >= curDiff) + totalTime += curTime; + else if (curLevel < curDiff) + { + // (diff-level) * (time_cur + time_prev) + time_cur + totalTime += (curTime + ((curTime+prevTime) * (curDiff-curLevel)) ); + } + + } + // 현재 수행한 레벨이 시간 내에 들어온다 -> 더 작은 레벨을 계산해본다. + if(totalTime <= limit) + { + // 시간 안에 들어왔는데 최소 레벨보다 현재 레벨이 더 작으면. + if(minLevel > curLevel) + { + minLevel = curLevel; + } + binarySearch(leftIdx, midIdx-1, levels, diffs, times, limit); + + } + // totalTime > limit 시간 안에 수행 불가. -> 큰 레벨을 수행해본다 + else + { + binarySearch(midIdx+1, rightIdx,levels, diffs, times, limit); + } + +} + +int solution(vector diffs, vector times, long long limit) { + int answer = 0; + n = (int)diffs.size(); // 퍼즐 n개 + maxLevel = *max_element(diffs.begin(),diffs.end()); + minLevel = maxLevel; // 초기 최소 숙련도는 최상으로 설정. + + // 현재 가능한 maxLevel을 기준으로 + // 이진 탐색으로 찾는다. + vector levels (maxLevel+1, 0); + for(int i=0; i<(int)levels.size(); ++i) + { + levels[i] = i; + } + + long long leftIdx = 1; + long long rightIdx = (int)levels.size()-1; + binarySearch(leftIdx, rightIdx, levels, diffs, times, limit); + answer = minLevel; + + return answer; +} \ No newline at end of file diff --git a/problems/week09/Programmers_340213/DaewonKim/340213.cpp b/problems/week09/Programmers_340213/DaewonKim/340213.cpp new file mode 100644 index 0000000..e4b7de5 --- /dev/null +++ b/problems/week09/Programmers_340213/DaewonKim/340213.cpp @@ -0,0 +1,65 @@ +#include +#include +#include + +using namespace std; + +int toSec(string time) +{ + int mm = stoi(time.substr(0, 2)); + int ss = stoi(time.substr(3, 2)); + + return mm * 60 + ss; +} + +string toTime(int time) +{ + int mm = time / 60; + int ss = time % 60; + + string result = ""; + + if(mm < 10) result += "0"; + result += to_string(mm); + + result += ":"; + + if(ss < 10) result += "0"; + result += to_string(ss); + + return result; +} + +string solution(string video_len,string pos,string op_start,string op_end,vector commands) +{ + int videoLen = toSec(video_len); + int cur = toSec(pos); + int opStart = toSec(op_start); + int opEnd = toSec(op_end); + + // 명령 실행 전에 현재 위치 검사 + if(opStart <= cur && cur <= opEnd) + { + cur = opEnd; + } + + for(string command : commands) + { + if(command == "prev") + { + cur = max(0, cur - 10); + } + else if(command == "next") + { + cur = min(videoLen, cur + 10); + } + + // 명령 실행 후 오프닝 검사 + if(opStart <= cur && cur <= opEnd) + { + cur = opEnd; + } + } + + return toTime(cur); +} \ No newline at end of file diff --git a/problems/week10/Programmers_250134/DaewonKim/250134.cpp b/problems/week10/Programmers_250134/DaewonKim/250134.cpp new file mode 100644 index 0000000..351f910 --- /dev/null +++ b/problems/week10/Programmers_250134/DaewonKim/250134.cpp @@ -0,0 +1,212 @@ +#include +#include +#include + +using namespace std; + +struct State +{ + int redX; + int redY; + int blueX; + int blueY; + int turn; + + vector> redVisit; + vector> blueVisit; +}; + +int solution(vector> maze) +{ + int n = (int)maze.size(); + int m = (int)maze[0].size(); + + int redStartX = 0; + int redStartY = 0; + int blueStartX = 0; + int blueStartY = 0; + + int redEndX = 0; + int redEndY = 0; + int blueEndX = 0; + int blueEndY = 0; + + for(int row = 0; row < n; ++row) + { + for(int col = 0; col < m; ++col) + { + if(maze[row][col] == 1) + { + redStartX = row; + redStartY = col; + } + else if(maze[row][col] == 2) + { + blueStartX = row; + blueStartY = col; + } + else if(maze[row][col] == 3) + { + redEndX = row; + redEndY = col; + } + else if(maze[row][col] == 4) + { + blueEndX = row; + blueEndY = col; + } + } + } + + vector> redVisit(n, vector(m, false)); + vector> blueVisit(n, vector(m, false)); + + redVisit[redStartX][redStartY] = true; + blueVisit[blueStartX][blueStartY] = true; + + queue q; + + q.push({ + redStartX, + redStartY, + blueStartX, + blueStartY, + 0, + redVisit, + blueVisit + }); + + int dx[4] = {1, -1, 0, 0}; + int dy[4] = {0, 0, 1, -1}; + + while(!q.empty()) + { + State cur = q.front(); + q.pop(); + + bool redArrived = + cur.redX == redEndX && cur.redY == redEndY; + + bool blueArrived = + cur.blueX == blueEndX && cur.blueY == blueEndY; + + if(redArrived && blueArrived) + { + return cur.turn; + } + + vector> redNextList; + vector> blueNextList; + + // 빨간 수레가 이미 도착했다면 현재 위치에 고정 + if(redArrived) + { + redNextList.push_back({cur.redX, cur.redY}); + } + else + { + for(int dir = 0; dir < 4; ++dir) + { + int nextRedX = cur.redX + dx[dir]; + int nextRedY = cur.redY + dy[dir]; + + if(nextRedX < 0 || nextRedX >= n || + nextRedY < 0 || nextRedY >= m) + { + continue; + } + + if(maze[nextRedX][nextRedY] == 5) + { + continue; + } + + if(cur.redVisit[nextRedX][nextRedY]) + { + continue; + } + + redNextList.push_back({nextRedX, nextRedY}); + } + } + + // 파란 수레가 이미 도착했다면 현재 위치에 고정 + if(blueArrived) + { + blueNextList.push_back({cur.blueX, cur.blueY}); + } + else + { + for(int dir = 0; dir < 4; ++dir) + { + int nextBlueX = cur.blueX + dx[dir]; + int nextBlueY = cur.blueY + dy[dir]; + + if(nextBlueX < 0 || nextBlueX >= n || + nextBlueY < 0 || nextBlueY >= m) + { + continue; + } + + if(maze[nextBlueX][nextBlueY] == 5) + { + continue; + } + + if(cur.blueVisit[nextBlueX][nextBlueY]) + { + continue; + } + + blueNextList.push_back({nextBlueX, nextBlueY}); + } + } + + for(auto redNext : redNextList) + { + for(auto blueNext : blueNextList) + { + int nextRedX = redNext.first; + int nextRedY = redNext.second; + + int nextBlueX = blueNext.first; + int nextBlueY = blueNext.second; + + // 두 수레가 같은 칸으로 이동하면 안 됨 + if(nextRedX == nextBlueX && nextRedY == nextBlueY) + { + continue; + } + + // 두 수레가 서로 위치를 바꾸면 안 됨 + if(nextRedX == cur.blueX && nextRedY == cur.blueY && + nextBlueX == cur.redX && nextBlueY == cur.redY) + { + continue; + } + + State nextState = cur; + + nextState.redX = nextRedX; + nextState.redY = nextRedY; + nextState.blueX = nextBlueX; + nextState.blueY = nextBlueY; + nextState.turn = cur.turn + 1; + + if(!redArrived) + { + nextState.redVisit[nextRedX][nextRedY] = true; + } + + if(!blueArrived) + { + nextState.blueVisit[nextBlueX][nextBlueY] = true; + } + + q.push(nextState); + } + } + } + + return 0; +} \ No newline at end of file diff --git a/problems/week10/Programmers_250135/DaewonKim/250135.cpp b/problems/week10/Programmers_250135/DaewonKim/250135.cpp new file mode 100644 index 0000000..6aafa97 --- /dev/null +++ b/problems/week10/Programmers_250135/DaewonKim/250135.cpp @@ -0,0 +1,117 @@ +#include +#include +#include + +using namespace std; +/* + 초침이 시침 or 분침과 겹칠 때 마다 알림이 울림. + + h1, m1, s1 -> 시작 시 분 초 + h2, m2, s2 -> 끝 시 분 초 + + 출력 : 알람이 울리는 횟수 + + 시침 분침 초침이 모두 겹칠 때 -> 알람은 1번만 + + 현재 초침이 어딧는지 알아야 함. + 시침의 경우-> 초나 분처럼 변환을 해줘야 함. 1시인 경우 -> 5분이나 5초와 동일 + 시침 * 5를 해줘야 함. + + for나 while의 주기 설정을 어떻게? + 종료 -> h2 - h1 , m2 - m1 , s2 -s1 + -> 전부 초로 계산 +*/ +int toSecond(int h, int m, int s) +{ + return h * 3600 + m * 60 + s; +} + +int getSecondHand(int t) +{ + return (t * 720) % 43200; +} + +int getMinuteHand(int t) +{ + return (t * 12) % 43200; +} + +int getHourHand(int t) +{ + return t % 43200; +} + +bool isOverlapNow(int t) +{ + int second = getSecondHand(t); + int minute = getMinuteHand(t); + int hour = getHourHand(t); + + return second == minute || second == hour; +} + +int solution(int h1, int m1, int s1, int h2, int m2, int s2) +{ + int answer = 0; + + int start = toSecond(h1, m1, s1); + int end = toSecond(h2, m2, s2); + + // 시작 시각에 이미 겹쳐 있으면 1번 카운트 + if(isOverlapNow(start)) + { + answer++; + } + + for(int t = start; t < end; ++t) + { + int secondCur = getSecondHand(t); + int minuteCur = getMinuteHand(t); + int hourCur = getHourHand(t); + + int secondNext = getSecondHand(t + 1); + int minuteNext = getMinuteHand(t + 1); + int hourNext = getHourHand(t + 1); + + // 초침이 59초 -> 00초로 넘어가면 값이 0이 되므로, + // 비교를 위해 한 바퀴 끝인 43200으로 처리 + if(secondNext == 0) + { + secondNext = 43200; + } + + bool crossMinute = false; + bool crossHour = false; + + // 초침이 분침을 따라잡거나 추월한 경우 + if(secondCur < minuteCur && secondNext >= minuteNext) + { + crossMinute = true; + } + + // 초침이 시침을 따라잡거나 추월한 경우 + if(secondCur < hourCur && secondNext >= hourNext) + { + crossHour = true; + } + + if(crossMinute) + { + answer++; + } + + if(crossHour) + { + answer++; + } + + // 시침, 분침, 초침이 동시에 겹치는 경우는 알람 1번만 + // 대표적으로 12:00:00 + if(crossMinute && crossHour && (t + 1) % 43200 == 0) + { + answer--; + } + } + + return answer; +} \ No newline at end of file diff --git a/problems/week10/Programmers_250136/DaewonKim/250136.cpp b/problems/week10/Programmers_250136/DaewonKim/250136.cpp new file mode 100644 index 0000000..4bed8c7 --- /dev/null +++ b/problems/week10/Programmers_250136/DaewonKim/250136.cpp @@ -0,0 +1,91 @@ +#include +#include +#include +#include + +using namespace std; +/* + 가로 : m + 세로 : n + + 수직으로 단 1개의 시추관 -> 가장 많은 석유를 뽑을 수 있는 위치 + + 크기 배열 + board[n][m] + + 시추관을 꽂을 때, 붙어있는 석유 + 지나가는 석유 부분은 전부 시추 가능 + -> bfs + + 방향 고려 + + bfs + + 1인 곳에서부터 bfs를 들어가야함. +*/ +int solution(vector> land) { + int answer = 0; + + int n = (int)land.size(); // 행 + int m = (int)land[0].size(); // 열 + + vector> visited(n, vector(m, false)); + vector petroleums(m, 0); // 각 열에서 얻을 수 있는 석유량 + + int dx[4] = {1, -1, 0, 0}; + int dy[4] = {0, 0, 1, -1}; + + queue> q; + + for(int col = 0; col < m; ++col) + { + for(int row = 0; row < n; ++row) + { + // 아직 방문하지 않은 석유 덩어리에서만 BFS 시작 + if(land[row][col] == 1 && !visited[row][col]) + { + int oilSize = 0; // 현재 석유 덩어리 크기 + vector usedCol(m, false); // 현재 덩어리가 걸친 열 체크 + + q.push({row, col}); + visited[row][col] = true; + + while(!q.empty()) + { + auto [x, y] = q.front(); + q.pop(); + + oilSize++; + usedCol[y] = true; + + for(int k = 0; k < 4; ++k) + { + int nextX = x + dx[k]; + int nextY = y + dy[k]; + + // 범위 검사를 먼저 해야 함 + if(nextX >= 0 && nextX < n && + nextY >= 0 && nextY < m && + land[nextX][nextY] == 1 && + !visited[nextX][nextY]) + { + visited[nextX][nextY] = true; + q.push({nextX, nextY}); + } + } + } + + // 현재 석유 덩어리가 걸친 모든 열에 덩어리 크기 추가 + for(int c = 0; c < m; ++c) + { + if(usedCol[c]) + { + petroleums[c] += oilSize; + } + } + } + } + } + + answer = *max_element(petroleums.begin(), petroleums.end()); + + return answer; +} \ No newline at end of file diff --git a/problems/week10/Programmers_250137/DaewonKim/250137.cpp b/problems/week10/Programmers_250137/DaewonKim/250137.cpp new file mode 100644 index 0000000..8b4aa42 --- /dev/null +++ b/problems/week10/Programmers_250137/DaewonKim/250137.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +#include + +using namespace std; +/* + t초 동안 붕대감기 + 1초마다 x만큼 회복 + t초를 다 감으면 y만큼 체력 추가로 회복 + + 기술 사용 중 공격 받 -> 기술 취소 + 공격 당하는 순간 체력 회복 X + 공격 당해 기술 취소 or 기술이 끝나면 바로 붕대 감기 다시 사용 -> 연속 시간 0 + + bandage[0] = t + bandage[1] = x + bandage[2] = y + health = 최대체력 + + attacks - 공격 시간을 기준으로 오름차순 정렬됨. + attacks[0] = 공격시간 + attacks[1] = 피해량 + + + 출력: 모든 공격이 끝난 직후 남은 체력 + 죽으면 -1 + 시간 복잡도 : O(n^2) 가능 +*/ +int solution(vector bandage, int health, vector> attacks) { + int answer = 0; + // 진행 시간 + int curTime = 0; + + int t = bandage[0]; // 붕대 감기 시간 + int x = bandage[1]; // 1초 당 체력 회복 + int y = bandage[2]; // 추가 체력 회복 + int curHealth = health; // 현재 체력량 + int skillTime = 0; // 공격받은 시간 체크 + queue> q; + for(auto& it : attacks) + { + q.push({it[0], it[1]}); + } + + while(!q.empty()) + { + auto it = q.front(); + // 공격시간이 아직 아니라면 + if(curTime < it.first) + { + curHealth += x; + skillTime++; + } + else if(curTime == it.first) + { + curHealth -= it.second; + skillTime = 0; + q.pop(); + } + if(skillTime == t) + { + curHealth += y; + skillTime = 0; + } + + // 최대 체력 제한 + if(curHealth >= health) + curHealth = health; + + if(curHealth <= 0) + { + answer = -1; + break; + } + answer = curHealth; + curTime++; + } + + return answer; +} \ No newline at end of file