Idea: Each set of numbers entered is stored with arraylist<integer> arr, each circle of friends (set) is represented by a hashset<integer> tmp,arraylist<integer> res Number of people used to store each circle of friends.
For arr[i],i to be even, it is the first number of each group, and I is odd to indicate that it is the second number of each group.
The last set of numbers (2) is used as the initial element of the hashset<integer> tmp, then the number of each set of numbers preceding it is determined to appear in the collection, and if so, the set of numbers is added to the collection, and the set of numbers is deleted in ArrayList arr;
If the number of elements in the collection has changed during the traversal, you will need to iterate over them again. When the elements in the collection have not changed after a traversal, the circle of friends has been found.
Use the same method for the remaining number of arraylist<integer> arr, until arr.size () = 0.
The Java implementation is as follows:
Import Java.util.arraylist;import java.util.collections;import Java.util.hashset;import Java.util.List;import Java.util.scanner;public class Main {public static void Main (string[] args) {Scanner input = new Scanner (system.in); int n = Input.nextint ();//list
Circle of Friends