题目:https://www.luogu.org/problemnew/show/P1019
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <deque>
#include <stack>
#define INF 0x3f3f3f3
using namespace std;
typedef long long LL;
const int maxn=1e5+5;
int N,map[25][25],vis[25],ans;
char s[25][50],head;
//map[i][j]代表第i个单词后接第j个单词的重合部分,用solve(i,j)算
int solve(int x,int y)
{
int lenx=strlen(s[x]+1),leny=strlen(s[y]+1);
for(int i=lenx; i>0; i--)
{
int ky=1,flag=1;
for(int j=i; j<=lenx; j++)
{
if(s[x][j]!=s[y][ky++])
{
flag=0;
break;
}
}
if(flag)
return ky-1;
}
return 0;
}
void dfs(int x,int sum,int sum_chonghe)//sum代表经过的单词的长度和,sum_chonghe代表重合的长度和
{
ans=max(ans,sum-sum_chonghe);
for(int i=1; i<=N; i++)
{
if(map[x][i]&&vis[i]!=2)//如果重合长度为零,就不能接,用过两次也不能接
{
vis[i]++;
dfs(i,sum+strlen(s[i]+1),sum_chonghe+map[x][i]);
vis[i]--;
}
}
}
int main()
{
scanf("%d",&N);
for(int i=1; i<=N; i++)
scanf("%s",s[i]+1);
cin>>head; //洛谷上用getchar()会全wa
for(int i=1; i<=N; i++)
for(int j=1; j<=N; j++)
map[i][j]=solve(i,j);
for(int i=1; i<=N; i++)
{
memset(vis,0,sizeof(vis));
if(s[i][1]==head)
{
vis[i]++;
dfs(i,strlen(s[i]+1),0);
vis[i]--;
}
}
printf("%d\n",ans);
return 0;
}