主要是字符串拼接處理比較麻煩(下見mix
函數(shù)),DFS還是比較簡單的
鑒定
讀題有坑 注意max_初始化
短小精悍(?)的深搜代碼:
#include <iostream>
#include <string>
using namespace std;
int n,max_;
string str[20];
int b[20];
int mix(string str1, string str2) {//如果沒有重疊部分就返回-1即彪,否則返回重疊部分開始的位置
for(int k=str1.size()-1; k>=0; k--) {//貪心黔州,為了讓合并后的字符串盡量長一定要從后往前判斷
bool r=1;
int i_2=0;
for(int i=k; i<=str1.size()-1; i++) {
if(!(i_2<=str2.size()-1)) {//判斷str2邊界
r=0;
break;
} else if(str1[i]!=str2[i_2]) {
r=0;
break;
}
i_2++;
}
if(r) return k;
}
return -1;
}
void search(int cur, string s) {
bool bb=1;//bb規(guī)定:0表示有至少一個解活翩,1表示此情況無解
for(int i=0; i<n; i++)
if(b[i]<=1) {//注意每個單詞可以用兩次
bb=0;
int t=mix(s,str[i]);
if(t!=-1) {
string news;
for(int i=0; i<=t-1; i++)
news+=s[i];
news+=str[i];//合并兩個字符串
b[i]+=1;
search(cur+1, news);
b[i]-=1;
}
}
if(bb&&max_<s.size())
max_=s.size();//更新max_
}
int main() {
ios::sync_with_stdio(false);//cin cout速度嗖嗖嗖
cin>>n;
for(int i=0; i<=n-1; i++)
cin>>str[i];
char a;
cin>>a;
for(int i=0; i<n; i++)
if(str[i][0]==a) {//枚舉每個以字符a開頭的字符串
b[i]=1;
string t=str[i];
if(max_<t.size()) {
max_=t.size();//初始化max_
}
search(0, t);//開搜的诵!
b[i]=0;
}
cout<<max_;
return 0;
}