1 条题解

  • 0
    @ 2023-10-18 10:01:25

    C++ :

    #include<bits/stdc++.h>
    using namespace std;
    const int N=6;
    int n;
    string A,B;
    string a[N],b[N];
    //将队列中距离为d的串按照a->b扩展 
    int extend(queue<string>& q,map<string,int>& da,map<string,int> db,string a[N],string b[N])
    {
    	int d=da[q.front()]; //计算当前队头距离 
    	while(q.size()&&da[q.front()]==d) //扩展所有为d的字串 
    	{
    		string t=q.front();
    		q.pop();
    		for(int i=0;i<n;i++) //枚举每个位置 
    		{
    			for(int j=0;j<t.size();j++) //枚举起点 
    			{
    				if(t.substr(j,a[i].size())==a[i]) //如果可以转换 
    				{
    					string r=t.substr(0,j)+b[i]+t.substr(j+a[i].size()); //转换以后得到的串 
    					if(db.count(r)) return da[t]+db[r]+1; //如果在终点出现过了 
    					if(da.count(r)) continue; //如果之前已经在起点中出现过了 
    					da[r]=da[t]+1; //更新步数 
    					q.push(r); //压入队列 
    				}
    			}
    		}
    	}
    	return 11; //得不到 
    }
    int bfs()
    {
    	if(A==B) return 0;
    	queue<string> qa,qb;
    	map<string,int> da,db;
    	qa.push(A),qb.push(B);
    	da[A]=db[B]=0;
    	int step=0;
    	while(qa.size()&&qb.size())
    	{
    		int t;
    		if(qa.size()<qb.size()) t=extend(qa,da,db,a,b); //a少就从a扩展 
    		else t=extend(qb,db,da,b,a); //从b扩展 
    		if(t<=10) return t; //相遇 
    		if(++step==10) return -1; //10步以内无解 
    	}
    	return -1;
    }
    int main()
    {
    	cin>>A>>B;
    	while(cin>>a[n]>>b[n]) n++;
    	int t=bfs();
    	if(t==-1) cout<<"NO ANSWER!";
    	else cout<<t<<endl;
    	return 0;
    }
    
    
    • 1

    信息

    ID
    783
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者