Help me in this Cookoff's CO92TREE

I was solving this question from march cook-off using map data structure.can you please tell whats wrong with my code??
link to question: here

link to code: Solution: 17911030 | CodeChef

Fails for test case

1
6
4 5
2 5
3 5
1 5
6 5

Correct answer is 12. Your calculated answer is 8.
I think the code is nearly correct, though too slow to pass the test cases.