Find two disjoint good sets of vertices in a given graph Last Updated : 05 Oct, 2021 Summarize Comments Improve Suggest changes Share Like Article Like Report Given an undirected unweighted graph with N vertices and M edges. The task is to find two disjoint good sets of vertices. A set X is called good if for every edge UV in the graph at least one of the endpoint belongs to X(i.e, U or V or both U and V belong to X). If it is not possible to make such sets then print -1. Examples: Input : Output : {1 3 4 5} ,{2 6} One disjoint good set contains vertices {1, 3, 4, 5} and other contains {2, 6}. Input : Output : -1 Approach: One of the observations is that there is no edge UV that U and V are in the same set. The two good sets form a bipartition of the graph, so the graph has to be bipartite. And being bipartite is also sufficient. Read about bipartition here. Below is the implementation of the above approach : C++ // C++ program to find two disjoint // good sets of vertices in a given graph #include <bits/stdc++.h> using namespace std; #define N 100005 // For the graph vector<int> gr[N], dis[2]; bool vis[N]; int colour[N]; bool bip; // Function to add edge void Add_edge(int x, int y) { gr[x].push_back(y); gr[y].push_back(x); } // Bipartite function void dfs(int x, int col) { vis[x] = true; colour[x] = col; // Check for child vertices for (auto i : gr[x]) { // If it is not visited if (!vis[i]) dfs(i, col ^ 1); // If it is already visited else if (colour[i] == col) bip = false; } } // Function to find two disjoint // good sets of vertices in a given graph void goodsets(int n) { // Initially assume that graph is bipartite bip = true; // For every unvisited vertex call dfs for (int i = 1; i <= n; i++) if (!vis[i]) dfs(i, 0); // If graph is not bipartite if (!bip) cout << -1; else { // Differentiate two sets for (int i = 1; i <= n; i++) dis[colour[i]].push_back(i); // Print vertices belongs to both sets for (int i = 0; i < 2; i++) { for (int j = 0; j < dis[i].size(); j++) cout << dis[i][j] << " "; cout << endl; } } } // Driver code int main() { int n = 6, m = 4; // Add edges Add_edge(1, 2); Add_edge(2, 3); Add_edge(2, 4); Add_edge(5, 6); // Function call goodsets(n); } Java // Java program to find two disjoint // good sets of vertices in a given graph import java.util.*; class GFG { static int N = 100005; // For the graph @SuppressWarnings("unchecked") static Vector<Integer>[] gr = new Vector[N], dis = new Vector[2]; static { for (int i = 0; i < N; i++) gr[i] = new Vector<>(); for (int i = 0; i < 2; i++) dis[i] = new Vector<>(); } static boolean[] vis = new boolean[N]; static int[] color = new int[N]; static boolean bip; // Function to add edge static void add_edge(int x, int y) { gr[x].add(y); gr[y].add(x); } // Bipartite function static void dfs(int x, int col) { vis[x] = true; color[x] = col; // Check for child vertices for (int i : gr[x]) { // If it is not visited if (!vis[i]) dfs(i, col ^ 1); // If it is already visited else if (color[i] == col) bip = false; } } // Function to find two disjoint // good sets of vertices in a given graph static void goodsets(int n) { // Initially assume that graph is bipartite bip = true; // For every unvisited vertex call dfs for (int i = 1; i <= n; i++) if (!vis[i]) dfs(i, 0); // If graph is not bipartite if (!bip) System.out.println(-1); else { // Differentiate two sets for (int i = 1; i <= n; i++) dis[color[i]].add(i); // Print vertices belongs to both sets for (int i = 0; i < 2; i++) { for (int j = 0; j < dis[i].size(); j++) System.out.print(dis[i].elementAt(j) + " "); System.out.println(); } } } // Driver Code public static void main(String[] args) { int n = 6, m = 4; // Add edges add_edge(1, 2); add_edge(2, 3); add_edge(2, 4); add_edge(5, 6); // Function call goodsets(n); } } // This code is contributed by // sanjeev2552 Python3 # Python 3 program to find two disjoint # good sets of vertices in a given graph N = 100005 # For the graph gr = [[] for i in range(N)] dis = [[] for i in range(2)] vis = [False for i in range(N)] colour = [0 for i in range(N)] bip = 0 # Function to add edge def Add_edge(x, y): gr[x].append(y) gr[y].append(x) # Bipartite function def dfs(x, col): vis[x] = True colour[x] = col # Check for child vertices for i in gr[x]: # If it is not visited if (vis[i] == False): dfs(i, col ^ 1) # If it is already visited elif (colour[i] == col): bip = False # Function to find two disjoint # good sets of vertices in a given graph def goodsets(n): # Initially assume that # graph is bipartite bip = True # For every unvisited vertex call dfs for i in range(1, n + 1, 1): if (vis[i] == False): dfs(i, 0) # If graph is not bipartite if (bip == 0): print(-1) else: # Differentiate two sets for i in range(1, n + 1, 1): dis[colour[i]].append(i) # Print vertices belongs to both sets for i in range(2): for j in range(len(dis[i])): print(dis[i][j], end = " ") print('\n', end = "") # Driver code if __name__ == '__main__': n = 6 m = 4 # Add edges Add_edge(1, 2) Add_edge(2, 3) Add_edge(2, 4) Add_edge(5, 6) # Function call goodsets(n) # This code is contributed # by Surendra_Gangwar C# // C# program to find two // disjoint good sets of // vertices in a given graph using System; using System.Collections.Generic; class GFG{ static int N = 100005; // For the graph static List<int>[] gr = new List<int>[N], dis = new List<int>[2]; static bool[] vis = new bool[N]; static int[] color = new int[N]; static bool bip; // Function to add edge static void add_edge(int x, int y) { gr[x].Add(y); gr[y].Add(x); } // Bipartite function static void dfs(int x, int col) { vis[x] = true; color[x] = col; // Check for child vertices foreach (int i in gr[x]) { // If it is not visited if (!vis[i]) dfs(i, col ^ 1); // If it is already visited else if (color[i] == col) bip = false; } } // Function to find two disjoint // good sets of vertices in a // given graph static void goodsets(int n) { // Initially assume that // graph is bipartite bip = true; // For every unvisited // vertex call dfs for (int i = 1; i <= n; i++) if (!vis[i]) dfs(i, 0); // If graph is not bipartite if (!bip) Console.WriteLine(-1); else { // Differentiate two sets for (int i = 1; i <= n; i++) dis[color[i]].Add(i); // Print vertices belongs // to both sets for (int i = 0; i < 2; i++) { for (int j = 0; j < dis[i].Count; j++) Console.Write(dis[i][j] + " "); Console.WriteLine(); } } } // Driver Code public static void Main(String[] args) { int n = 6, m = 4; for (int i = 0; i < N; i++) gr[i] = new List<int>(); for (int i = 0; i < 2; i++) dis[i] = new List<int>(); // Add edges add_edge(1, 2); add_edge(2, 3); add_edge(2, 4); add_edge(5, 6); // Function call goodsets(n); } } // This code is contributed by shikhasingrajput JavaScript <script> // JavaScript program to find two // disjoint good sets of // vertices in a given graph var N = 100005; // For the graph var gr = Array.from(Array(N), ()=>Array()); var dis = Array.from(Array(2), ()=>Array()); var vis = Array(N).fill(false); var color = Array(N).fill(0); var bip; // Function to add edge function add_edge(x, y) { gr[x].push(y); gr[y].push(x); } // Bipartite function function dfs(x, col) { vis[x] = true; color[x] = col; // Check for child vertices for(var i of gr[x]) { // If it is not visited if (!vis[i]) dfs(i, col ^ 1); // If it is already visited else if (color[i] == col) bip = false; } } // Function to find two disjoint // good sets of vertices in a // given graph function goodsets(n) { // Initially assume that // graph is bipartite bip = true; // For every unvisited // vertex call dfs for (var i = 1; i <= n; i++) if (!vis[i]) dfs(i, 0); // If graph is not bipartite if (!bip) document.write(-1 + "<br>"); else { // Differentiate two sets for (var i = 1; i <= n; i++) dis[color[i]].push(i); // Print vertices belongs // to both sets for (var i = 0; i < 2; i++) { for (var j = 0; j < dis[i].length; j++) document.write(dis[i][j] + " "); document.write("<br>") } } } // Driver Code var n = 6, m = 4; // push edges add_edge(1, 2); add_edge(2, 3); add_edge(2, 4); add_edge(5, 6); // Function call goodsets(n); </script> Output: 1 3 4 5 2 6 Time Complexity: O(n) Space Complexity: O(n) Comment More infoAdvertise with us Next Article Find two disjoint good sets of vertices in a given graph P pawan_asipu Follow Improve Article Tags : DSA Graph Coloring Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 4 min read Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ 3 min read Like