Under construction

Still being built. Things may change

Fellow Sheep

Time limit2sMemory limit1024 MB

Summary
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 55 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 NN (1≤N≤1051 ≤ N ≤ 10^5), the number of segments. Each of the next NN lines contains five space-separated integers AiA_i, BiB_i, CiC_i, DiD_i, EiE_i (1≤Ai,Bi,Ci,Di,Ei≤1081 ≤ A_i, B_i, C_i, D_i, E_i ≤ 10^8), the number of sheep that the corresponding gate in the ii-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.

Examples1

  1. Example 1

    Input
    2
    3 6 2 5 2
    7 4 3 1 4
    
    Expected output
    7