Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Possible Bipartition

Moderate
0/80
Average time to solve is 20m
profile
Contributed by
11 upvotes
Asked in companies
SprinklrAppleAmazon

Problem statement

You are given an integer ‘N’ which denotes a set of N people numbered from 1 to N and a matrix ‘DISLIKE’ with M rows and 2 columns. Each row in the matrix denotes two people who dislike each other i.e. for any valid row i, DISLIKE[i][0] dislikes DISLIKE[i][1] and vice versa.

Your task is to split the set of N people into two groups under the conditions:

1. It is not allowed to put two persons in the same group who dislike each other.

2. The size of the two groups may or may not be equal.

3. Each person from the set belongs to exactly one group.

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer ‘T’, denoting the number of test cases. The test cases follow.

The first line of each test case contains two integers ‘N’ and ‘M’, which denotes the number of people in the given set and the number of rows of the matrix ‘DISLIKE’.

The next M lines contain two integers, DISLIKE[i][0] and DISLIKE[i][1], denoting the two people who dislike each other.
Output Format:
For each test case, print a single line containing 1 if it is possible to split everyone into two groups under the given conditions otherwise print 0.

The output of each test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1<= T <= 10
1 <= N <= 2000
0 <= M <= 5000
DISLIKE[i].size = 2
1 <= DISLIKE[i][0],DISLIKE[i][1] <=N
DISLIKE[i][0] != DISLIKE[i][1], for any valid i

Where ’T’ is the number of test cases, and N denotes the number of people in the set’, M denotes the size of the given matrix ‘DISLIKE’.

Time Limit: 1 sec.
Sample Input 1:
2
5 4
1 2
1 3
1 4
1 5
5 5
2 3
3 4
4 5
1 5
1 2
Sample Output 1:
1
0
Explanation for Sample Input 1:
In the first test case, there is a set of 5 people and the size of the dislike matrix is 4. Pairs of people who dislike each other are {1,2}, {1,3}, {1,4}, {1,5}.
It means we can divide the given set of 5 people into two groups by keeping Person 1 in the first group and all the other people in the second group.

In the second test case, there is a set of 5 people and the size of the dislike matrix is 5. Pairs of people who dislike each other are {2,3}, {3,4}, {4,5}, {1,5}, {1,2}.
There is no possible division that can divide the set of 5 people into 2 groups.
Sample Input 2:
2
4 3
1 2
1 3
2 4
10 9
1 2
1 3
1 4
1 5
1 8
1 6
1 9
1 7
1 10
Sample Output 2:
1
1
Full screen
Console