|
| 1 | +PROBLEM: |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | + |
| 6 | +Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size. |
| 7 | +Each person may dislike some other people, and they should not go into the same group. |
| 8 | +Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group. |
| 9 | +Return true if and only if it is possible to split everyone into two groups in this way. |
| 10 | + |
| 11 | + |
| 12 | +Example 1: |
| 13 | +Input: N = 4, dislikes = [[1,2],[1,3],[2,4]] |
| 14 | +Output: true |
| 15 | +Explanation: group1 [1,4], group2 [2,3] |
| 16 | + |
| 17 | +Example 2: |
| 18 | +Input: N = 3, dislikes = [[1,2],[1,3],[2,3]] |
| 19 | +Output: false |
| 20 | + |
| 21 | +Example 3: |
| 22 | +Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]] |
| 23 | +Output: false |
| 24 | + |
| 25 | + |
| 26 | +Note: |
| 27 | + |
| 28 | +1. 1 <= N <= 2000 |
| 29 | +2. 0 <= dislikes.length <= 10000 |
| 30 | +3. 1 <= dislikes[i][j] <= N |
| 31 | +4. dislikes[i][0] < dislikes[i][1] |
| 32 | +5. There does not exist i != j for which dislikes[i] == dislikes[j]. |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | +SOLUTION: |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +class Solution { |
| 43 | +public: |
| 44 | + |
| 45 | + bool dfs(vector<int> adj[],vector<bool>& vis,int color[],int s) |
| 46 | + { |
| 47 | + vis[s]=true; |
| 48 | + |
| 49 | + for(auto k:adj[s]) |
| 50 | + { |
| 51 | + if(!vis[k]) |
| 52 | + { |
| 53 | + color[k]=1-color[s]; |
| 54 | + |
| 55 | + if(dfs(adj,vis,color,k)==false) |
| 56 | + return false; |
| 57 | + |
| 58 | + } |
| 59 | + else if(color[k]==color[s]) |
| 60 | + return false; |
| 61 | + } |
| 62 | + |
| 63 | + return true; |
| 64 | + } |
| 65 | + |
| 66 | + bool possibleBipartition(int N, vector<vector<int>>& dislikes) { |
| 67 | + |
| 68 | + int n,m,i,j,a,b; |
| 69 | + n=dislikes.size(); |
| 70 | + |
| 71 | + vector<int> adj[N+1]; |
| 72 | + vector<bool> vis(N+1,false); |
| 73 | + int color[N+1]; |
| 74 | + |
| 75 | + for(i=0;i<n;i++) |
| 76 | + { |
| 77 | + a=dislikes[i][0]; |
| 78 | + b=dislikes[i][1]; |
| 79 | + |
| 80 | + adj[a].push_back(b); |
| 81 | + adj[b].push_back(a); |
| 82 | + } |
| 83 | + |
| 84 | + for(i=1;i<=N;i++) |
| 85 | + { |
| 86 | + if(!vis[i]) |
| 87 | + { |
| 88 | + color[i]=0; |
| 89 | + if(dfs(adj,vis,color,i)==false) |
| 90 | + return false; |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + |
| 95 | + return true; |
| 96 | + |
| 97 | + } |
| 98 | +}; |
0 commit comments