implement cost function