题目1008:最短路径问题
参考代码:空间复杂度和时间复杂度都十分惊人
import java.awt.print.Printable;
import java.util.*;
public class Main {
public static void main(String[] args) {
final Integer NaN = Integer.MAX_VALUE;
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
// 获取节点数和路径数
Integer NodeNum = sc.nextInt();
Integer NodeSting = sc.nextInt();
if(NodeNum==0 && NodeSting==0) break;
Integer[][] distance = new Integer[NodeNum][NodeNum];
Integer[][] cost = new Integer[NodeNum][NodeNum];
//设置S,T数组
ArrayList<Integer> S = new ArrayList<Integer>();
ArrayList<Integer> T = new ArrayList<Integer>();
//初始化邻接矩阵
for(int i=0;i<NodeNum;i++){
for(int j=0;j<NodeNum;j++){
distance[i][j] =NaN;
cost[i][j] =NaN;
}
T.add(i+1);
}
//改变邻接矩阵,重线时以相对小的取代
for(int i=0;i<NodeSting;i++){
int x=sc.nextInt();
int y=sc.nextInt();
int distance_temp = sc.nextInt();
int cost_temp = sc.nextInt();
if(distance[x-1][y-1]>distance_temp)
{
distance[x-1][y-1] = distance_temp;
distance[y-1][x-1] = distance_temp;
cost[x-1][y-1] = cost_temp;
cost[y-1][x-1] = cost_temp;
}
if(distance[x-1][y-1] == distance_temp)
{
if(cost[x-1][y-1] > cost_temp){
cost[x-1][y-1] = cost_temp;
cost[y-1][x-1] = cost_temp;
}
}
}
//设置原点、终点
Integer source = sc.nextInt();
Integer terminal = sc.nextInt();
Integer totaldistance = 0;
Integer totalcost = 0;
//初始化权值 和 代价值
Integer[] q = new Integer[NodeNum];
Arrays.fill(q, NaN);
Integer[] cost1 = new Integer[NodeNum];
Arrays.fill(cost1, NaN);
//路劲待查
ArrayList<Integer> route = new ArrayList<Integer>();
while(true){
//原点放入S数组,从T数组删除,初始化最小值和最短路劲点
S.add(source);
T.remove(source);
Integer min = NaN;
Integer minNode = 0;
for(int i = 0;i<T.size();i++)
{
//如果权值较小则改变,否则不变
int temp1 = distance[source-1][T.get(i)-1];
int temp2 = cost[source-1][T.get(i)-1];
if(temp1!=NaN && totaldistance+temp1 < q[T.get(i)-1]){
q[T.get(i)-1]=totaldistance+temp1;
cost1[T.get(i)-1]=totalcost+temp2;
}
//选择最短距离的点作为Source
if(temp1<min) {
min=temp1;
minNode = T.get(i);
// System.out.println("abc");
}
}
// for(Integer i:q) System.out.print(i+" ");
// System.out.println();
// for(Integer i:cost1) System.out.print(i+" ");
// System.out.println();
//修改Source 和起始权值及代价
source = minNode;
totaldistance = q[minNode-1];
totalcost = cost1[minNode-1];
if(source == terminal)
{
System.out.println(totaldistance+" "+totalcost);
break;
}
}
}
}
}