If you are using C++ for this problem, use scanf instead of cin for input.
The problem seems hard at first but is very easy if you understand the logic.
Hint 1:
Hint 2:
Hint 3: