ACM dp问题 给房子涂色

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]是指第i个房子选用第j种方案的钱数。注意要使相邻两户人家之间的颜色要不同。

程序代码:

#include <iostream>
#include <cstring>
using namespace std;
int a[25][3],dp[25][3];
int min(int x,int y)
{
	return x<y?x:y;
}
int main()
{
	int t,k=0;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		for(int u=0;u<n;u++)
			cin>>a[u][0]>>a[u][1]>>a[u][2];
		memset(dp,0,sizeof(dp));
		for(int v=0;v<3;v++)
			dp[0][v]=a[0][v];
		for(int i=1;i<n;i++)
			for(int j=0;j<3;j++)
				dp[i][j]=dp[i][j]+min(dp[i-1][(j+1)%3],dp[i-1][(j+2)%3])+a[i][j];
		int sum;
		sum=min(dp[n-1][0],min(dp[n-1][1],dp[n-1][2]));
	    cout<<"Case "<<++k<<": "<<sum<<endl;
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/xinxiangqing/p/4732646.html