https://www.luogu.org/problemnew/show/P1019

先预处理任意两个单词是否能相连及重叠长度,注意重叠长度必须小于两个字符串的长度。

然后跑一遍dfs就好了。

#include<iostream>
#include<cstdio>
#include<cctype>
#include<cstring>
#include<algorithm>
using namespace std;

int n,overlap[25][25],vis[25],ans;
char c,word[25][50];

void init()
{
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
		{
			int leni=strlen(word[i]),lenj=strlen(word[j]);
			for(int l=1;l<leni&&l<lenj;l++)
				if(0==strncmp(word[i]+leni-l,word[j],l))
				{
					overlap[i][j]=l;
					break;
				}
		}
}

void dfs(int u,int tot)
{
	ans=max(ans,tot);
	for(int v=1;v<=n;v++)
	{
		if(overlap[u][v]&&vis[v]<2)
		{
			vis[v]++;//printf("%d %d,%d\n",u,v,tot+len[u][v]);
			dfs(v,tot+strlen(word[v])-overlap[u][v]);  
			vis[v]--;
		}
	}
}

int main()
{
	freopen("input.in","r",stdin);
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%s",word[i]);
	do scanf("%c",&c); while(isspace(c));
	init();
	for(int i=1;i<=n;i++)if(word[i][0]==c)
	{
		vis[i]=1;
		dfs(i,strlen(word[i]));
		vis[i]=0;
	}
	printf("%d\n",ans);
	return 0;
}