google的题目每道都很经典,看似是NP-HARD问题,却能够贪心解决。
官方分析:
On the surface, this problem appears to require solving the classic problem "Satisfiability," the canonical example of an NP-complete problem. The customers represent clauses, the milkshake flavors represent variables, and malted and unmalted flavors represent whether the variable is negated.
We are not evil enough to have chosen a problem that hard! The restriction that makes this problem easier is that the customers can only like at most one malted flavor (or equivalently, the clauses can only have at most one negated variable.)
Using the following steps, we can quickly find whether a solution exists, and if so, what the solution is.
- Start with every flavor unmalted and consider the customers one by one.
- If there is an unsatisfied customer who only likes unmalted flavors, and all those flavors have been made malted, then no solution is possible.
- If there is an unsatisfied customer who has one favorite malted flavor, then we must make that flavor malted. We do this, then go back to step 2.
- If there are no unsatisfied customers, then we already have a valid solution and can leave the remaining flavors unmalted.
Notice that whenever we made a flavor malted, we were forced to do so. Therefore, the solution we got must have the minimum possible number of malted flavors.