DAY60-图论-Bellman_ford

Bellman_ford 队列优化算法(又名SPFA)

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int m = scan.nextInt();
		
		//初始化
		List> edges = new ArrayList<>();
		for(int i=0;i<=n;i++) {
			List temp = new ArrayList<>();
			edges.add(temp);
		}
		int[][] graph = new int[n+1][n+1];
		for(int i=0;i<=n;i++) {
			Arrays.fill(graph[i], Integer.MAX_VALUE);
		}
		int[] minDp = new int[n+1];
		Arrays.fill(minDp, Integer.MAX_VALUE);
		boolean[] visited = new boolean[n+1]; //标记是否放入队列中
		
		//接收数据
		for(int i=0;i queue = new LinkedList<>();
		queue.add(1);
		minDp[1]=0;
		while(!queue.isEmpty()) {
			int cur = queue.remove();
			visited[cur]=false;
			List temp = edges.get(cur);
			for(int i=0;iminDp[edge[0]]+edge[2]) {
					minDp[edge[1]]=minDp[edge[0]]+edge[2];
					if(visited[edge[1]]==false) {
						queue.add(edge[1]);
						visited[edge[1]]=true;
					}
					
				}
			}
		}

		//输出
		if(minDp[n]==Integer.MAX_VALUE) System.out.println("unconnected");
		else System.out.println(minDp[n]);
		
		scan.close();
	}

Bellman_ford之判断负权回路

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int m = scan.nextInt();
		
		//初始化
		int[][] edges = new int[m][3];
		int[][] graph = new int[n+1][n+1];
		for(int i=0;i<=n;i++) {
			Arrays.fill(graph[i], Integer.MAX_VALUE);
		}
		int[] minDp = new int[n+1];
		Arrays.fill(minDp, Integer.MAX_VALUE);
		
		//接收数据
		for(int i=0;iminDp[edge[0]]+edge[2]) {
					minDp[edge[1]]=minDp[edge[0]]+edge[2];
					if(i==n)flag=true;
				}
			}
		}
		
		//输出
		if(flag==false) {
			if(minDp[n]==Integer.MAX_VALUE) System.out.println("unconnected");
			else System.out.println(minDp[n]);
		}else {
			System.out.println("circle");
		}

		
		scan.close();
	}

Bellman_ford之单源有限最短路

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int m = scan.nextInt();
		
		//初始化
		int[][] edges = new int[m][3];
		int[][] graph = new int[n+1][n+1];
		for(int i=0;i<=n;i++) {
			Arrays.fill(graph[i], Integer.MAX_VALUE);
		}
		int[] minDp = new int[n+1];
		Arrays.fill(minDp, Integer.MAX_VALUE);
		
		//接收数据
		for(int i=0;iminCopy[edge[0]]+edge[2]) {
					minDp[edge[1]]=minCopy[edge[0]]+edge[2];
				}
			}
		}
		
		//输出
		if(minDp[end]==Integer.MAX_VALUE) System.out.println("unreachable");
		else System.out.println(minDp[end]);
		
		scan.close();
	}

你可能感兴趣的:(LeetCode刷题手册,图论)