C++ code to check all bulbs can be turned on or not

C++Server Side ProgrammingProgramming

<p>Suppose we have a number m and a nested list A with n sub-lists. Consider there are m bulbs, initially all are turned off. There are n buttons and each of them is connected to some set of bulbs. So A[i] is the set of bulbs that can be turned on by pressing ith switch. We have to check whether we can lit up all the bulbs or not.</p><p>So, if the input is like A = [[1, 4], [1, 3, 1], [2]]; m = 4, then the output will be True, because by pressing all switches we can turn on all four bulbs.</p><h2>Steps</h2><p>To solve this, we will follow these steps &minus;</p><pre class="just-code notranslate language-cpp" data-lang="cpp">Define one set s for initialize i := 0, when i &lt; size of A, update (increase i by 1), do: &nbsp; &nbsp;for initialize j := 0, when j &lt; size of A[i], update (increase j by 1), do: &nbsp; &nbsp; &nbsp; insert A[i, j] into s if size of s is same as m, then: &nbsp; &nbsp;return true Otherwise &nbsp; &nbsp;return false</pre><h2>Example</h2><p>Let us see the following implementation to get better understanding &minus;</p><pre class="demo-code notranslate language-cpp" data-lang="cpp">#include &lt;bits/stdc++.h&gt; using namespace std; bool solve(vector&lt;vector&lt;int&gt;&gt; A, int m){ &nbsp; &nbsp;set&lt;int&gt; s; &nbsp; &nbsp;for (int i = 0; i &lt; A.size(); i++){ &nbsp; &nbsp; &nbsp; for (int j = 0; j &lt; A[i].size(); j++){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.insert(A[i][j]); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;if (s.size() == m) &nbsp; &nbsp; &nbsp; return true; &nbsp; &nbsp;else &nbsp; &nbsp; &nbsp; return false; } int main(){ &nbsp; &nbsp;vector&lt;vector&lt;int&gt;&gt; A = { { 1, 4 }, { 1, 3, 1 }, { 2 } }; &nbsp; &nbsp;int m = 4; &nbsp; &nbsp;cout &lt;&lt;solve(A, m) &lt;&lt; endl; }</pre><h2>Input</h2><pre class="result notranslate">{ { 1, 4 }, { 1, 3, 1 }, { 2 } }, 4</pre><h2>Output</h2><pre class="result notranslate">1</pre>
Updated on 15-Mar-2022 06:46:48