#K36782. Efficient Resource Collection

    ID: 25831 Type: Default 1000ms 256MiB

Efficient Resource Collection

Efficient Resource Collection

You are given several structures, each consisting of a set of resources. Each resource has an associated cost and may depend on other resources. A resource can only be collected if all of its dependencies have been collected. If there is a cycle in the dependencies (i.e. a resource depends, directly or indirectly, on itself), then the structure cannot be built, and the answer is IMPOSSIBLE. Otherwise, if all resources can be collected, the minimum cost of collecting a structure is the sum of the costs of its resources.

The dependency relations can be described by a directed graph. Your task is to check if the dependency graph for each structure is acyclic and, if so, output the sum of the costs of all resources. If the graph has a cycle, output IMPOSSIBLE.

Note: Use topological sorting to detect cycles in the dependency graph.

Input and Output are taken from standard input (stdin) and written to standard output (stdout) respectively.

inputFormat

The first line of input contains an integer T representing the number of structures. For each structure, the input begins with an integer m representing the number of resources. This is followed by m lines, each representing a resource in the following format:

resource_name cost dependency_count [dependency1 dependency2 ... dependency_dependency_count]

Each part is separated by space. The dependency_count indicates how many dependencies the resource has. If dependency_count == 0 then no dependencies follow.

outputFormat

For each structure, output a single line containing either the minimum total cost (i.e. the sum of the cost of all resources) if the structure can be built, or IMPOSSIBLE if the structure contains a cyclic dependency.

## sample
2
4
WOOD 3 0
STONE 4 1 WOOD
BRICK 5 2 WOOD STONE
GLASS 6 1 STONE
3
IRON 2 0
COPPER 3 1 IRON
GOLD 10 2 IRON COPPER
18

15

</p>