文章目录
搜索做题笔记2
记录普及+以上难度的题目~
题目1 P1032 字串变换
P1032
最小步数模型与双向广搜,(luogu上面数据太水,单向bfs就可以通过)
类似魔板那道题目
单向bfsAC code:
#include<bits/stdc++.h>
using namespace std;
string st,ed;
map<string,string>mapt;
const int N = 25;
int cnt,n;
queue<string>q;
map<string,int>dist;
string a[N],b[N];//可以互相变幻的两个字符串
int bfs(string st)
{
dist[st] = 0;
q.push(st);
while(q.size())
{
auto 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(dist.count(r))
{
continue;
}
dist[r] = dist[t]+1;
if(r==ed)
{
return dist[r];
}
q.push(r);
}
}
}
}
return 1e9;
}
int main()
{
cin>>st>>ed;
string s1,s2;
while(cin>>s1>>s2)
{
//把字符串加入进来
a[n] = s1;
b[n] = s2;
n++;
}
int t = bfs(st);
if(t==1e9)
{
cout<<"NO ANSWER!";
}
else
{
cout<<t<<endl;
}
return 0;
}
双向bfs code:
明日更新~
P1025 数的划分
P1025