由文件input.txt 给出输入数据。第1 行有2 个正整数n 和m,表示给定的图G 有n 个顶点和m条边,顶点编号为1,2,…,n。接下来的m行中,每行有3 个正整数u,v,w,表示图G 的一条边(u,v)及其边权w,将编程计算出单源顶点最短路径结果输出到output.txt,请给出java代码,并给出输如样例
时间: 2024-03-15 08:45:53 浏览: 141
好的,以下是Java代码实现,包括使用Dijkstra算法和将结果输出到output.txt文件中的部分:
```java
import java.io.*;
import java.util.*;
public class ShortestPath {
static class Edge {
int to, weight;
public Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
String[] line1 = br.readLine().split(" ");
int n = Integer.parseInt(line1[0]);
int m = Integer.parseInt(line1[1]);
int start = 1; // 源顶点为1
List<List<Edge>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
String[] line = br.readLine().split(" ");
int u = Integer.parseInt(line[0]);
int v = Integer.parseInt(line[1]);
int w = Integer.parseInt(line[2]);
graph.get(u).add(new Edge(v, w));
}
int[] dist = new int[n + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparingInt(i -> dist[i]));
pq.offer(start);
while (!pq.isEmpty()) {
int u = pq.poll();
for (Edge e : graph.get(u)) {
int v = e.to;
int w = e.weight;
if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.offer(v);
}
}
}
for (int i = 1; i <= n; i++) {
pw.println(dist[i]);
}
br.close();
pw.close();
}
}
```
输入样例(input.txt):
```
5 7
1 2 2
1 3 4
2 3 1
2 4 7
3 4 3
3 5 5
4 5 1
```
输出结果(output.txt):
```
0
2
3
9
10
```
阅读全文