|
| 1 | +```java |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.io.*; |
| 5 | + |
| 6 | +class Main { |
| 7 | + |
| 8 | + // IO field |
| 9 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 10 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 11 | + static StringTokenizer st; |
| 12 | + |
| 13 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 14 | + static int nextInt() {return Integer.parseInt(st.nextToken());} |
| 15 | + static long nextLong() {return Long.parseLong(st.nextToken());} |
| 16 | + static void bwEnd() throws Exception {bw.flush();bw.close();} |
| 17 | + |
| 18 | + // Additional field |
| 19 | + |
| 20 | + |
| 21 | + public static void main(String[] args) throws Exception { |
| 22 | + |
| 23 | + int[] dx = {1,0,-1,0}; |
| 24 | + int[] dy = {0,1,0,-1}; |
| 25 | + |
| 26 | + nextLine(); |
| 27 | + int N = nextInt(), M = nextInt(), T = nextInt(), D = nextInt(); |
| 28 | + int[][] A = new int[N][M]; |
| 29 | + for(int i=0;i<N;i++) { |
| 30 | + String line = br.readLine(); |
| 31 | + for(int j=0;j<M;j++) { |
| 32 | + char a = line.charAt(j); |
| 33 | + if(a <= 'Z') A[i][j] = a-'A'; |
| 34 | + else A[i][j] = a-'a'+26; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + int INF = 1234567890; |
| 39 | + int[][][] dist = new int[N][M][52]; |
| 40 | + for(int i=0;i<N;i++) for(int j=0;j<M;j++) Arrays.fill(dist[i][j], INF); |
| 41 | + PriorityQueue<int[]> PQ = new PriorityQueue<>((a,b) -> a[0]-b[0]); |
| 42 | + dist[0][0][A[0][0]] = 0; |
| 43 | + PQ.offer(new int[] {0,0,0,A[0][0]}); |
| 44 | + while(!PQ.isEmpty()) { |
| 45 | + int[] now = PQ.poll(); |
| 46 | + int t = now[0], x = now[1], y = now[2], a = now[3]; |
| 47 | + if(t > dist[x][y][a]) continue; |
| 48 | + for(int i=0;i<4;i++) { |
| 49 | + int xx = x+dx[i], yy = y+dy[i]; |
| 50 | + if(xx<0 || xx>=N || yy<0 || yy>=M) continue; |
| 51 | + if(Math.abs(A[x][y] - A[xx][yy]) > T) continue; |
| 52 | + int aa = Math.max(a, A[xx][yy]); |
| 53 | + int v = Math.max(1, A[xx][yy] - A[x][y]); |
| 54 | + if(dist[xx][yy][aa] > t + v*v) { |
| 55 | + dist[xx][yy][aa] = t+v*v; |
| 56 | + PQ.offer(new int[] {t+v*v,xx,yy,aa}); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + for(int i=51;i>=0;i--) { |
| 61 | + if(dist[0][0][i] <= D) { |
| 62 | + bw.write(i+"\n"); |
| 63 | + bwEnd(); |
| 64 | + return; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + bwEnd(); |
| 69 | + } |
| 70 | + |
| 71 | +} |
| 72 | + |
| 73 | +``` |
0 commit comments