its a solutions of of a codeforce problem ->https://codeforces.com/problemset/problem/1819/A
u can try this by submiting this code in codeforce through codeforce site , or run locally by inputting the inputs manually.
example input ->
4
3
1 2 1
4
0 2 2 0
4
3 2 0 2
1
0