2
2
import java .io .IOException ;
3
3
import java .io .InputStreamReader ;
4
4
import java .io .PrintWriter ;
5
+ import java .util .ArrayList ;
5
6
import java .util .PriorityQueue ;
6
7
import java .util .StringTokenizer ;
7
8
import java .util .stream .IntStream ;
@@ -38,20 +39,17 @@ private void solveCase() throws IOException {
38
39
int n = Integer .parseInt (st .nextToken ());
39
40
int k = Integer .parseInt (in .readLine ());
40
41
int [][] grid = new int [m ][n ];
41
- int [][][] dists = new int [m ][n ][ k + 1 ];
42
+ ArrayList < State > [][] ss = new ArrayList [m ][n ];
42
43
for (int i = 0 ; i < m ; i ++) {
43
44
st = new StringTokenizer (in .readLine ());
44
45
for (int j = 0 ; j < n ; j ++) {
45
46
grid [i ][j ] = Integer .parseInt (st .nextToken ());
46
- for (int v = 0 ; v < k + 1 ; v ++) {
47
- dists [i ][j ][v ] = Integer .MAX_VALUE ;
48
- }
47
+ ss [i ][j ] = new ArrayList <>();
49
48
}
50
49
}
51
50
52
-
53
51
Pos p1 = new Pos (0 , 0 , 0 , k );
54
- dists [0 ][0 ][ k ] = k ;
52
+ ss [0 ][0 ]. add ( new State ( 0 , k )) ;
55
53
56
54
PriorityQueue <Pos > pq = new PriorityQueue <>();
57
55
pq .add (p1 );
@@ -66,21 +64,23 @@ private void solveCase() throws IOException {
66
64
int ndx = p .x + dx [d ];
67
65
int ndy = p .y + dy [d ];
68
66
if (ndx >= 0 && ndx < m && ndy >= 0 && ndy < n ) {
69
- if (dists [ndx ][ndy ].dist > p .dist + 1 || dists [ndx ][ndy ].k )
70
-
71
- if (grid [ndx ][ndy ] == 0 ) {
72
- if (dists [ndx ][ndy ].dist > p .dist + 1 || dists [ndx ][ndy ].k < k ) {
73
-
67
+ int newDist = p .dist + 1 ;
68
+ int newK = grid [ndx ][ndy ] == 1 ? p .k - 1 : k ;
69
+
70
+ if (newK >= 0 ) {
71
+ boolean shouldUpdate = true ;
72
+ for (State state : ss [ndx ][ndy ]) {
73
+ if (state .dist <= newDist && state .k >= newK ) {
74
+ shouldUpdate = false ;
75
+ break ;
74
76
}
77
+ }
75
78
76
- dists [ndx ][ndy ] = p .dist + 1 ;
77
- Pos np = new Pos (ndx , ndy , p .dist + 1 , k );
78
- pq .add (np );
79
- } else if (p .k > 0 ) {
80
- dists [ndx ][ndy ] = p .dist + 1 ;
81
- Pos np = new Pos (ndx , ndy , p .dist + 1 , p .k - 1 );
82
- pq .add (np );
79
+ if (shouldUpdate ) {
80
+ ss [ndx ][ndy ].add (new State (newDist , newK ));
81
+ pq .add (new Pos (ndx , ndy , newDist , newK ));
83
82
}
83
+ }
84
84
}
85
85
}
86
86
}
@@ -89,6 +89,7 @@ private void solveCase() throws IOException {
89
89
out .println (ans );
90
90
}
91
91
92
+
92
93
private void solve () throws IOException {
93
94
int c = Integer .parseInt (in .readLine ());
94
95
for (int i = 0 ; i < c ; i ++) {
0 commit comments