解题思路:一开始用了一下广搜,内存超了,又转向了深搜,但是超时了,忽略了一个问题,深搜的过程中有很多状态重复访问,所以最难的是找到状态的表示唯一表示方法,记忆化搜索
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
struct node{
string s[55];
int top;
};
//book[l][s1][s2][s3]
//长度为l,后三堆牌的标号
bool book[55][55][55][55];
node a;
bool judge(string a,string b){
if(a[0]==b[0]||a[1]==b[1])return true;
return false;
}
bool dfs(ll l,ll s1,ll s2,ll s3){
if(l==1)return true;
if(book[l][s1][s2][s3])return false;//此状态已经判断,不可行
if(judge(a.s[s2],a.s[s3])){
//合并s2,s3....下一个状态如下
//s1->l-3,s2->s1,s3->s3;
//l-3变为倒数第三个,s1变为倒数第二个,s3还是最后一个
if(dfs(l-1,l-3,s1,s3))return true;
}
if(l>3&&judge(a.s[l-3],a.s[s3])){
//合并s1,s3
//s1->s3,s2->s1,s3->2;
//s3变为倒数第三个,s1变为倒数第二个,s2是最后一个
if(dfs(l-1,s3,s1,s2))return true;
}
book[l][s1][s2][s3]=true;//此状态不可行
return false;
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a.s[i];
}
memset(book,false,sizeof(book));
a.top=n;
bool flag=dfs(n,n-2,n-1,n);
if(flag)cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return 0;
}
// /\ | / |**、
// / \ | / | \
// / \ |/ | / _____ ____ | /
// /------\ |\ |__/ / \ \ /\ / / \ | /
// / \ | \ | / \ \ / \ / /______\ |/
// / \ | \ | \ / \ / \ / \ |
// / \ | \ | \_____/ \/ \/ \_____ |
/**
* ┏┓ ┏┓
* ┏┛┗━━━━━━━┛┗━━━┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*/
// warm heart, wagging tail,and a smile just for you!
//
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// .' \| |// `.
// / \||| : |||// \
// / _||||| -:- |||||- \
// | | \\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//