記憶化搜索
dp【還剩下幾個】【倒1】【倒2】【倒3】
CF JAVA中 public static class 前面好像不能再開類了,連注釋掉的類也不可以,好像是個BUG???
B. Solitaire time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard outputA boy named Vasya wants to play an old Russian solitaire called "Accordion". In this solitaire, the player must observe the following rules:
Vasya has already shuffled the cards and put them on the table, help him understand whether completing this solitaire is possible or not.
InputThe 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.
OutputOn 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.
Sample test(s) input4 2S 2S 2C 2Coutput
YESinput
2 3S 2Coutput
NONote
In the first sample you can act like that:
In the second sample there is no way to complete the solitaire.
/** * Created by ckboss on 14-9-5. */ import java.util.*; public class Solitaire { static int[][][][] dp = new int[60][60][60][60]; static boolean[][][][] vis = new boolean[60][60][60][60]; static char[] c1=new char[60]; static char[] c2=new char[60]; static boolean check(int a,int b){ if((c1[a]==c1[b])||(c2[a]==c2[b])) return true; else return false; } static int dfs(int cur,int a,int b,int c){ if(vis[cur][a][b][c]==true) return dp[cur][a][b][c]; vis[cur][a][b][c]=true; if(cur==1) return dp[cur][a][b][c] = 1; if(cur==2){ if(check(a,b)==true){ return dp[cur][a][b][c] = 1; } else{ return dp[cur][a][b][c] = 0; } } int ret=0; if(check(a,b)==true){ ret=dfs(cur-1,a,c,cur-3); } if(ret==1){ return dp[cur][a][b][c] = 1; } if(check(a,cur-3)==true){ ret=dfs(cur-1,b,c,a); } return dp[cur][a][b][c]=ret; } public static void main(String[] args){ Scanner in=new Scanner(System.in); int n=in.nextInt(); for(int i=1;i<=n;i++){ String temp=in.next().trim(); c1[i]=temp.charAt(0); c2[i]=temp.charAt(1); } if(n==1){ System.out.println("YES"); } else if(dfs(n,n,n-1,n-2)==1){ System.out.println("YES"); } else{ System.out.println("NO"); } } }