问题描述
资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。
输入格式
第一行两个整数n, m。
接下来的m行,每行有三个整数u, v, l,表示u到v有一条长度为l的边。
输出格式
共n-1行,第i行表示1号点到i+1号点的最短路。
样例输入
3 3
1 2 -1
2 3 -1
3 1 2
样例输出
-1
-2
数据规模与约定
对于10%的数据,n = 2,m = 2。
对于30%的数据,n <= 5,m <= 10。
对于100%的数据,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保证从任意顶点都能到达其他所有顶点。
解题思路
1.首先要建立起各个顶点的线路连通图
2.运用地杰斯塔拉算法寻找最短路径
3.输出dist里面所有除0顶点外的值
地杰斯特拉算法请参考:https://haokan.baidu.com/v?vid=12876411808292764250&pd=bjh&fr=bjhauthor&type=video
参考代码
package 最短路;
import java.util.Scanner;
public class Main {
static int[][] map;
public static void main(String[] args) {
Scanner sr = new Scanner(System.in);
//建立规划地图
int n = sr.nextInt();
map = new int[n][n];
int m = sr.nextInt();
for (int i = 0; i < m; i++) {
int u, v, l;
u = sr.nextInt()-1;
v = sr.nextInt()-1;
l = sr.nextInt();
//从u-v的距离是l
map[u][v] = l;
}
sr.close();
//确定最短路径的顶点的状态数组
boolean check[] = new boolean[n];
int[] dist = new int[n];
//确定0与周边顶点的状态
for (int i = 0; i < map.length; i++){
if (map[0][i] != 0) {
dist[i] = map[0][i];
}else {
dist[i] = Integer.MAX_VALUE;
}
}
while (!check[n-1]) {
int min = Integer.MAX_VALUE;
int index = 0;
//从没有确定最小值的顶点选择一个最小距离
for (int i = 0; i < n; i++) {
//!check用来确定顶点没有被确定哪个顶点到他最近
if (!check[i] && dist[i] < min) {
min = dist[i];
index = i;
}
}
//标记:已获得到达此点最短距离
check[index] = true;
//从这个点出发,更新周边顶点的距离,原距离小?还是通过此点的距离小?
for (int i = 0; i < n; i++) {
if (map[index][i] != 0) {//确保是通路状态。
//0-当前最短距离+当前顶点到附近顶点距离<0-附近顶点距离
int length = dist[index]+map[index][i];
if ( length < dist[i]) {
dist[i] = length;
}
}
}
}
//dist集合存储的是从0点到以下所有点的最短路径
for (int i = 1; i < dist.length; i++) {
System.out.println(dist[i]);
}
}
}