if(b.find(a) != string::npos && b != a) return false;
不能单纯的这样去判断,要严谨的一个一个对应的去比较:
if(b.find(t) != string::npos && t[0] == b[0]) return true;
正确的check函数:
for(int i = a.size() - 1; i >= 0; i--)
{
int flag = 1;
t = a.substr(i);
for(int j = 0; j < t.size(); j++)
if(t[j] != b[j]) {flag = 0; break;}
if(flag) return true;
}
return false;
void connect(string &a, string b)
{
a += b.substr(t.size());
}
void dfs(string s)
{
maxLen = max((int)s.size(), maxLen);
for(int i = 0; i < N; i++)
{
if(vis[i] >= 2) continue;
if(check(s, str[i]))
{
string ss = s;
connect(ss, str[i]);
vis[i]++;
dfs(ss);
vis[i]--;
}
}
}
if(check(s, str[i]))
{
connect(s, str[i]);
vis[i]++;
dfs(s);
vis[i]--;
}
for(int i = 0; i < N; i++)
{
if(c == str[i][0])
{
vis[i]++;
dfs(str[i]);
vis[i]--;
}
}
#include
#include
#include
#include
using namespace std;
int N, maxLen;
string str[100], t;
char c;
int vis[100];
/*
1
envelope
e
*/
bool check(string a, string b)//1、atactactouch choose
{
//if(a == b) return true;
if(b.find(a) != string::npos && b != a) return false;
//if(a.find(b)!=string::npos || b.find(a)!=string::npos) return false;
for(int i = a.size() - 1; i >= 0; i--)
{
int flag = 1;
t = a.substr(i);
//if(b.find(t) != string::npos && t[0] == b[0]) return true;
//if(b.find(t) != string::npos)
//{
for(int j = 0; j < t.size(); j++)
//if(t[j] != b[j]) break;
if(t[j] != b[j]) {flag = 0; break;}
//return true;
//}
if(flag) return true;
}
return false;
}
void connect(string &a, string b)
{
a += b.substr(t.size());
}
void dfs(string s)
{
maxLen = max((int)s.size(), maxLen);
for(int i = 0; i < N; i++)
{
if(vis[i] >= 2) continue;
if(check(s, str[i]))
{
// connect(s, str[i]);
// cout << s << endl;
// vis[i]++;
// dfs(s);
// vis[i]--;
string ss = s;
connect(ss, str[i]);
//cout << ss << endl;
vis[i]++;
dfs(ss);
vis[i]--;
}
}
}
int main()
{
cin >> N;
for(int i = 0; i < N; i++) cin >> str[i];
cin >> c;
for(int i = 0; i < N; i++)
{
if(c == str[i][0])
{
vis[i]++;
dfs(str[i]);
vis[i]--;
}
}
cout << maxLen << endl;
//cout << check("atactactouch", "choose") << endl;
//cout << check("envelope", "envelope") << endl;
return 0;
}
#include
#include
#include
#include
using namespace std;
int N, maxLen;
string str[100], t;
char c;
int vis[100];
bool check(string a, string b)
{
if(b.find(a) != string::npos && b != a) return false;
for(int i = a.size() - 1; i >= 0; i--)
{
int flag = 1;
t = a.substr(i);
for(int j = 0; j < t.size(); j++)
if(t[j] != b[j]) {flag = 0; break;}
if(flag) return true;
}
return false;
}
void connect(string &a, string b)
{
a += b.substr(t.size());
}
void dfs(string s)
{
maxLen = max((int)s.size(), maxLen);
for(int i = 0; i < N; i++)
{
if(vis[i] >= 2) continue;
if(check(s, str[i]))
{
string ss = s;
connect(ss, str[i]);
vis[i]++;
dfs(ss);
vis[i]--;
}
}
}
int main()
{
cin >> N;
for(int i = 0; i < N; i++) cin >> str[i];
cin >> c;
for(int i = 0; i < N; i++)
{
if(c == str[i][0])
{
vis[i]++;
dfs(str[i]);
vis[i]--;
}
}
cout << maxLen << endl;
return 0;
}