시간 제한 | 메모리 제한 |
---|---|
2초 | 512 MB |
N×N 크기의 공간에 물고기 M마리와 아기 상어 1마리가 있다. 공간은 1×1 크기의 정사각형 칸으로 나누어져 있다. 한 칸에는 물고기가 최대 1마리 존재한다.
아기 상어와 물고기는 모두 크기를 가지고 있고, 이 크기는 자연수이다. 가장 처음에 아기 상어의 크기는 2이고, 아기 상어는 1초에 상하좌우로 인접한 한 칸씩 이동한다.
아기 상어는 자신의 크기보다 큰 물고기가 있는 칸은 지나갈 수 없고, 나머지 칸은 모두 지나갈 수 있다. 아기 상어는 자신의 크기보다 작은 물고기만 먹을 수 있다. 따라서, 크기가 같은 물고기는 먹을 수 없지만, 그 물고기가 있는 칸은 지나갈 수 있다.
아기 상어가 어디로 이동할지 결정하는 방법은 아래와 같다.
거리는 아기 상어가 있는 칸에서 물고기가 있는 칸으로 이동할 때, 지나야하는 칸의 개수의 최솟값이다.
거리가 가까운 물고기가 많다면, 가장 위에 있는 물고기, 그러한 물고기가 여러마리라면, 가장 왼쪽에 있는 물고기를 먹는다.
아기 상어의 이동은 1초 걸리고, 물고기를 먹는데 걸리는 시간은 없다고 가정한다. 즉, 아기 상어가 먹을 수 있는 물고기가 있는 칸으로 이동했다면, 이동과 동시에 물고기를 먹는다. 물고기를 먹으면, 그 칸은 빈 칸이 된다.
아기 상어는 자신의 크기와 같은 수의 물고기를 먹을 때 마다 크기가 1 증가한다. 예를 들어, 크기가 2인 아기 상어는 물고기를 2마리 먹으면 크기가 3이 된다.
공간의 상태가 주어졌을 때, 아기 상어가 몇 초 동안 엄마 상어에게 도움을 요청하지 않고 물고기를 잡아먹을 수 있는지 구하는 프로그램을 작성하시오.
첫째 줄에 공간의 크기 N(2 ≤ N ≤ 20)이 주어진다.
둘째 줄부터 N개의 줄에 공간의 상태가 주어진다. 공간의 상태는 0, 1, 2, 3, 4, 5, 6, 9로 이루어져 있고, 아래와 같은 의미를 가진다.
아기 상어는 공간에 한 마리 있다.
첫째 줄에 아기 상어가 엄마 상어에게 도움을 요청하지 않고 물고기를 잡아먹을 수 있는 시간을 출력한다.
시간제한 : 2초 (1억 - 1초)
최대 20*20 사이즈의 공간 입력
상어의 최대 이동 횟수 400
이동할 때 마다 O(N^2)일 경우, 이동을 최대 N번
400 * 400 * 400 = 64_000_000
-> 6천4백만번으로 연산 가능
이동할 때 마다 O(N^3)일 경우, 이동을 최대 N번
400 * 400 * 400 * 400 = 25_600_000_000
-> 25억번으로 불가능
N^2 이내로 이동가능한 알고리즘 구현해야함
bfs를 이용한 너비 우선탐색으로 가까운 먹이를 찾는 코드를 구현.
다만, 같은 거리내에서는 y값이 작을수록, x값이 작을수록 우선순위가 높아진다.
첫번째 생각, 다음 노드를 저장하는 배열을 만들어 매번 우선순위에 맞게 정렬을 해준다.
정렬 : O(NlogN)
-> 전체 시간복잡도 O(N^3logN) 약 553_206_796 가능.
두번째 생각 다음 노드를 우선순위 큐를 이용하여 삽입 삭제를 logN에 연산.
-> 전체 시간복잡도 O(N^2logN) 약 1_383_016 가능.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
private static class Node implements Comparable<Node> {
public int distance;
public int x;
public int y;
public Node(int distance, int x, int y) {
this.distance = distance;
this.x = x;
this.y = y;
}
@Override
public int compareTo(Node o) {
if (o.distance != distance){
return distance - o.distance; //smaller
} else if (o.x != x) { //distance is same
return x - o.x; //bigger
}
else {// distance same, x same
return y - o.y; //bigger
}
}
}
우선순위 큐에 삽입할 Node class 구현,
Comparable 인터페이스 구현으로 우선순위 설정
private static int[] dy = {0, -1, 1, 0};
private static int[] dx = {-1, 0, 0, 1};
상하좌우 탐색을 위한 배열, 문제 우선순위에 맞춰 상, 좌, 우, 하 순서로 탐색해서 우선순위 큐 삽입 속도를 높혀줌.
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine()); // Max = 20
int[][] space;
int insideShark = 0;
int sharkSize = 2;
int distance = 0;
int sharkX=-1, sharkY=-1;
space : 물고기 위치 배열
insideShark : 상어가 먹은 물고기 수
sharkSize : 현재 상어 크기
distance : 총 이동거리, 총 소요시간
sharkX, sharkY : 현재 상어 위치
space = new int[N][N]; // Max 20*20 400
StringTokenizer st;
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
int n = Integer.parseInt(st.nextToken());
if (n==9) {
sharkX = i;
sharkY = j;
n=0;
}
space[i][j] = n;
}
}
입력 종료
PriorityQueue<Node> que = new PriorityQueue<>();
boolean ischanged = true;
while (ischanged){ // if changed nothing -> break
int[][] visited = new int[N][N];
que.add(new Node(1,sharkX,sharkY));
visited[sharkX][sharkY] = 1;
ischanged = false;
while (!que.isEmpty()){
Node cur = que.poll();
int curX = cur.x;
int curY = cur.y;
if (space[curX][curY] > 0 && space[curX][curY] < sharkSize){
distance += (visited[curX][curY] -1);
insideShark++;
if (sharkSize == insideShark){
sharkSize++;
insideShark = 0;
}
space[curX][curY] = 0; // fish is gone
sharkX = curX;
sharkY = curY;
ischanged = true; // shark position changed
que.clear();
break;
}
for (int i = 0; i < 4; i++) {
int nextX = curX + dx[i];
int nextY = curY + dy[i];
if (0 <= nextX && nextX < N && 0 <= nextY && nextY < N
&& visited[nextX][nextY] ==0 && space[nextX][nextY] <= sharkSize){
visited[nextX][nextY] = visited[curX][curY] + 1;
que.add(new Node(visited[nextX][nextY], nextX, nextY));
}
}
}
}
System.out.println(distance);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
private static class Node implements Comparable<Node> {
public int distance;
public int x;
public int y;
public Node(int distance, int x, int y) {
this.distance = distance;
this.x = x;
this.y = y;
}
@Override
public int compareTo(Node o) {
if (o.distance != distance){
return distance - o.distance; //smaller
} else if (o.x != x) { //distance is same
return x - o.x; //bigger
}
else {// distance same, x same
return y - o.y; //bigger
}
}
}
private static int[] dy = {0, -1, 1, 0};
private static int[] dx = {-1, 0, 0, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine()); // Max = 20
int[][] space;
int insideShark = 0;
int sharkSize = 2;
int distance = 0;
int sharkX=-1, sharkY=-1;
space = new int[N][N]; // Max 20*20 400
StringTokenizer st;
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
int n = Integer.parseInt(st.nextToken());
if (n==9) {
sharkX = i;
sharkY = j;
n=0;
}
space[i][j] = n;
}
}
PriorityQueue<Node> que = new PriorityQueue<>();
boolean ischanged = true;
while (ischanged){ // if changed nothing -> break
int[][] visited = new int[N][N];
que.add(new Node(1,sharkX,sharkY));
visited[sharkX][sharkY] = 1;
ischanged = false;
while (!que.isEmpty()){
Node cur = que.poll();
int curX = cur.x;
int curY = cur.y;
if (space[curX][curY] > 0 && space[curX][curY] < sharkSize){
distance += (visited[curX][curY] -1);
insideShark++;
if (sharkSize == insideShark){
sharkSize++;
insideShark = 0;
}
space[curX][curY] = 0; // fish is eaten
sharkX = curX;
sharkY = curY;
ischanged = true; // shark position changed
que.clear();
break;
}
for (int i = 0; i < 4; i++) {
int nextX = curX + dx[i];
int nextY = curY + dy[i];
if (0 <= nextX && nextX < N && 0 <= nextY && nextY < N
&& visited[nextX][nextY] ==0 && space[nextX][nextY] <= sharkSize){
visited[nextX][nextY] = visited[curX][curY] + 1;
que.add(new Node(visited[nextX][nextY], nextX, nextY));
}
}
}
}
System.out.println(distance);
}
}