Better graph generating algorithm