Given a recipe where each mixture's ingredients are other mixtures, find the minimum number of bowls needed to prepare it.
Medium7TreeDFSGreedyDynamic programmingNo attempts yetTime limit5sMemory limit512 MBYou are following a recipe to make your lunch.
The recipe is a mixture made by combining ingredients in a bowl. Each ingredient is one of two things:
To make a mixture, get all of its ingredients ready, take an empty bowl, and mix the ingredients in it. You cannot make a new mixture by adding ingredients to a bowl that already holds a mixture.
For example, to make the mixture CAKE out of the mixture CAKEMIX and the basic ingredient lies, you must first make CAKEMIX in its own bowl, then add CAKEMIX and lies to a second bowl to make CAKE.
Once you have used a mixture as an ingredient and emptied the bowl it was prepared in, you can reuse that bowl for another mixture. The number of bowls you need to prepare the recipe therefore depends on the order in which you make the mixtures.
Find the minimum number of bowls you need.
The first line contains an integer C, the number of test cases.
Each test case has this format:
Tokens on one line are separated by single spaces.
The first mixture of a test case is the recipe you are making.
Mixture names are strings of 1 to 20 uppercase letters. Basic ingredient names are strings of 1 to 20 lowercase letters.
Every mixture except the recipe is used as an ingredient in exactly one other mixture, and the recipe is used in none. No name appears twice in the ingredient list of one mixture. No mixture requires itself, directly or indirectly.
Limits
For each test case, print one line in the form Case #X: Y, where X is the test case number starting from 1 and Y is the minimum number of mixing bowls required.
In the first test case of the example input, you can make SOUP like this.
In the second test case you choose whether to make FLAVOR or FRUIT first, before mixing them with milk and icecream to get MILKSHAKE.
Making FRUIT first uses four bowls.
Making FRUIT after FLAVOR uses only three bowls.