luogu1019_单词接龙(NOIP2000普及组第4题/提高组第3题)

luogu1019_单词接龙(NOIP2000普及组第4题/提高组第3题)

时空限制    1000ms/128MB

题目描述

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

输入输出格式

输入格式:

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

输出格式:

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

输入输出样例

输入样例#1:

5
at
touch
cheat
choose
tact
a

输出样例#1:

23

说明

(连成的“龙”为atoucheatactactouchoose)

NOIP2000提高组第四题

NOIP2000提高组第三题

代码

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
const int N = 25;
int n,used[N],ans;
string s[N];

int can(string s1,string s2){
	int len1=s1.size(),len2=s2.size();
	int t=min(len1,len2);
	for (int i=1; i<t; i++){//重叠长度从1开始,直到最短的字符串长度-1
		bool OK=true;
		for (int j=0; j<i; j++)
			if (s1[len1-i+j]!=s2[j]) OK=false;
		if (OK) return i;
	}
	return 0;
}

void dfs(string s1,int len){
	ans = max(ans,len);
	for (int i=0; i<n; i++)
		if (used[i]<2){
			int k=can(s1,s[i]);	//获取重叠长度
			if (k>0){	//有重叠
				used[i]++;
				dfs(s[i],len+s[i].size()-k);
				used[i]--;
			}
		}
}

int main(){
	cin>>n;
	for (int i=0; i<=n; i++) cin>>s[i];	//s[n]为开始字符
	dfs(" "+s[n],1);
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/WDAJSNHC/article/details/81350336