Triangle Graph

Time limit1sMemory limit256 MB

Summary
Find the minimum vertex-cost path from top-center to bottom-center in a layered 3-column DAG over N rows.
Level

Medium4 of 10

Topics
Dynamic programming, Graph
Solved
No attempts yet

Problem

A triangle graph is a directed acyclic graph made of N≥2N \ge 2 rows and 33 columns. Number the columns 11 (left), 22 (center), and 33 (right), and write (i,j)(i, j) for the vertex in column jj of row ii.

Unlike an ordinary graph, the cost lives on the vertices, not the edges. The cost of a path is the sum of the costs of every vertex it passes through.

The goal is to find the minimum-cost path from the top-center vertex (1,2)(1, 2) to the bottom-center vertex (N,2)(N, 2).

The directed edges of a triangle graph are always connected as follows.

  • Within a row: for every row ii, (i,1)→(i,2)(i, 1) \to (i, 2) and (i,2)→(i,3)(i, 2) \to (i, 3).
  • To the next row: for every row ii with 1≤i<N1 \le i < N,
    • (i,1)→(i+1,1)(i, 1) \to (i+1, 1), (i,1)→(i+1,2)(i, 1) \to (i+1, 2)
    • (i,2)→(i+1,1)(i, 2) \to (i+1, 1), (i,2)→(i+1,2)(i, 2) \to (i+1, 2), (i,2)→(i+1,3)(i, 2) \to (i+1, 3)
    • (i,3)→(i+1,2)(i, 3) \to (i+1, 2), (i,3)→(i+1,3)(i, 3) \to (i+1, 3)

For example, in a graph whose center-column costs are 7,13,3,67, 13, 3, 6 from top to bottom, the straight-down path (1,2)→(2,2)→(3,2)→(4,2)(1,2) \to (2,2) \to (3,2) \to (4,2) costs 7+13+3+6=297 + 13 + 3 + 6 = 29.

Input

The input consists of several test cases.

The first line of each test case contains the number of rows NN (2≤N≤100,000)(2 \le N \le 100{,}000). Each of the next NN lines contains the costs of the three vertices in that row, in left, center, right order. Every cost is an integer, and the square of each cost is less than 1,000,0001{,}000{,}000 (so a cost may be negative).

The last line of the input contains a single 00, marking the end of the input.

Output

For each test case, print on one line the minimum cost of a path from the top-center vertex to the bottom-center vertex, in the following format.

k. n

Here kk is the test case number (starting from 11) and nn is the minimum cost for that test case.

Examples2

  1. Example 1

    Input
    4
    13 7 5
    7 13 6
    14 3 12
    15 6 16
    0
    
    Expected output
    1. 22
    
  2. Example 2

    Input
    2
    1 2 3
    4 5 6
    3
    10 1 10
    10 1 10
    10 1 10
    0
    
    Expected output
    1. 7
    2. 3