Fun and interesting algorithm (C++) implementation