您的位置:首页 > 其它

hihocoder 1093 : 最短路径·三:SPFA算法

2017-09-12 09:43 323 查看
时间限制:10000ms
单点时限:1000ms
内存限制:256MB


描述

万圣节的晚上,小Hi和小Ho在吃过晚饭之后,来到了一个巨大的鬼屋!
鬼屋中一共有N个地点,分别编号为1..N,这N个地点之间互相有一些道路连通,两个地点之间可能有多条道路连通,但是并不存在一条两端都是同一个地点的道路。
不过这个鬼屋虽然很大,但是其中的道路并不算多,所以小Hi还是希望能够知道从入口到出口的最短距离是多少?
提示:Super Programming Festival Algorithm。


输入

每个测试点(输入文件)有且仅有一组测试数据。
在一组测试数据中:
第1行为4个整数N、M、S、T,分别表示鬼屋中地点的个数和道路的条数,入口(也是一个地点)的编号,出口(同样也是一个地点)的编号。
接下来的M行,每行描述一条道路:其中的第i行为三个整数u_i, v_i, length_i,表明在编号为u_i的地点和编号为v_i的地点之间有一条长度为length_i的道路。
对于100%的数据,满足N<=10^5,M<=10^6, 1 <= length_i <= 10^3, 1 <= S, T <= N, 且S不等于T。
对于100%的数据,满足小Hi和小Ho总是有办法从入口通过地图上标注出来的道路到达出口。


输出

对于每组测试数据,输出一个整数Ans,表示那么小Hi和小Ho为了走出鬼屋至少要走的路程。

样例输入
5 10 3 5
1 2 997
2 3 505
3 4 118
4 5 54
3 5 480
3 4 796
5 2 794
2 5 146
5 4 604
2 5 63


样例输出

172

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
class Edge{
int start,end;
int val;
Edge(int start, int end, int val) {
this.start = start;
this.end = end;
this.val = val;
}
}
public class Main {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int verNum=scan.nextInt();
int count=scan.nextInt();
int s=scan.nextInt();
int t=scan.nextInt();
List<Edge> graph=new ArrayList<Edge>();
for(int i=0;i<count;i++){
int start=scan.nextInt()-1;
int end=scan.nextInt()-1;
int val=scan.nextInt();
graph.add(new Edge(start,end,val));
graph.add(new Edge(end,start,val));
}
HashMap<Integer,List<Edge>> map=new HashMap<Integer,List<Edge>>();
for(int i=0;i<verNum;i++){
map.put(i,new ArrayList<Edge>());
}
for(Edge edge:graph){
int a=edge.start;
map.get(a).add(edge);
}
System.out.println(solve(map,s-1,t-1,verNum));
}
public static int solve(HashMap<Integer,List<Edge>> graph,int start,int end,int verNum){
final int NN=verNum;
boolean[] visited=new boolean[verNum];
int[] c=new int[verNum];
Queue<Integer> queue=new LinkedList<Integer>();
queue.add(start);
int[] re=new int[verNu
9872
m];
Arrays.fill(re,Integer.MAX_VALUE);
re[start]=0;
visited[start]=true;
while(!queue.isEmpty()){
int top=queue.poll();
visited[top]=false;
List<Edge> nei=graph.get(top);
for(Edge edge:nei){
int to=edge.end;
int val=edge.val;
if(re[top]+val<re[to]){
re[to]=val+re[top];
if(visited[to]) continue;
queue.add(to);
c[to]++;
visited[to]=true;
// if(c[to]>=NN) return 0;
}
}
}
return re[end];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: