[Blue Bridge Cup] [algorithm training VIP] word Solitaire (DFS + String)

Title Description
word Solitaire is an idiom used to play with our Solitaire similar games, and now we know a set of words, and given a letter at the beginning, a requirement beginning with the letter of the longest "Dragon" (each words are most appear in the "dragon" twice), when connected to two words, which makes part of the overlapping portions together, and beast Astonish e.g., if connected to the train becomes beastonish, two additional adjacent portion can not exist inclusion relationship, and for example, can not be connected between at atide.

The sample description
together into the "dragon" is atoucheatactactouchoose

Input
of the first act input a single integer n (n <= 20) represents the number of words, each of the n row has a word line, the last row of a single input character, represents the letter "Dragon" at the beginning. You can assume that this begins with the letter "dragon" must exist.
Output
longest "dragon" of the length of output only begins with the letter of this
sample input
5
AT
Touch
Cheat
the Choose
TACT
A
sample output
23
ideas: the amount of data is not big, then we are on every possible search. Because it occurs at most twice, so to add a qualification. Here I use the string type, character string type for the interception useful, especially inside the substr function, you can not understand their own to Baidu.
code show as below:

#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int maxx=21;
string s[maxx];
int vis[maxx];
int n;

inline void dfs(string t,int &_max)
{
	if(t.length()>_max) _max=t.length();
	string gg,kk;
	for(int i=1;i<t.length();i++)
	{
		gg=t.substr(t.length()-i);
		for(int j=1;j<=n;j++)
		{
			kk=s[j].substr(0,gg.length());
			if(kk==gg&&vis[j]<2)
			{
				vis[j]++;
				dfs(t+s[j].substr(kk.length()),_max);
				vis[j]--;
			}
		}
	}
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) cin>>s[i];
	char c[2];
	scanf("%s",c);
	int _max=0;
	for(int i=1;i<=n;i++)
	{
		if(s[i][0]==c[0])
		{
			memset(vis,0,sizeof(vis));
			vis[i]++;
			dfs(s[i],_max);
		}
	}
	printf("%d\n",_max);
	return 0;
}

To refuel a ah, ( O ) / ~

Published 601 original articles · won praise 51 · views 50000 +

Guess you like

Origin blog.csdn.net/starlet_kiss/article/details/105225945