#5MLE,有没有优化策略
查看原帖
#5MLE,有没有优化策略
1379856
error_kkksc03楼主2025/2/7 20:14
#include <bits/stdc++.h>
#define ll long long
#define P 1000007
#define hashmod P
#define hashp 182557
using namespace std;
string u,v;
map<string,vector<string>>c;
struct L{
	string tr;
	int d;
};
int kmp[30];
int n,j;
queue<L>q;
inline void bfs(){
	q.push(L{u,0});
	while(!q.empty()){
		string a = q.front().tr;
		int dot = q.front().d;
		if(dot > 10){
			cout << "NO ANSWER!";
			return;
		}
		if(a == v){
			cout << dot;
			return;
		}
		q.pop();
		int la = a.size();
		for(auto tyy : c){
			string b = tyy.first;
			j = 0;
			memset(kmp,0,sizeof(kmp));
			int lb = b.size();
			for (int i=1;i<lb;i++)
		   	{     
			    while(j && b[i]!=b[j])j=kmp[j];    
		        if(b[j]==b[i])j++;    
		        kmp[i + 1]=j;
	       	}
	    	j=0;
	    	for(int i=0;i<la;i++)
		    {
		        while(j>0&&b[j]!=a[i])j=kmp[j];
		        if (b[j]==a[i]) j++;
		        if (j==lb){
		        	string m = a;
					for(auto y : c[b]){
						m.replace(i - lb + 1,lb,y);
						q.push(L{m,dot + 1});
					}
				}
	        }
		}		
	}
	return;
}
int main(){
	ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	cin >> u;
	cin >> v;
	n = v.size();
	string x,y;
	int tn;
	cin >> x >> y;
	do{
		int t = x.size();
		c[x].push_back(y);
	}while(cin >> x >> y);
	bfs();
	return 0;
}

感觉是map太占内存,但没有思路,有没有大佬(救救MnZn)

2025/2/7 20:14
加载中...