Help on a math problem

Hello, I ask for help on this forum for a quite challenging problem that is on the Italian training platform, the text is English and the problem is this https://training.olinfo.it/#/task/ois_dungeon/statement .
We need some math skills that I think I don’t have, if anyone knows how to solve this problem or which algorithms to use, they would give me a lot of help, thanks and good continuation.