int bj(string a,string b)
{
	for(int i=1;i<=min(a.size(),b.size());i++)
	{
		int f=1;
		for(int j=0;j<i;j++)
		if(a[a.size()-i+j]!=b[j])
		f=0;
		if(f) return i;
	}
	return 0;
}

题目还有要求就是每个字符串最多用两次,那么就跟每个字符串只能访问一次一样的回溯只是use[i]=0变成了use[i]--罢了。

我的代码(题解的算法)

#include <bits/stdc++.h>
using namespace std;
string st[100];
int use[100];
int len;
int n;
int bj(string a,string b)
{
	for(int i=1;i<=min(a.size(),b.size());i++)
	{
		int f=1;
		for(int j=0;j<i;j++)
		if(a[a.size()-i+j]!=b[j])
		f=0;
		if(f) return i;
	}
	return 0;
}
void dfs(string a,int b)
{
	len=max(b,len);
	for(int i=0;i<n;i++)
	{
		if(use[i]>=2)
		continue;
		int c=bj(a,st[i]);
		if(c)
		{
			use[i]++;
			dfs(st[i],b+st[i].size()-c);
			use[i]--;
		}
	}
}
main()
{
	cin>>n;
	for(int i=0;i<=n;i++)
	cin>>st[i];
	dfs(st[n],1);
	cout<<len;		
} 

相关文章:

  • 2022-01-17
  • 2021-08-14
  • 2021-10-02
  • 2021-10-15
  • 2021-12-23
猜你喜欢
  • 2021-09-25
  • 2021-12-17
  • 2022-12-23
  • 2021-06-01
  • 2021-10-31
  • 2021-07-02
相关资源
相似解决方案