Codechef Long 16 May

I was trying to solve Chef and amazingness problem but couldn’t think of any approach to solve large test cases . If any one if free to explain the idea please help me with it, link to the problem statement → CodeChef: Practical coding for everyone . I can see some kind of bitmasking is done but not able to figure out anything.