More general cost computation function