I’m having trouble figuring out the solution to this problem. I know it somehow involves DSU, but the only method I have is as follows:

For each cow that has at least 2 admirers, start a equal BFS, merging all of the cows (using DSU) that are at the same “level” of the BFS.

However, this has 2 problems. First, I don’t know when to stop, since infinite loops can occur, and second of all, this results in an O(n^2) solution, which is too slow.

Any help?