zoukankan      html  css  js  c++  java
  • 【NOIp 2002】【BFS+STL】字串变换

    描述

    已知有两个字串 A,B 及一组字串变换的规则(至多6个规则):
    A1>B1
    A2>B2
    规则的含义为:在 A$中的子串 A1B1、A2B2 …。
    例如:AabcdB=’xyz’
    变换规则为:
    ‘abc’->‘xu’ ‘ud’->‘y’ ‘y’->‘yz’
    则此时,AB,其变换的过程为:
    ‘abcd’->‘xud’->‘xy’->‘xyz’
    共进行了三次变换,使得 AB

    格式

    输入格式

    第一行为两个字符串,第二行至文件尾为变换规则
    AB
    A1B1
    A2B2 |-> 变换规则
    … … /
    所有字符串长度的上限为 20。

    输出格式

    若在 10 步(包含 10步)以内能将 AB ,则输出最少的变换步数;否则输出”NO ANSWER!”

    代码

    BFS…再加上那么一点点STL小技巧、

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <queue>
    #include <map>
    #define INF 1000
    using namespace std;
    
    struct Trans{
        string a,b;
        Trans(const string &a,const string &b){
            this->a=a; this->b=b;
        }
    };
    
    int n=1,d[1000],ans=20;
    string A,B;
    string a,b;
    vector<Trans> trans;
    map<string,int> dic;
    
    bool bfs(){
        queue<string> q;
        q.push(A); dic[A]=0;
        while(!q.empty()){
            const string temp=q.front(); q.pop();
            if(dic[temp]>10) return false;
            if(temp==B) {
                ans=dic[temp]; return true;
            }
            for(int i=0;i<(int)trans.size();i++){
                int pos=temp.find(trans[i].a);
                while(pos!=(int)string::npos){
                    string t2(temp);
                    t2.replace(pos,trans[i].a.length(),trans[i].b);
                    if(dic.count(t2)==0) {
                        q.push(t2); dic[t2]=dic[temp]+1;
                    }
                    pos=temp.find(trans[i].a,pos+1);
                }
            }
        }
        return false;
    }
    
    
    int main(){
        freopen("in.txt","r",stdin);
        cin>>A>>B;
        while(cin>>a>>b) trans.push_back(Trans(a,b));
        if(bfs()) printf("%d",ans);
        else printf("NO ANSWER!");
        return 0;
    }
  • 相关阅读:
    Zoj 3511 线段树
    HDU 3340 Rain in ACStar 线段树+简单几何?
    BZOJ 2282 & 树的直径
    BZOJ 1121 & science
    BZOJ 1067 & Interval_Tree
    BZOJ 1001 & SPFA
    UVa 11181 条件概率
    并查集——启发式合并,路径压缩
    GSS系列(1)——GSS1&&GSS3
    评测脚本
  • 原文地址:https://www.cnblogs.com/leotan0321/p/6081388.html
Copyright © 2011-2022 走看看