ここでのオリジナルタイトルリンク:https://leetcode.com/problems/cheapest-flights-within-k-stops/
トピック:
あり n
で接続された都市 m
便。それぞれの戦いは、市内から始まる u
と到着 v
価格で w
。
今、一緒に街始まる、すべての都市や航空券を与えられた src
と目的地を dst
、あなたのタスクは、より安い価格を見つけるためにある src
のを dst
、最大で k
止まります。そのようなルート、出力がない場合 -1
。
実施例1: 入力: N = 3、エッジ= [0,1,100]、[1,2,100]、[0,2,500] SRC = 0、DST = 2、K = 1つの 出力:200 説明: グラフのように見えますこの:
街から最も安い価格0
街に2
絵に赤い印として、せいぜい1つのストップでは、200がかかります。
実施例2: 入力: N = 3、エッジ= [0,1,100]、[1,2,100]、[0,2,500] SRC = 0、DST = 2、K = 0 出力:500 説明: グラフのように見えますこの:
街から最も安い価格0
街への2
写真の青いマークとして高々 0ストップでは、500がかかります。
注意:
- ノードの数は、
n
範囲内であろう[1, 100]
から、標識されたノードと、0
にn
- 1
。 - 大きさは、
flights
範囲内であろう[0, n * (n - 1) / 2]
。 - 各フライトの形式になります
(src,
dst
, price)
。 - 各フライトの価格は範囲内であろう
[1, 10000]
。 k
の範囲です[0, n - 1]
。- There will not be any duplicated flights or self cycles.
题解:
When it comes to Dijkstra, it needs PriorityQueue based on cost.
From the example, if the stops is within K, then it could continue update the total cost.
Create a map first.
Initialize PriorityQueue based on current cost. Put src in it.
When polling out head node, check if it is dst, if it is, it must be smallest cost because of PriorityQueue.
Otherwise, get its stop, it is still smaller than K, and check the graph, get next nestinations and accumlate the cost, add to PriorityQueue.
If until the PriorityQueue is empty, there is no return yet, then there is no such route, return -1.
Time Complexity: O(ElogE). E = flights.length. que size could be E, each add and poll takes logE.
Space: O(E). graph size is O(E). que size is O(E).
AC Java:
1 class Solution { 2 public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) { 3 if(n == 0 || K < 0 || flights == null || flights.length == 0 || flights[0].length != 3){ 4 return -1; 5 } 6 7 int res = Integer.MAX_VALUE; 8 9 Map<Integer, List<int []>> graph = new HashMap<>(); 10 for(int [] f : flights){ 11 if(!graph.containsKey(f[0])){ 12 graph.put(f[0], new ArrayList<int []>()); 13 } 14 15 graph.get(f[0]).add(new int[]{f[1], f[2]}); 16 } 17 18 PriorityQueue<Node> que = new PriorityQueue<Node>((a, b) -> a.cost-b.cost); 19 que.add(new Node(src, 0, -1)); 20 while(!que.isEmpty()){ 21 Node cur = que.poll(); 22 23 if(cur.city == dst){ 24 return cur.cost; 25 } 26 27 if(cur.stop < K){ 28 List<int []> nexts = graph.getOrDefault(cur.city, new ArrayList<int []>()); 29 for(int [] next : nexts){ 30 que.add(new Node(next[0], cur.cost+next[1], cur.stop+1)); 31 } 32 } 33 } 34 35 return -1; 36 } 37 } 38 39 class Node{ 40 int city; 41 int cost; 42 int stop; 43 public Node(int city, int cost, int stop){ 44 this.city = city; 45 this.cost = cost; 46 this.stop = stop; 47 } 48 }