您的位置:首页 > 其它

题目1008:最短路径问题

2014-11-12 20:17 489 查看
题目1008:最短路径问题

时间限制:1 秒

内存限制:32 兆

特殊判题:否

提交:6500

解决:2115

题目描述:
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。

输入:
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点t。n和m为0时输入结束。

(1<n<=1000, 0<m<100000, s != t)

输出:
输出 一行有两个数, 最短距离及其花费。

样例输入:
3 2
1 2 5 6
2 3 4 5
1 3
0 0


样例输出:
9 11


参考代码:空间复杂度和时间复杂度都十分惊人

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;
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: