I think the official editorial of problem G is a little bit hard to understand for me, therefore I write a learning note, with an example, in English:
Google Drive (Typo corrected): https://drive.google.com/file/d/1imUKYXcxQNw8wC28YFeTzEAkBV2wswMo/view?usp=sharing
Tencent Docs (Typo corrected): https://docs.qq.com/pdf/DU2VOa09uYUJHYU9E
The above pdf files do not contain code. My code:
Spoiler
and my submission: 211097938.
Be careful when handling indices! Here is a wrong submission with Runtime Error: 211089726.