有排成一行的n个方格,用红(Red)、粉(Pink)、绿(Green)三色涂每个格子,每格涂一色,要求任何相邻的方格不能同色,且首尾两格也不同色.求全部的满足要求的涂法.
以上就是著名的RPG难题.
如果你是Cole,我想你一定会想尽办法帮助LELE解决这个问题的;如果不是,看在众多漂亮的痛不欲生的Cole女的面子上,你也不会袖手旁观吧?
1 2
36
题解:
首先第一眼的印象便是利用深度优先搜索直接找出所有的方法数,结果...又超时了(感觉只要是深度、广度优先方法都要挂)
深度优先:
#include<stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int amount = 0; int n; int a[51]={0}; int dfs(int t) { int i,j,k; if(t > n) { if(a[1] != a[n]) //首尾颜色不等 { amount++; return 0; } else return 0; } else { for(i = 1;i<= 3;i++) { if(t == 1) { a[t] = i; dfs(t+1); a[t] = 0; } else{ if(a[t-1] != i) { a[t] = i; dfs(t+1); a[t] = 0; } } } } return 0; } int main() { while(1 != 0) { scanf("%d",&n); if( n == 1)printf("3\n"); else{ dfs(1); printf("%d\n",amount); amount = 0; } } return 0; }
但不管怎么说,答案可以的出来,联系之前挂掉的经历,我们又来找规律:
当格子数分别为:
1 | 2 | 3 | 4 | 5 | 6 | 7 |
3 | 6 | 6 | 18 | 30 | 66 | 126 |
所以得到代码:
#include<stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main() { int i,j,k; long long int a[51]; a[1] = 3; a[2] = 6; a[3] = 6; for(i = 4;i <= 50;i++) { a[i] = a[i-1] + a[i-2]*2; } while(scanf("%d",&k)!=EOF) { printf("%lld\n",a[k]); } return 0; }