Monday, 17 August 2015

The colorful street

Standard
There is a street by the name of colorful street in the Pretty Town. The residents of the house have decided that they will paint their houses in either Pink, Orange or Yellow color and not other. They have also decided that no two adjacent houses will have the same color. For house i, i-1 and i+1 are the neighbors and note that the first and the last house are not neighbors.
The cost of painting a house in a particular color is different. The cost of painting the first house in color yellow maybe different than what its for painting the second house in the same color.
You have to find the minimum of cost of painting the houses which satisfy the given condition.
Input Constraints - Number of houses will contain between 1 and 20 elements, inclusive. - Each line of input for houses will have three values for cost of coloring in each color. Each value will be between 1 and 1000.
Input Format - The first line will contain the number of testcases - T. - The second line will contain an integer N that will specify how many houses are there. - Each of the following N lines will contain 3 numbers separated by space that represents the cost of painting that house in either pink, orange or yellow color.
Output Format Print T lines showing the cost of painting the houses for each testcase.

Sample Input
1
2
11 12 13
14 15 16
Sample Output
26
Explanation
The first house should be painted in pink (11), the second should be painted in orange (15). So the total cost becomes 11+15 = 26

Time Limit: 2 sec(s) for all input files combined.
Memory Limit: 256 MB
Source Limit: 1024 KB 
 
Code : 
 
/*
 * uncomment this if you want to read input.
import java.io.BufferedReader;
import java.io.InputStreamReader;
*/
import java.io.*;
import java.util.*;
class Colors {
    public static void main(String args[] ) throws Exception {
       Scanner in = new Scanner(System.in);
       int t = in.nextInt();
       for(int test=0; test<t; test++){
           int n = in.nextInt();
           int arr[][] = new int[n][3];
          
       for(int i=0; i<n; i++){
           arr[i][0] = in.nextInt();
           arr[i][1] = in.nextInt();
           arr[i][2] = in.nextInt();
       }
       int dp[][] = new int[n][3];
       dp[0][0] = arr[0][0];
       dp[0][1] = arr[0][1];
       dp[0][2] = arr[0][2];
      
       for(int i=0; i<n-1; i++){
           dp[i+1][0] = Math.min(dp[i][1], dp[i][2]) + arr[i+1][0];
        dp[i+1][1] = Math.min(dp[i][0], dp[i][2]) + arr[i+1][1];
        dp[i+1][2] = Math.min(dp[i][0], dp[i][1]) + arr[i+1][2];
        }
        System.out.println(Math.min(dp[n-1][0],Math.min(dp[n-1][1], dp[n-1][2])));
       }
    }
}
 

0 comments:

Post a Comment