improve distance algorithm