import java.util.*; class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } } class Node extends Point { int dist; Node(int dist, int x, int y) { super(x, y); this.dist = dist; } } public class _16236 { static boolean inField(int x, int y, int N) { return (0<=x && x pq = new PriorityQueue<>((a, b) -> { if(a.dist == b.dist) { if(a.y == b.y) return a.x - b.x; return a.y - b.y; } return a.dist - b.dist; }); int[] dx = {0,-1,1,0}; int[] dy = {-1,0,0,1}; while(true) { boolean[][] visited = new boolean[N][N]; boolean eatFish = false; pq.clear(); visited[shark.y][shark.x] = true; pq.add(new Node(0, shark.x, shark.y)); while(!pq.isEmpty()) { Node now = pq.poll(); if(field[now.y][now.x] != 0 && field[now.y][now.x] < sharkSize) { field[now.y][now.x] = 0; shark.x = now.x; shark.y = now.y; eatCount++; moveTime += now.dist; eatFish = true; if(sharkSize == eatCount) { eatCount = 0; sharkSize++; } break; } for(int i=0; i<4; i++) { int nx = now.x + dx[i]; int ny = now.y + dy[i]; if(inField(nx, ny, N) && !visited[ny][nx] && field[ny][nx] <= sharkSize) { pq.add(new Node(now.dist + 1, nx, ny)); visited[ny][nx] = true; } } } if(!eatFish) break; } System.out.println(moveTime); } }