写一段Java实现Input The first line contains the number n of fighters in the division (2 ≤ n ≤ 50000). The second line contains ten integers in the range from 1 to 10000 separated with a space written in the nonascending order. These are the times of sending a message from one telegraph to another if the length of their common prefix is zero, one, two, …, nine. The next n lines contain the numbers of telegraphs given to the fighters of the division. The number of Anka's telegraph is described first, and the number of Chapaev's telegraph is described last. All the numbers of telegraphs are different. Output Output the only line “-1” if it is impossible to deliver the message to Chapaev. Otherwise, in the first line output the minimal time required to deliver the message. In the second line output the number of fighters in the delivery path, and in the third line output their numbers separated with a space in the order from Anka to Chapaev. The fighters of the 25th Division are numbered from 1 to n in the order in which their mobile telegraphs are described in the input. If there are several ways to deliver the message in minimal time, output any of them.
时间: 2024-02-19 10:01:24 浏览: 95
以下是Java实现,可以满足你的要求:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] t = new int[10];
for (int i = 0; i < 10; i++) {
t[i] = sc.nextInt();
}
int[] telegraphs = new int[n];
for (int i = 0; i < n; i++) {
telegraphs[i] = sc.nextInt();
}
int anka = sc.nextInt();
int chapaev = sc.nextInt();
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
boolean[] visited = new boolean[n];
dist[anka - 1] = 0;
int[] prev = new int[n];
Arrays.fill(prev, -1);
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> dist[a - 1] - dist[b - 1]);
pq.offer(anka);
while (!pq.isEmpty()) {
int u = pq.poll();
if (visited[u - 1]) {
continue;
}
visited[u - 1] = true;
for (int i = 0; i < n; i++) {
if (telegraphs[i] == u) {
for (int j = 0; j < 10; j++) {
int v = i + j + 1;
if (v > n || visited[v - 1]) {
continue;
}
int w = dist[u - 1] + t[j];
if (w < dist[v - 1]) {
dist[v - 1] = w;
prev[v - 1] = u;
pq.offer(v);
}
}
}
}
}
if (dist[chapaev - 1] == Integer.MAX_VALUE) {
System.out.println("-1");
} else {
System.out.println(dist[chapaev - 1]);
List<Integer> path = new ArrayList<>();
int cur = chapaev;
while (cur != -1) {
path.add(cur);
cur = prev[cur - 1];
}
Collections.reverse(path);
System.out.println(path.size());
for (int i : path) {
System.out.print(i + " ");
}
}
}
}
阅读全文