Title Description Description
Word Solitaire is a game similar to the idiom solitaire we often play, and now we know a group of words, and given a beginning letter, asking for the longest "dragon" starting with the letter (each word is up to two occurrences in the "dragon"), and when two words are connected, the coincident part is part of it. For example, Beast and Astonish, if the next dragon is changed to Beastonish, the other two adjacent parts can not have a containment relationship, such as at and Atide can not be connected.
Enter a description input Description
The first behavior of the input is a separate integer n (n<=20) that represents the number of words, the following n lines have one word per line, and the last behavior entered is a single character representing the letter beginning with "Dragon". You can assume that a "dragon" that begins with this letter must exist.
outputs description output Description
Just output the longest length of "dragon" that starts with this letter
sample input to sample
5
At
Touch
Cheat
Choose
Tact
A
sample output Sample outputs
23
Data Size & Hint
(the "dragon" is Atoucheatactactouchoose)
The data range is very small can be done with DFS, we first enumerate the first letter with the specified letter of the same word, and then Dfs. For the two words can be connected, we write a check function, first enumerate the length of the possible coincidence, and then from the first word first and the second word the last one to start the comparison, until they can pick up, return to the length of the connection.
The code is as follows :
#include <cstdio> #include <cstring> #include <iostream> using namespace std;
const int maxn=1010;
int N,MAXX=0,USED[MAXN]; struct Word {char a[maxn];}
S[MAXN];
int check (int l,int r) {int Ll=strlen (S[L].A);
int Lr=strlen (S[R].A);
for (int k=1;k<lr;k++)//enumeration to be able to pick up the length {bool flag=0;
for (int i=ll-k,j=0;i<ll,j<k;i++,j++) {//First word from go after, second word from back to forward if (S[l].a[i]!=s[r].a[j])
{flag=1;
Break
}} if (!flag) return k;//returns the minimum length that can be picked up} return 0;
The void Dfs (int last,int len)//last is the number of the current word, Len is the length of the currently connected Dragon {if (!last) {for (int i=1;i<=n;i++)
if (S[I].A[0]==S[0].A[0]&&USED[I]<2)//First find the first letter with the given letter the same word {used[i]++;
DFS (I,strlen (S[I].A));
used[i]--; }} else {Maxx=max (Maxx,len);//record the maximum value for the dragon for (int i=1;i<=n;i++{int X=check (last,i);//Returns the minimum length if (x&&used[i]<2) {
used[i]++;
DFS (I,len+strlen (S[I].A)-X);//The current length plus the new word length minus the length of the coincident part used[i]--;
}}}} int main () {scanf ("%d", &n);
for (int i=1;i<=n;i++) scanf ("%s", s[i].a);
scanf ("%s", s[0].a);
DFS (0,1);
printf ("%d\n", Maxx);
return 0; }