算法提高 多源最短路

资源限制
时间限制:3.0s 内存限制:256.0MB
问题描述
  给定n个结点两两之间的单向边的长度,求两两之间的最短路径。
输入格式
  输入第一行包含一个整数n,表示点数。
  接下来n行,每行包含n个整数,第i行表示第i个点到每个点的边的长度,如果没有边,则用0表示。
输出格式
  输出n行,第i行表示第i个点到其他点的最短路径长度,如果没有可达的路径,则输出-1。
样例输入
3

0 1 0
0 0 6
0 2 0
样例输出
0 1 7
-1 0 6
-1 2 0
数据规模和约定
  1<=n<=1000,0<边长<=10000。

import java.util.*;

public class Main {
    
    
	static int[][]graph;
	static final int INF=0x3f3f3f3f;
	public static void floyd(int n) {
    
    
		for(int k=1;k<=n;k++) {
    
    
			for(int i=1;i<=n;i++) {
    
    
				for(int j=1;j<=n;j++) {
    
    
					if(i!=j&&graph[i][j]>graph[i][k]+graph[k][j])
						graph[i][j]=graph[i][k]+graph[k][j];
				}
			}
		}
	}
    public static void main(String[]args) {
    
    
    	Scanner sc=new Scanner(System.in);
    	int n=sc.nextInt();	
    	graph=new int[n+1][n+1];
    	for(int i=1;i<=n;i++) {
    
    
    		for(int j=1;j<=n;j++) {
    
    
    			int x=sc.nextInt();
    			if(x!=0)
    			graph[i][j]=x;
    			else graph[i][j]=INF;
    		}
    	}
    	floyd(n);
    	for(int i=1;i<=n;i++) {
    
    
    		for(int j=1;j<=n;j++) {
    
    
    			if(i!=j&&graph[i][j]!=INF)
    			System.out.print(graph[i][j]+" ");
    			else if(i!=j&&graph[i][j]==INF)
    				System.out.print(-1+" ");
    			else System.out.print(0+" ");
    		}
    		System.out.println();
    	}
    }
}

在这里插入图片描述

参考别人的代码应该是读入是没有用IO读写导致内存超时

import java.io.*;
 
public class Main {
    
    
	public static void main(String[] args) throws NumberFormatException, IOException {
    
    
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		int INF = 65535;
		int [][]dis = new int[n][n];
		for(int i = 0; i < n;i++) {
    
    
			String[] split = br.readLine().split(" ");
			for(int j = 0; j < n;j++) {
    
    
				if(Integer.parseInt(split[j]) == 0) {
    
    
					dis[i][j] = INF;
				}else {
    
    
					dis[i][j] = Integer.parseInt(split[j]);
				}
			}
		}
		Graph1057 graph = new Graph1057(dis);
		graph.floyd();
		graph.print();
	}
	
}
class Graph1057{
    
    
	int n;
	int [][]dis;
	int INF = 65535;
 
	public Graph1057(int[][] dis) {
    
    
		this.dis = dis;
		n = dis.length;
	}
	
	public void floyd() {
    
    
		for(int k = 0; k < n;k++) {
    
    
			for(int i = 0; i < n;i++) {
    
    
				for(int j = 0; j < n;j++) {
    
    
					int len = dis[i][k] + dis[k][j];
					if(len < dis[i][j]) {
    
    
						dis[i][j] = len;
					}
				}
			}
		}
	}
	
	public void print() {
    
    
		for(int i = 0; i < n;i++) {
    
    
			for(int j = 0; j < n;j++) {
    
    
				if(i == j) {
    
    
					System.out.print("0 ");
				}else if(dis[i][j] == INF){
    
    
					System.out.print("-1 ");
				}else {
    
    
					System.out.print(dis[i][j] + " ");
				}
			}
			System.out.println();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_54537215/article/details/123869588