zoukankan      html  css  js  c++  java
  • LuoguP1032 字符变换(BFS)

    题目链接为:https://www.luogu.org/problemnew/show/P1032

    思路:看到数据比较小,而且最多有6个规则,就可以用搜索去做了,我用的BFS,大体思路如下:

    1. 定义结构体表示状态,其中包括字符串str和当前步数num;并定义该结构体的队列;
    2. 用map实现string到int的映射,用来记录某个状态是否到达过,若到达过,标记为1,否则为0;
    3. bfs函数中就是bfs的经典模块,有个难点是从当前状态搜时,不仅要考虑遍历每一个规则的情况,而且要注意在某一规则中母串中可能有多个字串可以被替换,必须都考虑到,否则会被第5个数据卡。

    下面是AC代码:

     1 #include<cstdio>
     2 #include<string>
     3 #include<queue>
     4 #include<iostream>
     5 #include<map>
     6 using namespace std;
     7 
     8 struct node{
     9     string str;
    10     int num;
    11 }nod;
    12 
    13 queue<node> q;
    14 map<string,int> m;
    15 string a,b;
    16 string aa[6],bb[6];
    17 int n=0;
    18 
    19 void bfs(){
    20     q.push(nod);
    21     while(!q.empty()){
    22         node now=q.front();q.pop();
    23         string ns=now.str;
    24         int nn=now.num;
    25         if(nn>10){
    26             printf("NO ANSWER!
    ");
    27             return;
    28         }
    29         if(ns==b){
    30             printf("%d
    ",nn);
    31             return;
    32         }
    33         for(int i=0;i<n;i++){
    34             int index=ns.find(aa[i],0);
    35             while(index!=string::npos){
    36                 string tmp=ns;
    37                 tmp.replace(index,aa[i].length(),bb[i]);
    38                 if(!m[tmp]){
    39                     m[tmp]=1;
    40                     nod.str=tmp;
    41                     nod.num=nn+1;
    42                     q.push(nod);
    43                 }
    44                 index=ns.find(aa[i],index+aa[i].length());
    45             }
    46         }
    47     }
    48     printf("NO ANSWER!
    ");
    49 }
    50 
    51 int main(){
    52     cin>>a>>b;    
    53     while(cin>>aa[n]>>bb[n])
    54         n++;
    55     nod.str=a;
    56     nod.num=0;
    57     m[a]=1;
    58     bfs();
    59     return 0;
    60 }
  • 相关阅读:
    面试笔记1
    Hello World!!
    百度地图API JavaScript显示人员分布信息
    MUI Picker选择器 自定义省市地址三级联动
    【Unity】Lua热重载
    【临时存放】变量配置
    SVN代码管理出现注册错误
    javaweb学习
    微信应用号(微信小程序)开发教程
    shell脚本时间运算
  • 原文地址:https://www.cnblogs.com/FrankChen831X/p/10327449.html
Copyright © 2011-2022 走看看