Fellow Sheep
Time limit2sMemory limit1024 MB
Given N repeated five-gate segments with gate capacities, find the maximum number of sheep that can reach the farmyard from the pasture.
- Level
Medium6 of 10
- Topics
- Graph, Dynamic programming
- Solved
- No attempts yet
Problem
The sheep are fleeing from a wolf that has entered their pasture. To save themselves, they must escape through fenced paths designated for sheep shearing. The paths connect to each other and eventually lead to a single exit into the farmyard, where the sheep that escape the wolf will be safe. The paths form a special arrangement of several segments with the same shape, and each segment contains paths. The entry point of each segment, except the first, is the exit point of the previous segment.
The entry point of the first segment is in the pasture, and the exit point of the last segment leads into the farmyard. Sheep always run in the same direction along one path, and no two sheep ever run along the same path in opposite directions. Sheep cannot jump over the fence of a path. Halfway along each path is an automatic gate that lets a certain number of sheep pass before it closes, after which the path is impassable for other sheep. The wolf can jump over the gates. We assume, and the sheep assume as well, that the wolf can catch only those sheep that can no longer reach the farmyard because the gates are closed.
Determine the maximum number of sheep that can escape the wolf, given the number of sheep each gate lets through.

Input
The first line contains a single integer (), the number of segments. Each of the next lines contains five space-separated integers , , , , (), the number of sheep that the corresponding gate in the -th segment lets through before it closes. The letters match the notation in the image. Segments are linked in the order they appear in the input. The first segment's entry is in the pasture, and the last segment leads into the farmyard.
Output
Print a single integer, the maximum number of sheep that can escape the wolf.