dfs4 5TLE,bfs4 5MLE,麻了,该怎么优化呀?
查看原帖
dfs4 5TLE,bfs4 5MLE,麻了,该怎么优化呀?
983436
wh_up楼主2024/3/28 10:34

dfs:

#include<stdio.h>
#include<string>
#include<iostream> 

using namespace std;

string a[30], b[30], s, f;
int n, i, ti = 0, ans = 1e9;

void dfs(string s)
{
	if(s == f){
		ans = ti<ans ? ti : ans;
		return;
	}
	if(ti > 10)  // 超过10次的直接剪枝 
		return; 
	for(int j = 0; j < i; j++){  // 枚举所有的替换规则 
		// 从第一个不同的字符开始进行替换
		int loc =  s.find(a[j], 0); // 从开始位置进行查找
		int le = a[j].length();
		if(loc == -1)	continue;
		do{ 
			string news = s;
			news.replace(loc, le, b[j]); // 进行字符串的替换 
			ti++;
			dfs(news);
			ti--;
			loc = s.find(a[j], loc+1); // 从后一个位置查找 
		}while(loc != -1);
	}
}

int main(void)
{
	cin>>s>>f;
	for(i =0;cin>>a[i]>>b[i]; i++)	;  // 连续输入
	dfs(s);
	ans > 10 ? printf("NO ANSWER!") : printf("%d", ans);
	return 0;
 }

bfs:

#include<stdio.h>
#include<queue>
#include<string>
#include<iostream>

using namespace std;

string a[200], b[200], s, f;
int i, ans = 1e9;

struct node
{
	string s;
	int ti; // 变换次数 
};

queue<node> q;

int main(void)
{
	int j;
	cin >> s >> f;
	for(i = 0; cin >> a[i] >> b[i]; i++)	;
	q.push((node){s, 0});
	node tmp;
	string news;
	
	while(!q.empty()){
		tmp = q.front(); q.pop(); // 出队
		string so = tmp.s;
		int nowti = tmp.ti+1; // 本次的新替换次数 
		if(nowti > 10)
			continue;		
		for(j = 0; j < i;j++){  // 枚举所有的替换规则 
			int loc = so.find(a[j]);
			int le = a[j].length();
			if(loc == -1)
				continue;
			do{
				news = so;
				news.replace(loc, le, b[j]);
				if(news == f){
					ans = nowti < ans ? nowti : ans;
				}else{
					q.push((node){news, nowti});  // 次数小于10的才进队! 
				}
				loc = so.find(a[j], loc+1); // 从后一个位置再次查找,直到查找不到 
			}while(loc != -1);
		}
	}
	ans > 10 ? printf("NO ANSWER!") : printf("%d", ans);
	return 0;
}
2024/3/28 10:34
加载中...