文章目录
- [dijkstra(堆优化版)精讲 47. 参加科学大会(第六期模拟笔试)](#dijkstra(堆优化版)精讲 47. 参加科学大会(第六期模拟笔试))
- [Bellman_ford 算法精讲 94. 城市间货物运输 I](#Bellman_ford 算法精讲 94. 城市间货物运输 I)
dijkstra(堆优化版)精讲 47. 参加科学大会(第六期模拟笔试)
加入小顶堆,每次从优先队列获取到最小值,不需要遍历整个数组。
java
import java.util.*;
class Edge {
int to;
int val;
Edge(int to, int val) {
this.to = to;
this.val = val;
}
}
class Pair {
public int first;
public int second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
class MyComparision implements Comparator<Pair> {
@Override
public int compare(Pair r, Pair l) {
return Integer.compare(r.second, l.second);
}
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] minDist = new int[n + 1];
List<List<Edge>> grid = new ArrayList<>(n + 1);
Arrays.fill(minDist, Integer.MAX_VALUE);
for (int i =0; i <= n; i++) {
grid.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int s = sc.nextInt();
int t = sc.nextInt();
int val = sc.nextInt();
grid.get(s).add(new Edge(t, val));
}
boolean[] visited = new boolean[n + 1];
PriorityQueue<Pair> pq = new PriorityQueue<>(new MyComparision());
pq.add(new Pair(1, 0));
minDist[1] = 0;
while (!pq.isEmpty()) {
Pair cur = pq.poll();
visited[cur.first] = true;
for (Edge edge : grid.get(cur.first)) {
if (!visited[edge.to] && minDist[edge.to] > minDist[cur.first] + edge.val) {
minDist[edge.to] = minDist[cur.first] + edge.val;
pq.add(new Pair(edge.to, minDist[edge.to]));
}
}
}
if (minDist[n] == Integer.MAX_VALUE) {
System.out.println(-1);
}
else {
System.out.println(minDist[n]);
}
}
}
Bellman_ford 算法精讲 94. 城市间货物运输 I
总共最多需要松弛边n - 1次,得到每一个点到原点的最短距离。
java
import java.util.*;
class Edge {
int from;
int to;
int val;
Edge(int from, int to, int val) {
this.from = from;
this.to = to;
this.val = val;
}
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
List<Edge> edges = new ArrayList<>();
for (int i = 0; i < m; i++) {
int s = sc.nextInt();
int t = sc.nextInt();
int v = sc.nextInt();
edges.add(new Edge(s, t, v));
}
int[] minDist = new int[n + 1];
Arrays.fill(minDist, Integer.MAX_VALUE);
minDist[1] = 0;
for (int i = 1; i < n; i++) {
for (Edge edge : edges) {
if (minDist[edge.from] != Integer.MAX_VALUE && minDist[edge.from] + edge.val < minDist[edge.to]) {
minDist[edge.to] = minDist[edge.from] + edge.val;
}
}
}
if (minDist[n] == Integer.MAX_VALUE) {
System.out.println("unconnected");
}
else {
System.out.println(minDist[n]);
}
}
}