跳到正文

题解

P1032 [NOIP 2002 提高组] 字串变换 题解

NSFXSSSYsky约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
P1032

版本

  1. v1当前

我的思路是将字符串存到一个队列里,然后i循环队列里的字符串,j循环找到这个字符串能用的规则,将用了规则的新字符串存到队列中,重复执行以上操作直到操作了十次或有一个新字符串变成了目标字符串。

代码如下:

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
    string A,B;
    cin>>A>>B;
    vector<pair<string,string> >rules;
    string a,b;
    while(cin>>a>>b)rules.emplace_back(a,b);
    queue<string>q;
    unordered_set<string>visited;
    q.push(A),visited.insert(A);
    int step=0;
    while(!q.empty()&&step<=10){
       int size=q.size();
       for(int i=0;i<size;i++){
           string current=q.front();
           q.pop();
           if(current==B){
               cout<<step;
               return 0;
           }
           for(const auto&rule:rules){
              const string& from=rule.first;
              const string& to=rule.second;
              size_t pos=0;
              while((pos=current.find(from,pos))!=string::npos){
                  string next=current;
                  next.replace(pos,from.length(),to);
                  if(visited.find(next) == visited.end())
                      visited.insert(next),q.push(next);
                      pos++;
                  }
               }
           }
       step++;
    }
    cout<<"NO ANSWER!";
    return 0;
}
原文