Lionet (Lev Valkin) helped a lot with excelent solution: store pids in duplicate_bag with key by state. It happened to be very complicated solution, but fastest.