1 solutions

  • 0
    @ 2025-11-5 17:17:08

    C++ :

    #include<iostream>
    #include<string>
    #include<queue>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    string s[22];char ld;
    int n,maxx,tou[22],ans;
    struct at{
    	int cs[22];
    };
    int pd(string s1,string s2)
    {
    	int i=s1.size()-1,j=0;
    	string x1="",x2="";
    	x1+=s1[i];x2+=s2[j];
    	while(i>0&&j<s2.size()-1)
    	{
    		if(x1==x2)
    		    return 1;
    		i--;j++;
    		x1=s1[i]+x1;
    		x2=x2+s2[j];
    	}
    	return 0;
    }
    string cj1(string s1,string s2)
    {
        int i=s1.size()-1,j=0;
        string x1="",x2="";
    	x1+=s1[i];x2+=s2[j];
    	int i1,j1;
    	while(i>0&&j<s2.size()-1)
    	{
    		if(x1==x2)
    		{    
    			i1=i;
    			j1=j;
    			break;
    		}
    		i--;j++;
    		x1=s1[i]+x1;
    		x2=x2+s2[j];
    	}
    	s2.erase(0,j1+1);
    	string sx="";
    	sx=s1+s2;
    	//cout<<s1<<" + "<<s2<<" = "<<sx<<endl;
    	return sx;
    }
    void bfs(int x)
    {
    	at c;
    	for(int i=0;i<=20;i++)
    	    c.cs[i]=0;
    	queue <string> dr;
    	queue <int> cd;
    	queue <at> a;
    	c.cs[x]++;
    	a.push(c);
    	if(s[x][0]!=ld)
    	{
    		string sx=""; sx+=ld;
    		s[x].insert(0,sx);
    	}
    	dr.push(s[x]);
    	cd.push(s[x].size());
    	while(!dr.empty())
    	{
    		//cout<<dr.front()<<endl;
    		for(int i=1;i<=n;i++)
    		{
    			//cout<<s[i]<<endl;
    			if(a.front().cs[i]<2&&pd(dr.front(),s[i])==1)
    			{
    				for(int i=1;i<=n;i++)                        //回溯
                		c.cs[i]=a.front().cs[i];                //回溯
    				//cout<<dr.front()<<" "<<s[i]<<endl;
    				c.cs[i]=a.front().cs[i]+1;
    				a.push(c);
    				dr.push(cj1(dr.front(),s[i]));
    				cd.push(cj1(dr.front(),s[i]).size());
    				//cout<<"!"<<cj1(dr.front(),s[i])<<endl;
    			}
    		}
    		if(cd.front()>maxx)
    		{
    			//cout<<dr.front()<<endl;
    			maxx=cd.front();
    
    		}
    		a.pop();
    		dr.pop();
    		cd.pop();
    	}
    }
    int main()
    {
    	//freopen("4.in","r",stdin);
    	//freopen("4.ans","w",stdout);
    	cin>>n;
    	for(int i=1;i<=n;i++)
    	    cin>>s[i];
    	cin>>ld;
    	for(int i=1;i<=n;i++)
    	{
    		//cout<<"   第"<<i<<"步"<<endl;
    		bfs(i);
    	}
    	cout<<maxx;
    	//while(1);
    	return 0;
    }
    
    
    • 1

    Information

    ID
    18251
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    (None)
    Tags
    # Submissions
    0
    Accepted
    0
    Uploaded By