P1019 单词接龙

题目描述

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

输入格式

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

输出格式

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

输入输出样例

输入 #1复制

5
at
touch
cheat
choose
tact
a

输出 #1复制

23

说明/提示

(连成的“龙”为atoucheatactactouchoose)

NOIp2000提高组第三题

 

深度优先搜索

 

#include<iostream>
#include<vector>
#include<climits>
#include<queue>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
int a[25];
string s[25];
char ch;
int res;
int b[25][25];
int tag[25];
void dsf(int n,int p,int& count)
{
	if (count > res)
		res = count;
	if (b[p][0] == 0)
	{
		return;
	}
	for (int i = 1; i < b[p][0];i+=2)
	{
		if (tag[b[p][i]] >= 2)
			continue;
		count += s[b[p][i]].size() - b[p][i + 1];
		tag[b[p][i]]++;
		dsf(n, b[p][i], count);
		tag[b[p][i]]--;
		count -= s[b[p][i]].size() - b[p][i + 1];
	}
}
int main()
{
	int n;
	cin>> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> s[i];
	}
	cin >> s[0];
	for (int i = 0; i <=n; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			int h, k=0,r;
			for (i==0?h =0:h=1; h < s[i].size(); h++)//不可能全部匹配
			{
				if (s[i][h] == s[j][0])
				{
					if ((int(s[i].size()) - h < s[j].size()) && s[i].substr(h, int(s[i].size()) - h) == s[j].substr(0, int(s[i].size()) - h))
					{
						k = int(s[i].size()) - h;
					}
					
				}
			}
			int tmp = b[i][0];
			if (k > 0)
			{
				b[i][tmp + 1] = j;
				b[i][tmp + 2] = k;
				b[i][0] += 2;
			}
		}
	}
	int count = 1;
	dsf(n,0,count);
	cout << res;
	//system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值