Can anyone please have a look at my solution for problem D of AtCoder ABC 216 and tell me where did I go wrong? I have compared my solution to a correct solution by comparing multiple test cases but every one of them gives the same answer on both the solutions. The logic was also a lot similar to the successful submission but I'm not able to spot the error in my code. I have commented the code to explain my logic as well as I can.
Problem link: https://atcoder.jp/contests/abc216/tasks/abc216_d
My solution link: https://atcoder.jp/contests/abc216/submissions/25492717
Your logic is absolutely correct it's just that when the queue is empty q.front() will return an undefined behaviour which may not be zero so checking for if it is a zero or not zero might not be the solution to see if it is empty. You may just initially assign them zero and if they are not empty you assign them the value in front. Here is the updated code you can check for reference. Link