lightOJ 1047 Neighbor House (DP)

lightOJ 1047   Neighbor House (DP)

题目链接: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 B are 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个邻居用红、绿、蓝三种颜色中的一种涂房子,相邻的房子颜色不能一样,每种颜色花费不同,求将N个用户全部涂完的总花费最小是什么。

分析:

动态规划,和数字三角形类似。先求每户人家涂颜色的最小花费,每次涂下一个房子时不能与上一个房子颜色相同

状态转移方程:
      dp[i][j] = min(dp[i - 1][2], dp[i - 1][3]) + p[i][j];
      dp[i][j] = min(dp[i - 1][1], dp[i - 1][3]) + p[i][j];
      dp[i][j] = min(dp[i - 1][2], dp[i - 1][1]) + p[i][j];

代码:

 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring> //memset函数头文件
using namespace std; int p[][];
int dp[][]; //第i户人家涂第j种颜色的最小花费 int min(int a,int b)//输出最小值
{
return a>b?b:a;
} int main()
{
int t;
int n;
int m=;
scanf("%d",&t);//t组案例
while(t--)
{
memset(dp,,sizeof(dp));
scanf("%d",&n); //n户人家
for(int i=;i<=n;i++)
for(int j=;j<=;j++)
scanf("%d",&p[i][j]);//第i户人家涂第j种颜色的花费
for(int i=;i<=n;i++)
for(int j=;j<=;j++)
{
if (j == )//涂第一种颜色
dp[i][j] = min(dp[i - ][], dp[i - ][]) + p[i][j];
if (j == )//涂第二种颜色
dp[i][j] = min(dp[i - ][], dp[i - ][]) + p[i][j];
if (j == )//涂第三种颜色
dp[i][j] = min(dp[i - ][], dp[i - ][]) + p[i][j];
}
printf("Case %d: %d\n",m++,min(dp[n][],min(dp[n][],dp[n][])));
}
return ;
}
上一篇:百度地图API 级别自动缩放


下一篇:Linux popen/pclose