社区讨论

蒻篛求助,wa了第2,5测试点

P1032[NOIP 2002 提高组] 字串变换(疑似错题)参与者 1已保存回复 1

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
1 条
当前快照
1 份
快照标识符
@lo9jayvg
此快照首次捕获于
2023/10/28 12:20
2 年前
此快照最后确认于
2023/10/28 12:20
2 年前
查看原帖
CPP
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
#include <unordered_map>
using namespace std;
string A,B,a[6],b[6];
unordered_map<string,int>da,db;
queue<string>Q1,Q2;
int num=0;
/*string myreplace(string state,int x,int tt)
{
	string temp="";
	int j=0,g=0,h[100]={0};
	if(tt==1)
	{
		for(int i=0;i<state.size();i++)
		{
			if(state[i]==a[x][j])
			{
				j++;
			}
			else j=0;
			if(j==a[x].size())
			{
				h[g++]=i-j+1;
				j=0;
			}
		}
		j=0;
		/
		for(int i=0;i<state.size();i++)
		{
			if(i==h[j])
			{
				j++;
				temp+=b[x];
				i+=a[x].size()-1;
			}
			else 
			{
				temp+=state[i];
			}
		}
		for(int i=0;i<g;i++)
		{
			state.replace(h[i],a[i].size(),b[i]);
		}
	}
	else if(tt==-1)
	{
		for(int i=0;i<state.size();i++)
		{
			if(state[i]==b[x][j])
			{
				j++;
			}
			else j=0;
			if(j==b[x].size())
			{
				h[g++]=i-j+1;
				j=0;
			}
		}
		j=0;
		for(int i=0;i<state.size();i++)
		{
			if(i==h[j])
			{
				j++;
				temp+=a[x];
				i+=b[x].size()-1;
			}
			else 
			{
				temp+=state[i];
			}
		}
		for(int i=0;i<g;i++)
		{
			state.replace(h[i],b[i].size(),a[i]);
		}
	}
	return state;
}*/
int extrend(int tt)
{
	if(tt==1)
	{
		string state=Q1.front();Q1.pop();
		for(int i=0;i<num;i++)
		{
			int h=state.find(a[i]);
			if(h!=-1)
			{
				string source=state;
				//state=myreplace(state,i,tt);
				state.replace(h,a[i].size(),b[i]);
				if(!da[state])
				{
					da[state]=da[source]+1;
					Q1.push(state);
				}
			}
			if(db[state])
			{
				return db[state];
			}
			if(da[state]>5)return -1;
		}
	}
	else 
	{
		string state=Q2.front();Q2.pop();
		for(int i=0;i<num;i++)
		{
			int h=state.find(b[i]);
			if(h!=-1)
			{
				string source=state;
				//state=myreplace(state,i,tt);
				state.replace(h,b[i].size(),a[i]);
				if(!db[state])
				{
					db[state]=db[source]+1;
					Q2.push(state);
				}
			}
			if(da[state])
			{
				return da[state];
			}
			if(db[state]>5)return -1;
		}
	}
	return 0;
}
int bfs(string A,string B)
{
	Q1.push(A),Q2.push(B);
	da[A]=0,db[B]=0;int tt=1,t=0;
	while(Q1.size()&&Q2.size())
	{
		if(tt==1)
		{
			int h1=extrend(tt);
			if(h1!=-1&&h1!=0)
			{
				t=h1;break;
			}
			else if(h1==-1)return 0;
		}
		else 
		{
			int h1=extrend(tt);
			if(h1!=-1&&h1!=0)
			{
				t=h1;break;
			}
			else if(h1==-1)return 0;
		}
		Q1.size()>Q2.size()?tt=-1:tt=1;
	}
	if(t!=0)return t;
	else return 0;
} 
int main()
{
	cin>>A>>B;
	while(cin>>a[num]>>b[num])num++;
	int c=bfs(A,B);
	if(c)
	cout<<c;
	else cout<<"NO ANSWER!";
	return 0;
 } 

回复

1 条回复,欢迎继续交流。

正在加载回复...