Solution for 330 (runs in 1min45 in Python, should rewrite in C...).