Dynamic programming meets the principle of inclusion and exclusion