链接P1019 单词接龙
感想
这道题还是看了题解才做出来的,一方面是我太菜,另一方面真的是被c++没有库,全部靠数组基本STL生造逻辑感动了.反正这道题思维难度倒是不大,主要还是学会分解比如把check函数,判断最小重叠的逻辑抽象出一个link出来,这样就一目了然了,不然直接在check里面实现,会比较冗杂(其实也就是一个大循环),另外要时刻去做单元测试,不然都不知道有什么问题…
code
#include <algorithm>
#include <bits/stdc++.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
const int maxn = 1005;
int n;
string ans;
int length = 0;
string a[30];
int vis[30]={0};
bool link(string a, string b, int k)
{
string temp = a.substr(a.length()-k,k);
b = b.substr(0, k);
// cout<<temp<<endl;
// cout<<b<<endl;
if(temp == b)
return true;
else return false;
}
int check(string a, string b)
{
if(a.size() == 1)//如果是最开始的字母的话
{
if(b[0] == a[0])
return 1;
}
else//如果是之后的正常情况下
{
int flag = 1;
for(int k=1;k<min(a.length(), b.length());k++)
{
if(link(a, b, k)==true)
{
return k;
}
}
return 0;
}
}
void dfs(string s, int len)
{
if(len >length)
{
length = len;
ans = s;
}
for(int i=0;i<n;i++)
{
if(vis[i] == 2)//如果遍历到的这个字串已经用了两次直接continue
{
continue;
}
else
{
if (check(s, a[i]) != 0)//看看能不能连上
{
//如果能的话
int num = check(s, a[i]);
string temp = s;
s = s.substr(0, s.length()- num);
s+=a[i];
vis[i]++;
int delta = a[i].length() - num;
dfs(s, len+delta);
s = temp;
vis[i]--;
}
else//不能的话
{
continue;
}
}
}
}
int main()
{
#ifdef LOCAL
freopen("C:\\Users\\hsxny\\Desktop\\in.txt", "r", stdin);
#endif
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
string s;
cin>>s;
string temp1("at");
string temp2("touch");
// cout<<check(temp1, temp2);
dfs(s, 1);
cout<<length<<endl;
// cout<<ans;
return 0;
}