Beautiful Vertices

It is giving TLE.
Please help me with this.

@Karanveer
refer to this corrected code