90.1k views
4 votes
write an algorithm which, given the set s and a complete list of the pairs of people who dislike each other, will determine the two groups, or declare it is impossible.

User Duncanmoo
by
9.0k points

1 Answer

4 votes

Final answer:

One way to solve this problem is by using the concept of graph theory and finding connected components. First, represent each person as a vertex in the graph and each pair of people who dislike each other as a directed edge between the corresponding vertices. Then, use depth-first search (DFS) to traverse the graph and identify the connected components or declare it impossible if a cycle is found.

Step-by-step explanation:

One way to solve this problem is by using the concept of graph theory and finding connected components. First, we represent each person as a vertex in the graph and each pair of people who dislike each other as a directed edge between the corresponding vertices. Then, we can use depth-first search (DFS) to traverse through the graph and identify the connected components. If there is a cycle present in any connected component, it means it is impossible to divide the people into two groups.

Here is the algorithm in pseudo code:

  1. Create an empty graph
  2. Add vertices for all the people in the set
  3. Add directed edges between vertices representing pairs of people who dislike each other
  4. Perform DFS on the graph, starting from each unvisited vertex and keeping track of the visited vertices
  5. For each DFS traversal, if a cycle is found, declare it is impossible
  6. Otherwise, divide the people into two groups based on the visited vertices

For example, consider the set S = {A, B, C, D} and pairs of people who dislike each other: (A, B) and (C, D). The graph representation will be:

A -> B
C -> D

We start DFS from vertex A and find that A, B, C, and D are all visited. There is no cycle, so we can divide them into two groups as {A, C} and {B, D}.

User Justin Fay
by
7.8k points