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: https://drive.google.com/file/d/1D6ESAuTFvnhAe-lIIzmAqtC3phaTRm06/view?usp=sharing
Tencent Docs: https://docs.qq.com/pdf/DU1VaVUZHTUVrS0Nv
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.