<?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>NP Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/np/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/np/</link>
	<description></description>
	<lastBuildDate>Sun, 28 Jun 2020 07:06:10 +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>NP Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/np/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1494. Parallel Courses II</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1494-parallel-courses-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1494-parallel-courses-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Jun 2020 05:41:08 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[bitmask]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[NP]]></category>
		<category><![CDATA[state compression]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6982</guid>

					<description><![CDATA[<p>Given the integer&#160;n&#160;representing the number of courses at some university labeled from&#160;1&#160;to&#160;n, and the array&#160;dependencies&#160;where&#160;dependencies[i] = [xi, yi]&#160;&#160;represents a prerequisite relationship, that is, the course&#160;xi&#160;must&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1494-parallel-courses-ii/">花花酱 LeetCode 1494. Parallel Courses II</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>Given the integer&nbsp;<code>n</code>&nbsp;representing the number of courses at some university labeled from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>, and the array&nbsp;<code>dependencies</code>&nbsp;where&nbsp;<code>dependencies[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>&nbsp;&nbsp;represents a prerequisite relationship, that is, the course&nbsp;<code>x<sub>i</sub></code>&nbsp;must be taken before the course&nbsp;<code>y<sub>i</sub></code>. &nbsp;Also, you are given the&nbsp;integer&nbsp;<code>k</code>.</p>



<p>In one semester you can take&nbsp;<strong>at most</strong>&nbsp;<code>k</code>&nbsp;courses as long as you have taken all the prerequisites for the courses you are taking.</p>



<p><em>Return the minimum number of semesters to take all courses</em>.&nbsp;It is guaranteed that you can take all courses in some way.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/05/22/leetcode_parallel_courses_1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4, dependencies = [[2,1],[3,1],[1,4]], k = 2
<strong>Output:</strong> 3 
<strong>Explanation:</strong> The figure above represents the given graph. In this case we can take courses 2 and 3 in the first semester, then take course 1 in the second semester and finally take course 4 in the third semester.
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/05/22/leetcode_parallel_courses_2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, dependencies = [[2,1],[3,1],[4,1],[1,5]], k = 2
<strong>Output:</strong> 4 
<strong>Explanation:</strong> The figure above represents the given graph. In this case one optimal way to take all courses is: take courses 2 and 3 in the first semester and take course 4 in the second semester, then take course 1 in the third semester and finally take course 5 in the fourth semester.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 11, dependencies = [], k = 2
<strong>Output:</strong> 6
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= n &lt;= 15</code></li><li><code>1 &lt;= k &lt;= n</code></li><li><code>0 &lt;=&nbsp;dependencies.length &lt;= n * (n-1) / 2</code></li><li><code>dependencies[i].length == 2</code></li><li><code>1 &lt;= x<sub>i</sub>, y<sub>i</sub>&nbsp;&lt;= n</code></li><li><code>x<sub>i</sub>&nbsp;!= y<sub>i</sub></code></li><li>All prerequisite relationships are distinct, that is,&nbsp;<code>dependencies[i] != dependencies[j]</code>.</li><li>The given graph is a directed acyclic graph.</li></ul>



<h2><strong>Solution: DP</strong> <strong>/ Bitmask</strong></h2>



<p>NOTE: This is a NP problem, any polynomial-time algorithm is incorrect otherwise P = NP.</p>



<p>Variant 1:<br>dp[m] := whether state m is reachable, where m is the bitmask of courses studied.<br>For each semester, we enumerate all possible states from 0 to 2^n &#8211; 1, if that state is reachable, then we choose c (c &lt;= k) courses from n and check whether we can study those courses.<br>If we can study those courses, we have a new reachable state, we set dp[m | courses] = true.</p>



<p>Time complexity: O(n*2^n*2^n) = O(n*n^4) &lt;&#8211; This will be much smaller in practice.<br>and can be reduced to O(n*3^n).<br>Space complexity: O(2^n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 52 ms, 14.5 MB
class Solution {
public:
  int minNumberOfSemesters(int n, vector&lt;vector&lt;int&gt;&gt;&amp; dependencies, int k) {    
    const int S = 1 &lt;&lt; n;
    vector&lt;int&gt; deps(n); // deps[i] = dependency mask for course i.
    for (const auto&amp; d : dependencies)
      deps[d[1] - 1] |= 1 &lt;&lt; (d[0] - 1);    
    // dp(i)[s] := reachable(s) at semester i.
    vector&lt;int&gt; dp(S);
    dp[0] = 1;
    for (int d = 1; d &lt;= n; ++d) { // at most n semesters.
      vector&lt;int&gt; tmp(S); // start a new semesters.
      for (int s = 0; s &lt; S; ++s) {
        if (!dp[s]) continue; // not a reachable state.
        int mask = 0;
        for (int i = 0; i &lt; n; ++i)
          if (!(s &amp; (1 &lt;&lt; i)) &amp;&amp; (s &amp; deps[i]) == deps[i]) 
            mask |= (1 &lt;&lt; i);
        // Prunning, take all.
        if (__builtin_popcount(mask) &lt;= k) {
          tmp[s | mask] = 1;         
        } else {
          // Try all subsets. 
          for (int c = mask; c; c = (c - 1) &amp; mask)
            if (__builtin_popcount(c) &lt;= k) {
              tmp[s | c] = 1;
            }
        }
        if (tmp.back()) return d;
      }
      dp.swap(tmp);      
    }
    return -1;
  }
};</pre>
</div></div>



<p>Variant 2:<br>dp[m] := min semesters to reach state m.<br>dp[m | c] = min{dp[m | c], dp[m] + 1}, if we can reach m | c from m.<br>This allows us to get rid of enumerate n semesters.<br>Time complexity: O(2^n*2^n) &lt;&#8211; This will be much smaller in practice.<br>and can be reduced to O(3^n).<br>Space complexity: O(2^n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 16 ms, 8.5 MB
class Solution {
public:
  int minNumberOfSemesters(int n, vector&lt;vector&lt;int&gt;&gt;&amp; dependencies, int k) {
    const int kInf = 1e9;
    const int S = 1 &lt;&lt; n;
    vector&lt;int&gt; deps(n); // deps[i] = dependency mask for course i.
    for (const auto&amp; d : dependencies)
      deps[d[1] - 1] |= 1 &lt;&lt; (d[0] - 1);    
    // dp[m] := min semesters to reach state m.
    vector&lt;int&gt; dp(S, kInf);
    dp[0] = 0;
    for (int s = 0; s &lt; S; ++s) {
      if (dp[s] == kInf) continue; // not reachable.
      // Generate a mask of courses we can study under state s.
      int mask = 0;
      for (int i = 0; i &lt; n; ++i)
        if (!(s &amp; (1 &lt;&lt; i)) &amp;&amp; (s &amp; deps[i]) == deps[i])
          mask |= (1 &lt;&lt; i);
      // Prunning, take all.
      if (__builtin_popcount(mask) &lt;= k) {
        dp[s | mask] = min(dp[s | mask], dp[s] + 1);       
      } else {
        // Try all subsets.
        for (int c = mask; c; c = (c - 1) &amp; mask)
          if (__builtin_popcount(c) &lt;= k)
            dp[s | c] = min(dp[s | c], dp[s] + 1);
      }
      // Early termination?
      if (dp.back() != kInf) return dp.back();
    }
    return dp.back();
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1494-parallel-courses-ii/">花花酱 LeetCode 1494. Parallel Courses II</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-1494-parallel-courses-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
