ready to sa algorithm.copy most codes from cm(almost same)