房屋染色

来源:互联网 发布:淘宝怎么取消手机绑定 编辑:程序博客网 时间:2024/04/19 21:06
这里有n个房子在一列直线上,现在我们需要给房屋染色,分别有红色蓝色和绿色。每个房屋染不同的颜色费用也不同,你需要设计一种染色方案使得相邻的房屋颜色不同,并且费用最小。
费用通过一个nx3 的矩阵给出,比如cost[0][0]表示房屋0染红色的费用,cost[1][2]表示房屋1染绿色的费用。
 注意事项
所有费用都是正整数
样例
costs = [[14,2,11],[11,14,5],[14,3,10]] return 10


房屋 0 蓝色, 房屋 1 绿色, 房屋 2 蓝色, 2 + 5 + 3 = 10

import java.util.Scanner;/** * 这里有n个房子在一列直线上,现在我们需要给房屋染色,分别有红色蓝色和绿色。每个房屋染不同的颜色费用也不同,你需要设计一种染色方案使得相邻的房屋颜色不同,并且费用最小。费用通过一个nx3 的矩阵给出,比如cost[0][0]表示房屋0染红色的费用,cost[1][2]表示房屋1染绿色的费用。 注意事项所有费用都是正整数样例costs = [[14,2,11],[11,14,5],[14,3,10]] return 10房屋 0 蓝色, 房屋 1 绿色, 房屋 2 蓝色, 2 + 5 + 3 = 10 *  * @author Dell * */public class Test515 {   public static int minCost(int[][] costs)   {   int n=costs.length;   if(n==0)   return 0;   int m=3;   int[][] dp=new int[n][3];   for(int j=0;j<=2;j++)   {   dp[0][j]=costs[0][j];   }   for(int j=1;j<n;j++)   {   dp[j][0]=Math.min(dp[j-1][1],dp[j-1][2])+costs[j][0];   dp[j][1]=Math.min(dp[j-1][0],dp[j-1][2])+costs[j][1];   dp[j][2]=Math.min(dp[j-1][0],dp[j-1][1])+costs[j][2];   }   return Math.min(dp[n-1][0], Math.min(dp[n-1][1],dp[n-1][2]));   }public static void main(String[] args) {       Scanner sc=new Scanner(System.in);       int n=sc.nextInt();       int[][] costs=new int[n][3];       for(int i=0;i<n;i++)       {     for(int j=0;j<3;j++)     {     costs[i][j]=sc.nextInt();     }         }       System.out.println(minCost(costs)); }}



原创粉丝点击