<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>bellman-ford Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/bellman-ford/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/bellman-ford/</link>
	<description></description>
	<lastBuildDate>Fri, 31 Aug 2018 19:41:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>bellman-ford Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/bellman-ford/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 787. Cheapest Flights Within K Stops</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-787-cheapest-flights-within-k-stops/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-787-cheapest-flights-within-k-stops/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 22 Feb 2018 16:45:40 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[bellman-ford]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[shortest path]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1842</guid>

					<description><![CDATA[<p>题目大意：给你一些城市之间的机票价格，问从src到dst的最少需要花多少钱，最多可以中转k个机场。 There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. Now given all the cities and fights, together with starting city src and&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-787-cheapest-flights-within-k-stops/">花花酱 LeetCode 787. Cheapest Flights Within K Stops</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/PLY-lbcxEjg?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一些城市之间的机票价格，问从src到dst的最少需要花多少钱，最多可以中转k个机场。</p>
<p>There are <code>n</code> cities connected by <code>m</code> flights. Each fight starts from city <code>u </code>and arrives at <code>v</code> with a price <code>w</code>.</p>
<p>Now given all the cities and fights, together with starting city <code>src</code> and the destination <code>dst</code>, your task is to find the cheapest price from <code>src</code> to <code>dst</code> with up to <code>k</code> stops. If there is no such route, output <code>-1</code>.</p><pre class="crayon-plain-tag">Example 1:
Input: 
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation: 
The graph looks like this:

The cheapest price from city &lt;code&gt;0&lt;/code&gt; to city &lt;code&gt;2&lt;/code&gt; with at most 1 stop costs 200, as marked red in the picture.</pre><p><img src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/16/995.png" alt="" width="200" /></p><pre class="crayon-plain-tag">Example 2:
Input: 
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation: 
The graph looks like this:
The cheapest price from city &lt;code&gt;0&lt;/code&gt; to city &lt;code&gt;2&lt;/code&gt; with at most 0 stop costs 500, as marked blue in the picture.</pre><p><img src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/16/995.png" alt="" width="200" /></p>
<p><strong>Note:</strong></p>
<ul>
<li>The number of nodes <code>n</code> will be in range <code>[1, 100]</code>, with nodes labeled from <code>0</code> to <code>n</code><code> - 1</code>.</li>
<li>The size of <code>flights</code> will be in range <code>[0, n * (n - 1) / 2]</code>.</li>
<li>The format of each flight will be <code>(src, </code><code>dst</code><code>, price)</code>.</li>
<li>The price of each flight will be in the range <code>[1, 10000]</code>.</li>
<li><code>k</code> is in the range of <code>[0, n - 1]</code>.</li>
<li>There will not be any duplicated flights or self cycles.</li>
</ul>
<p><img class="alignnone size-full wp-image-1854" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/787-ep170.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/787-ep170.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/787-ep170-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/787-ep170-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution 1: DFS</strong></h1>
<p>w/o prunning TLE</p>
<p>w/ prunning Accepted</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 36 ms
class Solution {
public:
  int findCheapestPrice(int n, vector&lt;vector&lt;int&gt;&gt;&amp; flights, int src, int dst, int K) {
    g_.clear();  
    for (const auto&amp; e : flights)
      g_[e[0]].emplace_back(e[1], e[2]);
    vector&lt;int&gt; visited(n, 0);
    visited[src] = 1;
    int ans = INT_MAX;
    dfs(src, dst, K + 1, 0, visited, ans);
    return ans == INT_MAX ? - 1 : ans;
  }
private:
  unordered_map&lt;int, vector&lt;pair&lt;int,int&gt;&gt;&gt; g_;
  
  void dfs(int src, int dst, int k, int cost, vector&lt;int&gt;&amp; visited, int&amp; ans) {
    if (src == dst) {
      ans = cost;
      return;
    }
    
    if (k == 0) return;    
    
    for (const auto&amp; p : g_[src]) {
      if (visited[p.first]) continue; // do not visit the same city twice.
      if (cost + p.second &gt; ans) continue; // IMPORTANT!!! prunning 
      visited[p.first] = 1;
      dfs(p.first, dst, k - 1, cost + p.second, visited, ans);
      visited[p.first] = 0;
    }
  }
};</pre><p></div></div></p>
<h1><strong>Solution 2: BFS</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 20 ms
class Solution {
public:
  int findCheapestPrice(int n, vector&lt;vector&lt;int&gt;&gt;&amp; flights, int src, int dst, int K) {
    unordered_map&lt;int, vector&lt;pair&lt;int,int&gt;&gt;&gt; g;
    for (const auto&amp; e : flights)
      g[e[0]].emplace_back(e[1], e[2]);
    
    int ans = INT_MAX;
    queue&lt;pair&lt;int,int&gt;&gt; q;
    q.push({src, 0});
    int steps = 0;
    
    while (!q.empty()) {
      int size = q.size();
      while (size--) {
        int curr = q.front().first;
        int cost = q.front().second;
        q.pop();
        if (curr == dst) 
          ans = min(ans, cost);
        for (const auto&amp; p : g[curr]) {
          if (cost + p.second &gt; ans) continue; // Important: prunning          
          q.push({p.first, cost + p.second});
        }
      }
      if (steps++ &gt; K) break;
    }
    
    return ans == INT_MAX ? - 1 : ans;
  }
};</pre><p></div></div></p>
<h1><strong>Solution 3: Bellman-Ford algorithm</strong></h1>
<p>dp[k][i]: min cost from src to i taken up to k flights (k-1 stops)</p>
<p>init: dp[0:k+2][src] = 0</p>
<p>transition: dp[k][i] = min(dp[k-1][j] + price[j][i])</p>
<p>ans: dp[K+1][dst]</p>
<p>Time complexity: O(k * |flights|) / O(k*n^2)</p>
<p>Space complexity: O(k*n) -&gt; O(n)</p>
<p>w/o space compression O(k*n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++ O(k*n)</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 15 ms
class Solution {
public:
  int findCheapestPrice(int n, vector&lt;vector&lt;int&gt;&gt;&amp; flights, int src, int dst, int K) {
    constexpr int kInfCost = 1e9;
    vector&lt;vector&lt;int&gt;&gt; dp(K + 2, vector&lt;int&gt;(n, kInfCost));
    dp[0][src] = 0;
    
    for (int i = 1; i &lt;= K + 1; ++i) {
      dp[i][src] = 0;
      for (const auto&amp; p : flights)
          dp[i][p[1]] = min(dp[i][p[1]], dp[i-1][p[0]] + p[2]);    
    }
    
    return dp[K + 1][dst] &gt;= kInfCost ? -1 : dp[K + 1][dst];
  }
};</pre><p></div><h2 class="tabtitle">C++ O(n)</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 12 ms
class Solution {
public:
  int findCheapestPrice(int n, vector&lt;vector&lt;int&gt;&gt;&amp; flights, int src, int dst, int K) {
    constexpr int kInfCost = 1e9;
    vector&lt;int&gt; cost(n, kInfCost);
    cost[src] = 0;
    
    for (int i = 0; i &lt;= K; ++i) {
      vector&lt;int&gt; tmp(cost);
      for (const auto&amp; p : flights)
          tmp[p[1]] = min(tmp[p[1]], cost[p[0]] + p[2]);      
      cost.swap(tmp);
    }
    
    return cost[dst] &gt;= kInfCost ? -1 : cost[dst];
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 11 ms
class Solution {
  public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
    final int kInfCost = 1&lt;&lt;30;
    int[] cost = new int[n];
    Arrays.fill(cost, kInfCost);
    cost[src] = 0;
    
    for (int i = 0; i &lt;= K; ++i) {
      int[] tmp = cost.clone();
      for(int[] p: flights)
        tmp[p[1]] = Math.min(tmp[p[1]], cost[p[0]] + p[2]);
      cost = tmp;
    }
    
    return cost[dst] &gt;= kInfCost ? -1 : cost[dst]; 
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 132 ms
"""
class Solution:
  def findCheapestPrice(self, n, flights, src, dst, K):
    kInfCost = 1e9
    cost = [kInfCost for _ in range(n)]
    cost[src] = 0
    
    for i in range(K + 1):
      tmp = list(cost)
      for p in flights:
        tmp[p[1]] = min(tmp[p[1]], cost[p[0]] + p[2])
      cost = tmp
    
    return -1 if cost[dst] &gt;= 1e9 else cost[dst]</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-787-cheapest-flights-within-k-stops/">花花酱 LeetCode 787. Cheapest Flights Within K Stops</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-787-cheapest-flights-within-k-stops/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
