Under construction

Still being built. Things may change

RGB Street

Interview

Time limit0.5sMemory limit128 MB

Summary
Given per-house costs for three colors, compute the minimum total cost to paint all houses in a line so that no two adjacent houses share a color.
Level

Easy3 of 10

Topics
Dynamic programming, Array
Solved
No attempts yet

Problem

There are N houses arranged in a line, numbered from 1 to N.

Each house must be painted one of three colors: red, green, or blue. Given the cost of painting each house in each color, find the minimum total cost to paint all houses while satisfying all of the following rules.

  • The color of house 1 must be different from the color of house 2.
  • The color of house N must be different from the color of house N-1.
  • For every i with 2 ≤ i ≤ N-1, the color of house i must be different from the colors of houses i-1 and i+1.

Input

The first line contains the number of houses N. (2 ≤ N ≤ 1,000)

Each of the next N lines contains three costs for one house, in order from house 1 to house N: the cost to paint it red, green, and blue. Every cost is a natural number between 1 and 1,000 inclusive.

Output

Print the minimum cost required to paint all houses while satisfying the rules.

Examples5

  1. Example 1

    Input
    3
    26 40 83
    49 60 57
    13 89 99
    
    Expected output
    96
    
  2. Example 2

    Input
    3
    1 100 100
    100 1 100
    100 100 1
    
    Expected output
    3
    
  3. Example 3

    Input
    3
    1 100 100
    100 100 100
    1 100 100
    
    Expected output
    102
    
  4. Example 4

    Input
    6
    30 19 5
    64 77 64
    15 19 97
    4 71 57
    90 86 84
    93 32 91
    
    Expected output
    208
    
  5. Example 5

    Input
    8
    71 39 44
    32 83 55
    51 37 63
    89 29 100
    83 58 11
    65 13 15
    47 25 29
    60 66 19
    
    Expected output
    253