Skip to main content

Paint House

 1. You are given a number n, representing the number of houses.

2. In the next n rows, you are given 3 space separated numbers representing the cost of painting nth house with red or blue or green color.

3. You are required to calculate and print the minimum cost of painting all houses without painting any consecutive house with same color.

Input Format

A number n

n1red n1blue n1green

n2red n2blue n2green

.. n number of elements

Output Format

A number representing the minimum cost of painting all houses without painting any consecutive house with same color.

Constraints

1 <= n <= 1000

0 <= n1red, n1blue, .. <= 1000

Sample Input

4

1 5 7

5 8 4

3 2 9

1 2 4

Sample Output

8


Solution: 

import java.io.*;

import java.util.*;


public class Main {


    public static void main(String[] args) throws Exception {

        // input

        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int[][] A = new int[n][3];

        

        for(int i=0;i<n;i++)

            for(int j=0;j<3;j++)

                A[i][j] = sc.nextInt();

         

        // process

        int[] color = new int[3];

        

        for(int i=0;i<n;i++){

            int[] col = new int[3];    

            for(int j=0;j<3;j++){

                col[j] = A[i][j] + Math.min(color[(j+1)%3],color[(j+2)%3]);

            }

            color = col;

        }

        

        int mincost = Integer.MAX_VALUE;

        for(int i=0;i<3;i++)

            mincost = Math.min(mincost,color[i]);

        

        // output

        System.out.println(mincost);

    }

}

Comments