|
| 1 | +``` |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | +
|
| 5 | +public class Main { |
| 6 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + private static final long INF = Long.MAX_VALUE/2; |
| 9 | + private static List<Integer>[] graph; |
| 10 | + private static long[] dist; |
| 11 | + private static int[] a, b; |
| 12 | + private static int N; |
| 13 | + public static void main(String[] args) throws IOException { |
| 14 | + init(); |
| 15 | + dijkstra(); |
| 16 | + for (int i = 1; i <= N; i++) { |
| 17 | + bw.write(dist[i] + " "); |
| 18 | + } |
| 19 | +
|
| 20 | + bw.flush(); |
| 21 | + bw.close(); |
| 22 | + br.close(); |
| 23 | + } |
| 24 | +
|
| 25 | + private static void init() throws IOException { |
| 26 | + N = Integer.parseInt(br.readLine()); |
| 27 | +
|
| 28 | + a = new int[N+1]; |
| 29 | + b = new int[N+1]; |
| 30 | + dist = new long[N+1]; |
| 31 | + graph = new List[N+1]; |
| 32 | +
|
| 33 | + for (int i = 1; i <= N; i++) { |
| 34 | + graph[i] = new ArrayList<>(); |
| 35 | + } |
| 36 | +
|
| 37 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 38 | + for (int i = 1; i <= N; i++) { |
| 39 | + a[i] = Integer.parseInt(st.nextToken()); |
| 40 | + if (1 <= i-a[i] && i-a[i] <= N) { |
| 41 | + graph[i-a[i]].add(i); |
| 42 | + } |
| 43 | +
|
| 44 | + if (1 <= i+a[i] && i+a[i] <= N) { |
| 45 | + graph[i+a[i]].add(i); |
| 46 | + } |
| 47 | + } |
| 48 | +
|
| 49 | + st = new StringTokenizer(br.readLine()); |
| 50 | + for (int i = 1; i <= N; i++) { |
| 51 | + b[i] = Integer.parseInt(st.nextToken()); |
| 52 | + } |
| 53 | + } |
| 54 | +
|
| 55 | + private static void dijkstra() { |
| 56 | + PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> Long.compare(o1.cost, o2.cost)); |
| 57 | + Arrays.fill(dist, INF); |
| 58 | + for (int i = 1; i <= N; i++) { |
| 59 | + if (i-a[i] < 1 || i+a[i] > N) { |
| 60 | + dist[i] = b[i]; |
| 61 | + pq.add(new Node(i, b[i])); |
| 62 | + } |
| 63 | + } |
| 64 | +
|
| 65 | + while (!pq.isEmpty()) { |
| 66 | + Node current = pq.poll(); |
| 67 | +
|
| 68 | + if (current.cost > dist[current.dest]) continue; |
| 69 | +
|
| 70 | + for (int nDest : graph[current.dest]) { |
| 71 | + long nCost = current.cost + b[nDest]; |
| 72 | +
|
| 73 | + if (nCost < dist[nDest]) { |
| 74 | + dist[nDest] = nCost; |
| 75 | + pq.add(new Node(nDest, dist[nDest])); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | +
|
| 81 | + static class Node { |
| 82 | + int dest; |
| 83 | + long cost; |
| 84 | +
|
| 85 | + public Node(int dest, long cost) { |
| 86 | + this.dest = dest; |
| 87 | + this.cost = cost; |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | +``` |
0 commit comments