Triangle Graph
Time limit1sMemory limit256 MB
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 rows and columns. Number the columns (left), (center), and (right), and write for the vertex in column of row .
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 to the bottom-center vertex .
The directed edges of a triangle graph are always connected as follows.
- Within a row: for every row , and .
- To the next row: for every row with ,
- ,
- , ,
- ,
For example, in a graph whose center-column costs are from top to bottom, the straight-down path costs .
Input
The input consists of several test cases.
The first line of each test case contains the number of rows . Each of the next 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 (so a cost may be negative).
The last line of the input contains a single , 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 is the test case number (starting from ) and is the minimum cost for that test case.