第一反应是搜索,但裸搜会超时,所以考虑记忆化搜索。f[x][a][b][c]表示当前处理到第x堆,倒数第一第二第三堆的原来序号(也就是覆盖后的序号)为a,b,c; 这里的a和x是一样的吗?不是的,只能说a现在的位置在第x个位置。
f[x][a][b][c]= { f[x-1][b][c][a] || f[x-1][a][c][x-3] } 分别对应放在n-3的位置和n-1的位置的两种情况。
#include<stdio.h>
#include<string.h>
using namespace std;
char str[60][5];
int f[53][53][53][53];
bool dfs(int x,int a,int b,int c)
{
int res=0;
if(x==1)
{
return 1;
}
if(f[x][a][b][c]) return 0;
if( str[a][0]==str[b][0] || str[a][1]==str[b][1])
{
res=dfs(x-1,a,c,x-3);
}
if(!res && x-3 && (str[a][0]==str[x-3][0] || str[a][1]==str[x-3][1]) )
{
res=dfs(x-1,b,c,a);
}
f[x][a][b][c]=!res;
return res;
}
int main()
{
int i,n;
memset(f,0,sizeof(f));
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%s",str[i]);
if(n==1) printf("YES");
else
if(n==2 && (str[1][0]==str[2][0] || str[1][1]==str[2][1]))
printf("YES");
else
if(n==2) printf("NO");
else
{
if(dfs(n,n,n-1,n-2)) printf("YES"); else printf("NO");
}
return 0;
}