What is wrong with this code for - Bear and House Queries

Can someone point out the error in my code , only 2 test cases are giving correct answer .
I did dry run but found no error.
https://www.codechef.com/viewsolution/32327747