![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ code to check all bulbs can be turned on or not
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.
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.
Steps
To solve this, we will follow these steps −
Define one set s for initialize i := 0, when i < size of A, update (increase i by 1), do: for initialize j := 0, when j < size of A[i], update (increase j by 1), do: insert A[i, j] into s if size of s is same as m, then: return true Otherwise return false
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; bool solve(vector<vector<int>> A, int m){ set<int> s; for (int i = 0; i < A.size(); i++){ for (int j = 0; j < A[i].size(); j++){ s.insert(A[i][j]); } } if (s.size() == m) return true; else return false; } int main(){ vector<vector<int>> A = { { 1, 4 }, { 1, 3, 1 }, { 2 } }; int m = 4; cout <<solve(A, m) << endl; }
Input
{ { 1, 4 }, { 1, 3, 1 }, { 2 } }, 4
Output
1
Advertisements