Hints for SRM 682, D1, 250-Pointer (SmilesTheFriendshipUnicorn)

James S. Plank

Fri Feb 26 11:43:47 EST 2016
Problem Statement.
This is one of those problems where the writeup makes it more confusing than it needs to be. The part that confused me was "For every group containing between 1 and N-1 people (inclusive), at least one person in the group is friends with someone outside the group." I'm guessing that's a fancy way of saying that the graph is connected. Big whup.

So this is a boring old graph problem -- return whether or not a graph has a simple path of length four. DFS plain and simple. However, unlike cycle detection or connected component determination, once you call DFS on a child, and the call returns, you need to clear the visited field for the child. Take the following ASCII art as an example:

A---B---D---E
 \  |
  \ |
   \|
    C

Now, suppose you start a DFS from A. If the DFS starts with node B, you'll do the following:

DFS(A) with a path length of zero.
  DFS(B) with a path length of one.
    DFS(C) with a path length of two.  That returns.
    DFS(D) with a path length of two.  
      DFS(E) with a path length of three. That returns.
    DFS(D) returns that the longest path was three.
  DFS(B) returns that the longest path was three.
At this point, we are back in DFS(A). It needs to call DFS(C) to find the path. However, if you haven't cleared out the Visited fields for B, C, D and E, you won't find the path. For that reason, when DFS(n) returns, you should clear the Visited field for n.

You also need to cut the DFS short as soon as you find the path of length four. Otherwise, your program can have an exponential blow-up of DFS calls.

Just to help you a little more -- my DFS call had two parameters: DFS(n,l). The node is n, and the path length to n is l. That lets you cut the DFS short when l reaches 4.