Even my Brute Force approach was not working. This is what I thought - Let’s take every triplet i, j, k by naively iterating over all the possible triplets i, j, k. Next we determine if all the 3 nodes in the triplet are connected to each other(that is, if every node in the triplet is reachable from every other node). This can be easily done by taking the sum graph[i][j]
, graph[j][k]
and graph[i][k]
and finding if it equals to 2, here graph[i][j]
is the Adjacency Matrix representation of the graph, where gaph[i][j]
is set to 1 if nodes i and j are adjacent or 0 otherwise.
Next, if all the nodes are reachable from one another then we find which among the three is the parent of the rest, by parent I mean the node which is adjacent to both the other two nodes. Let’s say for example, j is our parent node here and i and k are other nodes of this triplet and reachable from one another(via j). So, finally we check if either i, j, k or k, j, i follows the order specified in Ramsay’s Restaurant Sequence and if it does we increment the answer by 1.
I tried my code on sample cases made by me and I was getting the expected result but WA on submission. Here is my submission- CodeChef: Practical coding for everyone
So, can anyone please-
- Explain me what’s wrong with my approach?
- The optimal approach with a step-step explanation.