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: CodeChef: Practical coding for everyone

Fails for test case

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.