As your solution is too lengthy I can not read it completely but the thing is that your propagation of updates is not correct , for the test case-
1
7 6
1 2 3 4 5 6 7
1 2 6 5
2 2 7 1
1 2 5 2
3 1 4
3 3 7
3 2 6
your codes output is “6” but it should be “2” so simulate your codes
working on this test case and you will know the mistake.