AcWing 920. 最优乘车
原题链接
中等
作者:
Ccc1Z
,
2020-07-14 16:18:26
,
所有人可见
,
阅读 527
思路:
- 求所有边权为1的单源最短路 (BFS,Dijkstra,spfa)
- 难点:建图
- 理解题意 何为换乘
spfa
import java.io.*;
import java.util.*;
public class Main{
private static int N = 1000;
private static int n,m,idx,INF = 0x3f3f3f3f;
private static int[] h,e,ne;
private static boolean[] st = new boolean[N];
private static int[] dist = new int[N];
private static void add(int a,int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
private static int spfa(){
Arrays.fill(dist,INF);
dist[1] = 0;
Queue<Integer> que = new LinkedList<>();
que.offer(1);
st[1] = true;
while(!que.isEmpty()){
int t = que.poll();
st[t] = false;
for(int i = h[t] ; i != -1 ; i = ne[i]){
int j = e[i];
if(dist[j] > dist[t] + 1){
dist[j] = dist[t] + 1;
if(!st[j]){
que.offer(j);
st[j] = true;
}
}
}
}
if(dist[n] == INF) return -1;
return dist[n]-1;
}
public static void main(String[] args)throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] s = in.readLine().split("\\s+");
m = Integer.valueOf(s[0]);
n = Integer.valueOf(s[1]);
h = new int[N];e = new int[N];ne = new int[N];
Arrays.fill(h,-1);
while(m-->0){
s = in.readLine().split("\\s+");
for(int i = 0 ; i < s.length-1 ; i++){
int a = Integer.valueOf(s[i]);
for(int j = i +1 ; j < s.length ; j++){
int b = Integer.valueOf(s[j]);
add(a,b);
}
}
}
int ans = spfa();
if(ans == -1) System.out.println("NO");
else System.out.println(ans);
}
}