hdu 2045 (dp)

题目链接

题目描述:

N 个格子染色,共有三种颜色,要求相邻的颜色不能一样,第一个和最后一个颜色不能一样,问有多少种染法

分析:

如果没有第一个和最后一个颜色不一样的要求的话,对于第 n 个格子染色,应该等于 dp[n - 1] * 2,就是另外两种与n - 1不同的颜色都染一次,但是可能会有重复,如果n - 1的颜色与第一个不同,我们就有了dp[n - 1]种染法,如果一样,那么第n - 2个格子的颜色一定不同于第一个,而且我们第 n 块的染色有两种选择,因此得到了方案数 dp[n - 2] * 2

由此得出

dp[ n ] = dp[ n - 1 ] + dp[ n - 2 ] * 2;

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long ll;
const int maxn = 55;
int n;
ll dp[maxn];
int main()
{
	memset(dp, 0, sizeof dp);
	dp[1] = 3;
	dp[2] = 6;
	dp[3] = 6;
	for (int i = 4; i <= 50; i++)dp[i] = dp[i - 1] + dp[i - 2] * 2;
	while (~scanf("%d", &n)){
		printf("%lld\n", dp[n]);
	}
	return 0;
}

 

posted @ 2019-08-01 13:32  correct  阅读(87)  评论(0)    收藏  举报