hdu 2045 不容易系列之(3)—— LELE的RPG难题


有排成一行的n个方格,用红(Red)、粉(Pink)、绿(Green)三色涂每个格子,每格涂一色,要求任何相邻的方格不能同色,且首尾两格也不同色.求全部的满足要求的涂法.

开始时,傻乎乎的用了递归。。。

就成了这样:

void fun(int a[], int i)
{
    if (i == n-1)
    {
        if (a[0] == a[2])
            ans += 2;
         else
            ans++;
         return;
    }
    else if (a[i-1] == 1)
    {
        a[i] = 2;
        fun(a, i+1);

        a[i] = 3;
        fun(a, i+1);
    }
    else if (a[i-1] == 2)
    {
        a[i] = 1;
        fun(a, i+1);

        a[i] = 3;
        fun(a, i+1);
    }
    else
    {
        a[i] = 2;
        fun(a, i+1);

        a[i] = 1;
        fun(a, i+1);
    }
}

int main()
{

    while (~scanf("%d", &n) && n)
    {
        if (n == 1)
        {
            printf("3\n");
            continue;
        }
        ans = 3;
        memset(b, 0, sizeof(b));
        b[0] = 1;
        fun(b, 1);

        b[0] = 2;
        fun(b, 1);

        b[0] = 3;
        fun(b, 1);
        printf("%d\n", ans);
    }
}

然后,果断超时了  -_-|||

后来借鉴了一下别人写的,终于知道了,应该这样:

#include
#include

long long n, dp[50];  //结果要用long long 才能存下

int main()
{
    dp[0] = 3;
    dp[1] = 6;
    dp[2] = 6;
    for (int i=3; i < 50; i++)
    {
        dp[i] = dp[i-1] + dp[i-2]*2;
    }
    while (~scanf("%lld", &n) && n)
        printf("%lld\n", dp[n-1]);
    return 0;
}


你可能感兴趣的:(hdu)