拓扑排序精讲
拓扑排序看上去很复杂,其实了解其原理之后,代码不难
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
List<List<Integer>> umap = new ArrayList<>();
int[] inDegree = new int[n];
for (int i = 0; i < n; i++)
umap.add(new ArrayList<>());
for (int i = 0; i < m; i++) {
int s = scanner.nextInt();
int t = scanner.nextInt();
umap.get(s).add(t);
inDegree[t]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (inDegree[i] == 0) {
queue.add(i);
}
}
List<Integer> result = new ArrayList<>();
while (!queue.isEmpty()) {
int cur = queue.poll();
result.add(cur);
for (int file : umap.get(cur)) {
inDegree[file]--;
if (inDegree[file] == 0) {
queue.add(file);
}
}
}
if (result.size() == n) {
for (int i = 0; i < result.size(); i++) {
System.out.print(result.get(i));
if (i < result.size() - 1) {
System.out.print(" ");
}
}
} else {
System.out.println(-1);
}
}
}
dijkstra(朴素版)精讲
后面几天都是最短路系列了,对于最短路系列,我的建议是,如果第一次接触最短路算法的话,能看懂原理,能照着代码随想录把代码抄下来就可以了,二刷的时候 再尝试自己去写出来。 三刷的时候,差不多才能把最短路吃透。
对于一刷的录友们,不要强行去逼迫自己去学透,很难刚接触到最短路算法就学透。
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] grid = new int[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
Arrays.fill(grid[i], Integer.MAX_VALUE);
}
for (int i = 0; i < m; i++) {
int p1 = scanner.nextInt();
int p2 = scanner.nextInt();
int val = scanner.nextInt();
grid[p1][p2] = val;
}
int start = 1;
int end = n;
int[] minDist = new int[n + 1];
Arrays.fill(minDist, Integer.MAX_VALUE);
boolean[] visited = new boolean[n + 1];
minDist[start] = 0;
for (int i = 1; i <= n; i++) {
int minVal = Integer.MAX_VALUE;
int cur = 1;
for (int v = 1; v <= n; ++v) {
if (!visited[v] && minDist[v] < minVal) {
minVal = minDist[v];
cur = v;
}
}
visited[cur] = true;
for (int v = 1; v <= n; v++) {
if (!visited[v] && grid[cur][v] != Integer.MAX_VALUE && minDist[cur] + grid[cur][v] < minDist[v]) {
minDist[v] = minDist[cur] + grid[cur][v];
}
}
}
if (minDist[end] == Integer.MAX_VALUE) {
System.out.println(-1);
} else {
System.out.println(minDist[end]);
}
}
}