> 文章列表 > P1032 [NOIP2002 提高组] 字串变换

P1032 [NOIP2002 提高组] 字串变换

P1032 [NOIP2002 提高组] 字串变换

题目背景

本题疑似错题,不保证存在靠谱的多项式复杂度的做法。测试数据非常的水,各种做法都可以通过,不代表算法正确。因此本题题目和数据仅供参考。

题目描述

已知有两个字串 �,�A,B 及一组字串变换的规则(至多 66 个规则),形如:

  • �1→�1A1​→B1​。
  • �2→�2A2​→B2​。

规则的含义为:在 �A 中的子串 �1A1​ 可以变换为 �1B1​,�2A2​ 可以变换为 �2⋯B2​⋯。

例如:�=abcdA=abcd,�=xyzB=xyz,

变换规则为:

  • abc→xuabc→xu,ud→yud→y,y→yzy→yz。

则此时,�A 可以经过一系列的变换变为 �B,其变换的过程为:

  • abcd→xud→xy→xyzabcd→xud→xy→xyz。

共进行了 33 次变换,使得 �A 变换为 �B。

输入格式

第一行有两个字符串 �,�A,B。

接下来若干行,每行有两个字符串 ��,��Ai​,Bi​,表示一条变换规则。

输出格式

若在 1010 步(包含 1010 步)以内能将 �A 变换为 �B,则输出最少的变换步数;否则输出 NO ANSWER!

输入输出样例

输入 #1复制

abcd xyz
abc xu
ud y
y yz

输出 #1复制

3

说明/提示

对于 100%100% 数据,保证所有字符串长度的上限为 2020。

【题目来源】

NOIP 2002 提高组第二题

#include<bits/stdc++.h>
using namespace std;
string s1,s2;
map<string,int>mp;
queue<string> Q;
queue<int> sum;
int main() {cin>>s1>>s2;string abc[100],su[100];int n=1;while(cin>>abc[n]>>su[n]) {n++;}n--;Q.push(s1);sum.push(0);while(!Q.empty()) { if(Q.front()==s2) {cout<<sum.front();return 0; }if(sum.front()==10) {Q.pop();sum.pop();}string c=Q.front();if(mp.count(c)==1) {Q.pop();sum.pop();continue;}mp[c]=1;for(int i=1; i<=n; i++) {int p=0;while(c.find(abc[i],p)!=-1) {p=c.find(abc[i],p);Q.push(c.substr(0,p)+su[i]+c.substr(p+abc[i].length())); sum.push(sum.front()+1); p++;}}Q.pop();sum.pop();}cout<<"NO ANSWER!";return 0;
}