light oj 1047

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=87730#problem/C

题目:

   

Description

The people of Mohammadpur have decided to paint each of their houses red, green, or blue. They've also decided that no two neighboring houses will be painted the same color. The neighbors of house i are houses i-1 and i+1. The first and last houses are not neighbors.

You will be given the information of houses. Each house will contain three integers "R G B" (quotes for clarity only), where R, G and Bare the costs of painting the corresponding house red, green, and blue, respectively. Return the minimal total cost required to perform the work.

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case begins with a blank line and an integer n (1 ≤ n ≤ 20) denoting the number of houses. Each of the next n lines will contain 3 integers "R G B". These integers will lie in the range [1, 1000].

Output

For each case of input you have to print the case number and the minimal cost.

Sample Input

2

4

13 23 12

77 36 64

44 89 76

31 78 45

3

26 40 83

49 60 57

13 89 99

Sample Output

Case 1: 137

Case 2: 96

Hint

Use simple DP

题意:

     有n户人,打算把他们的房子图上颜色,有red、green、blue三种颜色,每家人涂不同的

颜色要花不同的费用,而且相邻两户人家之间的颜色要不同,求最小的总花费费用。

分析:

    这个跟数字三角形问题很像,这个是求最小的值,而且有些限制,每次走到点要和上次走的点不在同一列。

动态转移方程:

   dp[i][j]=a[i][j]+min(dp[i+1][j-1],dp[i+1][j+1])    

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 int a[300][50];
 5 int dp[300][50];
 6 int min(int a,int b)
 7 {
 8   if(a<b)  return a;
 9   else  return b;
10 }
11 int main()
12 {
13     int t,n,i,c=0,j;
14     cin>>t;
15     while(t--)
16     {
17         c++;
18      cin>>n;
19      memset(dp,0,sizeof(dp));
20      for(i=1;i<=n;i++)
21          for(j=1;j<=3;j++)
22              cin>>a[i][j];
23          for(i=1;i<=3;i++)    dp[n][i]=a[n][i];
24          for(i=n-1;i>=1;i--)
25             for(j=1;j<=3;j++)
26             {
27         if(j==1) 
28             dp[i][j]=a[i][j]+min(dp[i+1][2],dp[i+1][3]);                  //不能与上一步相同
29         if(j==2)  
30            dp[i][j]=a[i][j]+min(dp[i+1][1],dp[i+1][3]);
31         if(j==3)  
32             dp[i][j]=a[i][j]+min(dp[i+1][2],dp[i+1][1]);
33             }
34             if(dp[1][2]<dp[1][1])                                               //比较出最大值
35                 dp[1][1]=dp[1][2];
36               if(dp[1][3]<dp[1][1])
37                   dp[1][1]=dp[1][3];
38         cout<<"Case "<<c<<": "<<dp[1][1]<<endl;
39     }
40 return 0;
41 }
原文地址:https://www.cnblogs.com/fenhong/p/4734805.html