There are some nice solutions from other guys (http://mirror.codeforces.com/blog/entry/9071) but they actually are not very handy. However, codeforces api provides us with a useful set of methods that makes tasks like this much easier.
So, you can download the script here and have fun with it.
Happy New Year, guys!
UPD: There were some IndentationErrors (github for some reason changes indentation). Thanks to Determinism who pointed to that. Now it should be fine.