I think all these sets should be unordered_sets otherwise the performance is n*log(n) and not n ;)