- 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
Possible Bipartition in C++
Suppose we have a set of N people (they are numbered 1, 2, ..., N), we would like to split everyone into two subgroups of any size. Now each person may dislike some other people, and they should not go into the same group. So, if dislikes[i] = [a, b], it indicates that it is not allowed to put the people numbered a and b into the same group. We have to find if it is possible to split everyone into two groups in this way.
So if the input is like N = 4 and dislike = [[1,2],[1,3],[2,4]], the output will be true, the group will be [1,4] and [2,3].
To solve this, we will follow these steps −
Create an array of sets called groups, there will be two groups
Create a method called dfs(), this will take node, an array graph and x
aux := 1 – x
if groups[aux] has node, then return false
insert node into groups[x]
for i in range 0 to size of graph[node] – 1
u := graph[node, i]
if groups[aux] has no u and dfs(u, graph, aux) is false, then return false
otherwise return true
From the main method do the following −
make an array called graph of size [N + 1]
for i in range 0 to size of dislikes - 1
u := dislikes[i, 0], v := dislikes[i, 1]
insert v into graph[u] and insert u into graph[v]
for i in range 1 to N
if groups[0] does not contain i and groups[1] does not have i, then
if dfs(i, graph, 0) is false, then return false
return true.
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: set <int> groups[2]; bool dfs(int node, vector <int> graph[], int x){ int aux = 1 - x; if(groups[aux].count(node)) return false; groups[x].insert(node); for(int i = 0; i < graph[node].size(); i++){ int u = graph[node][i]; if(!groups[aux].count(u) && !dfs(u, graph, aux)) return false; } return true; } bool possibleBipartition(int N, vector<vector<int<<& dislikes) { vector <int> graph[N + 1]; for(int i = 0; i < dislikes.size(); i++){ int u = dislikes[i][0]; int v = dislikes[i][1]; graph[u].push_back(v); graph[v].push_back(u); } for(int i = 1; i <= N;i++){ if(!groups[0].count(i) && !groups[1].count(i)){ if(!dfs(i, graph, 0)) return false; } } return true; } }; main(){ vector<vector<int>> v = {{1,2},{1,3},{2,4}}; Solution ob; cout << (ob.possibleBipartition(4, v)); }
Input
4 [[1,2],[1,3],[2,4]]
Output
true
To Continue Learning Please Login
Login with Google