This problem belongs to the problem set of Samara University ACM ICPC 2016-2017 Quarterfinal Qualification Contest.
A couple of hints to the problem(Codeforces) would b...
Hints:
1) Use stack to solve this