用Java实现Input The first line contains the integer numbers N (2 ≤ N ≤ 500) and M (0 ≤ M ≤ 124750). Each of the next M lines contains the integer numbers A[i], B[i] (1 ≤ A[i], B[i] ≤ N) and C[i] (1 ≤ C[i] ≤ 10000) for the corresponding pipeline. The last line contains the integer numbers S and F (1 ≤ S, F ≤ N; S ≠ F). Output If the desired route exists, you should output its profitability. Otherwise you should output "No solution".
时间: 2024-03-03 15:47:47 浏览: 132
以下是Java代码实现:
```java
import java.util.*;
public class Pipeline {
static int N, M;
static int[] dist;
static boolean[] visited;
static List<Edge>[] graph;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
dist = new int[N + 1];
visited = new boolean[N + 1];
graph = new List[N + 1];
for (int i = 1; i <= N; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < M; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
graph[a].add(new Edge(b, c));
graph[b].add(new Edge(a, c));
}
int start = sc.nextInt();
int end = sc.nextInt();
int res = dijkstra(start, end);
if (res == Integer.MAX_VALUE) {
System.out.println("No solution");
} else {
System.out.println(res);
}
}
private static int dijkstra(int start, int end) {
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.offer(new Node(start, 0));
while (!pq.isEmpty()) {
Node curr = pq.poll();
int u = curr.vertex;
if (visited[u]) {
continue;
}
visited[u] = true;
if (u == end) {
return dist[end];
}
for (Edge edge : graph[u]) {
int v = edge.to;
int w = edge.weight;
if (!visited[v] && dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.offer(new Node(v, dist[v]));
}
}
}
return Integer.MAX_VALUE;
}
}
class Node implements Comparable<Node> {
int vertex;
int dist;
public Node(int vertex, int dist) {
this.vertex = vertex;
this.dist = dist;
}
@Override
public int compareTo(Node o) {
return this.dist - o.dist;
}
}
class Edge {
int to;
int weight;
public Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
```
该程序输入包括两个整数N和M,表示有N个节点和M条边。接下来的M行包含A[i]、B[i]和C[i],表示第i条边连接节点A[i]和B[i],边的权重为C[i]。最后一行包含S和F,表示起点和终点。
程序使用了Dijkstra算法求解最短路径问题,采用了优先队列来实现。首先建立一个邻接表来存储图中每个节点的出边,然后初始化起点到所有节点的距离为无穷大,起点的距离为0。将起点加入优先队列中,每次从队列中取出距离起点最近的节点u,对u的所有出边进行松弛操作,即更新到与u相邻的节点v的距离,如果发现更优的路径则更新距离并将v加入优先队列中。重复上述操作直到队列为空或终点被访问到。如果终点被访问到了,则返回起点到终点的最短距离,否则返回无穷大表示不存在路径。最后根据返回值输出结果。
阅读全文