普及练习场-深度优先搜索-P1019 单词接龙

题目描述
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at 和 atide 间不能相连。

输入输出格式
输入格式:

输入的第一行为一个单独的整数n (n<=20)表示单词数,以下n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.

输出格式:

只需输出以此字母开头的最长的“龙”的长度

输入输出样例
输入样例#1:

5
at
touch
cheat
choose
tact
a

输出样例#1:

23

说明
连成的“龙”为atoucheatactactouchoose
————————————————
思路:先做比较字符然后进行深搜处理

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int wordTot, maxi = 0;
struct words{
	int left = 2;
	int tail = 0;
	char word[101];
}words[22];

int jude(char a[],char b[])
{
	int a1 = strlen(a),b1 = strlen(b),j;
	bool flag = true;
	for(int i = 1;(i<a1) && (i<b1);i++)
	{
		flag = true;
		for(j = 0;j < i;j++)
		
			flag = true;
			for(j = 0;j < i;j++)
			if(a[a1 - i + j] != b[j])
			{
				flag = false;
				break;
			}
			if(flag)
			return i;
	}
		return 0;
		
	}
	
void dfs(char tail[],int num){
	maxi = max(maxi,num);
	int a;
	for(int i=0;i< wordTot;i++)
	if(words[i].left>0)
 {
     a = jude(tail,words[i].word);
	 if(a != 0){
	 	words[i].left--;
	 	dfs(words[i].word,num + words[i].tail -a);
	 	words[i].left++;
	 }	
	
  }
 }	
int main(){
	char start;
	cin>>wordTot;
	for(int i = 0;i< wordTot; i++)
	{
		cin>>words[i].word;
		words[i].tail = strlen(words[i].word);
	}
	cin>>start;
	for(int i = 0;i < wordTot;i++)
	   if(words[i].word[0] == start)
	   {
	   	words[i].left--;
	   	dfs(words[i].word,words[i].tail);
	   	words[i].left++;
	   }
	cout<< maxi <<endl;
	return 0;
}
	

发布了108 篇原创文章 · 获赞 2 · 访问量 2078

猜你喜欢

转载自blog.csdn.net/zqhf123/article/details/104388296