kama117.拓扑排序
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
int m=scan.nextInt();
//初始化
int[] degree = new int[n];
List<List<Integer>> edges= new ArrayList<>(); //记录点集,每个点指向哪些对应点
for (int i = 0; i < n; i++)
edges.add(new ArrayList<>());
for(int i=0;i<m;i++) {
int x = scan.nextInt();
int y = scan.nextInt();
edges.get(x).add(y);
degree[y]=degree[y]+1;
}
scan.close();
//初始化,放入度为0的节点
Queue<Integer> queue = new LinkedList<>();
List<Integer> res = new ArrayList<>();
for(int i=0;i<n;i++) {
if(degree[i]==0) queue.add(i);
}
//遍历queue
while(!queue.isEmpty()) {
//pop
int cur = queue.remove();
res.add(cur);
//减入度操作,遍历边集合
List<Integer> temp = edges.get(cur);
for(int i=0;i<temp.size();i++) {
degree[temp.get(i)]--;
if(degree[temp.get(i)]==0) {
queue.add(temp.get(i));
}
}
}
if(res.size()<n) {
System.out.println(-1);
}else {
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i));
if (i < res.size() - 1) {
System.out.print(" ");
}
}
}
}
kama47.dijkstra
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int[][] graph = new int[n+1][n+1];
int[] dp = new int[n+1];
boolean[] visited = new boolean[n+1];
for(int i=0;i<n+1;i++) {
Arrays.fill(graph[i], Integer.MAX_VALUE);
}
Arrays.fill(dp, Integer.MAX_VALUE);
for(int i=0;i<m;i++) {
int x = scan.nextInt();
int y = scan.nextInt();
int val = scan.nextInt();
graph[x][y]=val;
}
dp[1]=0;
for(int i=1;i<=n;i++) {
//选择出最短路径
int cur=1;
int min=Integer.MAX_VALUE;
for(int j=1;j<=n;j++) {
if(visited[j]==false&&dp[j]<min) {
min=dp[j];
cur=j;
}
}
//标记
visited[cur]=true;
//更新最短路径数组
for(int k=1;k<=n;k++) {
if(visited[k]==false&&graph[cur][k]!=Integer.MAX_VALUE&&dp[k]>dp[cur]+graph[cur][k]) {
dp[k]=dp[cur]+graph[cur][k];
}
}
}
if(dp[n]==Integer.MAX_VALUE) System.out.println(-1);
else System.out.println(dp[n]);
scan.close();
}