반응형
https://www.acmicpc.net/problem/16236
16236번: 아기 상어
N×N 크기의 공간에 물고기 M마리와 아기 상어 1마리가 있다. 공간은 1×1 크기의 정사각형 칸으로 나누어져 있다. 한 칸에는 물고기가 최대 1마리 존재한다. 아기 상어와 물고기는 모두 크기를 가
www.acmicpc.net
#include <bits/stdc++.h>
using namespace std;
int n, arr[21][21];
struct Shark {
int x, y, size=2, cnt =0;
void sizeUp() {
if (cnt >= size) {
cnt -= size;
size++;
}
}
};
struct Node {
int x, y , dist;
bool operator<(const Node& b) const {
if (dist == b.dist) {
if (x == b.x) {
return y > b.y;
}
return x > b.x;
}
else return dist > b.dist;
}
};
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
bool ch[21][21];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
Shark sk;
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> arr[i][j];
if (arr[i][j] == 9) {
arr[i][j] = 0;
sk.x = i;
sk.y = j;
}
}
}
priority_queue<Node> Q;
Q.push({ sk.x, sk.y, 0 });
ch[sk.x][sk.y] = 1;
int ans = 0;
while (!Q.empty()) {
int x = Q.top().x;
int y = Q.top().y;
int d = Q.top().dist;
Q.pop();
if (arr[x][y]!=0 && arr[x][y] < sk.size) {
arr[x][y] = 0;
sk.cnt++;
sk.sizeUp();
memset(ch, 0, sizeof(ch));
ans += d;
while (!Q.empty()) {
Q.pop();
}
Q.push({ x,y,0 });
ch[x][y] = 1;
continue;
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= n || ny < 0 || ny >= n || ch[nx][ny]) continue;
if (arr[nx][ny] <= sk.size) {
ch[nx][ny] = 1;
Q.push({ nx,ny,d + 1 });
}
}
}
cout << ans << '\n';
return 0;
}

반응형
'Algorithm > problem' 카테고리의 다른 글
백준 16139번 : 인간 - 컴퓨터 상호작용 - 구간 합 C++ (0) | 2022.03.10 |
---|---|
백준 10986 : 나머지 합 - prefix sum C++ (0) | 2022.03.09 |
백준 11660번 : 구간 합 구하기 5 - 누적합 C++ (0) | 2022.03.09 |
백준 1493번 : 박스 채우기 - 그리디 , 분할정복 C++ (0) | 2022.03.08 |
백준 13904번 : 과제 - 그리디 C++ (0) | 2022.03.07 |