http://www.luogu.org/problem/show?pid=1019
先3层循环算出两个单词接上的长度,然后DFS最长路即可
注意重合部分可以随意取,2、3测试点就有这个坑
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define ms(i,j) memset(i,j, sizeof i);
using namespace std;
char ch[25][1000];
int l[25][25];
int n;
char head;
int ans = 0;
int visit[25];
void dfs(int x, int lo)
{
if (lo>ans) ans = lo;
for (int i=1;i<=n;i++)
{
if (l[x][i]>0&&visit[i])
{
visit[i]--;
dfs(i,lo+l[x][i]);
visit[i]++;
}
}
}
int main()
{
scanf("%d\n", &n);
for (int i=1;i<=n;i++)
scanf("%s\n", ch[i]);
head = getchar();
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
{
for (int k=0;k<strlen(ch[i]);k++)
{
if (memcmp(ch[i]+strlen(ch[i])-k-1,ch[j],k+1)==0)
{
if (i==j&&k==strlen(ch[i])-1) break;
if (strlen(ch[j])-k-1>l[i][j]) l[i][j] = strlen(ch[j])-k-1;
}
}
}
}
for (int i=1;i<=n;i++)
if (ch[i][0]==head)
{
for (int j=1;j<=n;j++) visit[j] = 2;
visit[i]--;
dfs(i, strlen(ch[i]));
}
printf("%d\n", ans);
return 0;
}