第三个点死循环
查看原帖
第三个点死循环
1046223
a_blue_fool楼主2024/2/29 14:09

跑不出去,所以TLE了,救救!!!

#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include <map>

using namespace std;

struct rule
{
	string from , to;
};
struct words
{
	string word;
	int step = 0;
}start , now;



int it , find_it;
rule rules[6];
string a , b;
queue <words> q;
vector <string> has;

bool in_vector (string in)
{
	for (unsigned i = 0 ; i < has.size() ; i++)
		if (has[i] == in) return true;
	return false;
}

words cut_ (int start , int size , words str , string put_in)
{
	str.word.replace(str.word.begin() + start , str.word.begin() + start + size , put_in);	
	return str;	
}

words cut (words str , string from , string to , int find_it)
{
	return cut_(str.word.find(from , find_it) , from.size() , str , to);
}



int main()
{
	cin >> a >> b;
	while (cin >> rules[it].from >> rules[it].to) it++;
	
	
	start.word = a;
	start.step = 0;
	
	q.push(start);
	
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		
		if (now.step > 10)
		{
			printf("NO ANSWER!");
			return 0;
		}
		
		if (now.word == b)
		{
			printf("%d" , now.step);
			return 0;
		}
		
		if (in_vector(now.word)) continue;
		has.push_back(now.word);
		
		now.step++;
		for (int i = 0 ; i < it ; i++)
		{	
			find_it = 0;
			
			while ((int)(now.word.find(rules[i].from , find_it)) != -1)
			{			
				if (in_vector(cut(now , rules[i].from , rules[i].to , find_it).word)) continue;
				q.push(cut(now , rules[i].from , rules[i].to , find_it));		
				
				find_it = now.word.find(rules[i].from , find_it)+1;
			}		
		}
	}
	
	printf ("NO ANSWER!");
	
	return 0;
}
2024/2/29 14:09
加载中...