• + 1 comment

    Because checking if a value is in list is deadly inefficient: you may need about 20*100*1000000*1000000 operations, the first million is for len(states) in "for x", the second - for "not in states".
    You may add a boolean list qstates[G+1] for faster checking, or appending anyway, but throw away duplicates after sorting, or change list to set. The last way runs in 1.22s on the worst TC #10. Trying first a greedy approach might reduce possible G to be under 5000. My algo (in C++14) works in 0s for any of the testcases.