알고리즘 문제/BOJ
16236번 아기 상어
parkit
2019. 1. 14. 11:43
728x90
반응형
문제 : https://www.acmicpc.net/problem/16236
저번에 푼 코드 : http://hsdevelopment.tistory.com/114
SW 역량 테스트 대비할 겸, 다시 풀어보았다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | #include <iostream> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> #include <map> using namespace std; typedef struct babyshark { int Size; int eat; int y; int x; int time; }babyshark; babyshark bs; // 왼쪽, 위쪽부터. int dy[4] = { -1, 0, 1, 0 }; int dx[4] = { 0, -1, 0, 1 }; int N = 0; int Map[22][22] = { 0, }; bool cmp(const pair< pair<int, int>, int> & a, const pair< pair<int, int>, int> & b) { // 거리 우선 if (a.second == b.second) { // 행이 같다면, 가장 왼쪽에 있는 것부터 if (a.first.first == b.first.first) return a.first.second < b.first.second; else return a.first.first < b.first.first; } else return a.second < b.second; } void BFS() { while (1) { queue<pair<int, int> > q; bool visit[22][22] = { false, }; q.push({ bs.y, bs.x }); visit[bs.y][bs.x] = true; vector<pair< pair<int, int>, int> > v; int ret = 0; while (!q.empty()) { int qSize = q.size(); while (qSize--) { int r = q.front().first; int c = q.front().second; q.pop(); if (Map[r][c] != 0 && bs.Size > Map[r][c]) { v.push_back({ { r, c }, ret }); } for (int i = 0; i < 4; i++) { int y = r + dy[i]; int x = c + dx[i]; // 자신의 크기보다 더 큰 물고기가 있는 위치를 지나갈 수 없다. if (y < 0 || y >= N || x < 0 || x >= N || visit[y][x] || bs.Size < Map[y][x]) continue; q.push({ y, x }); visit[y][x] = true; } } ++ret; } if (v.empty()) return; if (v.size() > 1) sort(v.begin(), v.end(), cmp); bs.y = v.at(0).first.first; // 먹을 물고기 위치를 아기 상어의 위치로 bs.x = v.at(0).first.second; bs.time += v.at(0).second; // 출발 지점에서 먹을 물고기로 가는데 걸리는 시간 ++bs.eat; // 물고기를 먹고 Map[bs.y][bs.x] = 0; // 먹은 물고기 처리 if (bs.Size == bs.eat) // 근데 먹은 물고기 수가 아기 상어의 크기와 같다면 { ++bs.Size; // 사이즈 증가 bs.eat = 0; // 다시 먹은 물고기 수는 0으로 } } } int main(void) { scanf("%d", &N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { scanf("%d", &Map[i][j]); if (Map[i][j] == 9) { bs.eat = 0; bs.Size = 2; // 아기 상어 처음 크기 bs.y = i; bs.x = j; bs.time = 0; Map[i][j] = 0; } } } BFS(); printf("%d\n", bs.time); return 0; } | cs |
728x90
반응형