1268: 单源最短路径问题
时间限制: 1 Sec 内存限制: 128 MB
提交: 86 解决: 45
[提交] [状态] [讨论版] [命题人:外部导入]
题目描述
给你一个n(1<=n<=2500)个点m(1<=m<=6200)条边的无向图,求s到t的最短路
输入
第一行四个由空格隔开的整数n,m,s,t
之后的m行,每行三个正整数u,v,w(1<=w<=1e9),表示一条从u到v长度为w的边
输出
一个整数表示从s到t的最短路长度。数据保证至少存在一条道路
样例输入 Copy
7 11 5 4 2 4 2 1 4 3 7 2 2 3 4 3 5 7 5 7 3 3 6 1 1 6 3 4 2 4 3 5 6 3 7 2 1
样例输出 Copy
7
来源/分类
import java.util.*;
//1268
class Edge {
int to;
int weight;
public Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // 点的数量
int m = scanner.nextInt(); // 边的数量
int s = scanner.nextInt(); // 起点
int t = scanner.nextInt(); // 终点
List<List<Edge>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
// 构建图的邻接表表示
for (int i = 0; i < m; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
int w = scanner.nextInt();
graph.get(u - 1).add(new Edge(v - 1, w));
graph.get(v - 1).add(new Edge(u - 1, w));
}
int[] distance = new int[n]; // 起点到各点的最短距离数组
Arrays.fill(distance, Integer.MAX_VALUE);
distance[s - 1] = 0;
// 使用Dijkstra算法求解最短路径
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> distance[a] - distance[b]);
pq.offer(s - 1);
while (!pq.isEmpty()) {
int u = pq.poll();
for (Edge edge : graph.get(u)) {
int v = edge.to;
int w = edge.weight;
if (distance[u] + w < distance[v]) {
distance[v] = distance[u] + w;
pq.offer(v);
}
}
}
System.out.println(distance[t - 1]);
}
}