CodeForces - 208B Solitaire 记忆化搜索

A boy named Vasya wants to play an old Russian solitaire called "Accordion". In this solitaire, the player must observe the following rules:

  • A deck of n cards is carefully shuffled, then all n cards are put on the table in a line from left to right;
  • Before each move the table has several piles of cards lying in a line (initially there are n piles, each pile has one card). Let's number the piles from left to right, from 1 to x. During one move, a player can take the whole pile with the maximum number x (that is the rightmost of remaining) and put it on the top of pile x - 1 (if it exists) or on the top of pile x - 3 (if it exists). The player can put one pile on top of another one only if the piles' top cards have the same suits or values. Please note that if pile x goes on top of pile y, then the top card of pile x becomes the top card of the resulting pile. Also note that each move decreases the total number of piles by 1;
  • The solitaire is considered completed if all cards are in the same pile.

Vasya has already shuffled the cards and put them on the table, help him understand whether completing this solitaire is possible or not.

Input

The first input line contains a single integer n (1 ≤ n ≤ 52) — the number of cards in Vasya's deck. The next line contains n space-separated strings c1, c2, ..., cn, where string ci describes the i-th card on the table. Each string ci consists of exactly two characters, the first one represents the card's value, the second one represents its suit. Cards on the table are numbered from left to right.

A card's value is specified by one of these characters: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A". A card's suit is specified by one of these characters: "S", "D", "H", "C".

It is not guaranteed that the deck has all possible cards. Also, the cards in Vasya's deck can repeat.

Output

On a single line print the answer to the problem: string "YES" (without the quotes) if completing the solitaire is possible, string "NO" (without the quotes) otherwise.

题解:如果 最后一个消除前一个 那前len-2个顺序不变 若消除前第3个 那前len-4不变 后三个改变 那么我们就维护该长度下,后三个的起始位置即可,记录失败的情况,数据最大为52 4维不会超

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long ll;
const int N=55;
int dp[N][N][N][N];
int n;
char s[N][4];
bool dfs(int len,int l1,int l2,int l3)
{
	if(len==1) return true;
	
	if(dp[len][l1][l2][l3]) return false;
	
	if(s[l1][0]==s[l2][0]||s[l1][1]==s[l2][1])
		if(dfs(len-1,l1,l3,len-3))
			return true;
	
	if(len>=4&&(s[l1][0]==s[len-3][0]||s[l1][1]==s[len-3][1]))
		if(dfs(len-1,l2,l3,l1))
			return true;
	
	dp[len][l1][l2][l3]=1;
	
	return false;
}
int main()
{
    while(~scanf("%d",&n))
    {
    	memset(dp,0,sizeof(dp));
    	for(int i=1;i<=n;i++)scanf("%s",s[i]);
    	if(dfs(n,n,n-1,n-2)) printf("YES\n");
    	else printf("NO\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/mmk27_word/article/details/83505977