zoukankan      html  css  js  c++  java
  • 青蛙跳杯子

    bfs,需要注意用set记录走过的局面,我用的是set<string> condition,看其他人的博客有用set<string> visited 的,变量名起得更加贴切

    只要注意这个点,细心一点就可以AC了

    #include <stdio.h>
    #include <memory.h>
    #include <math.h>
    #include <string>
    #include <string.h>
    #include <vector>
    #include <set>
    #include <stack>
    #include <queue>
    #include <algorithm>
    #include <map>
    
    
    #define I scanf
    #define OL puts
    #define O printf
    #define F(a,b,c) for(a=b;a<c;a++)
    #define FF(a,b) for(a=0;a<b;a++)
    #define FG(a,b) for(a=b-1;a>=0;a--)
    #define LEN 3000
    #define MAX 0x06FFFFFF
    #define V vector<int>
    
    using namespace std;
    
    struct Node{
        string s;
        int p;
        Node(string s="",int p=0):s(s),p(p){
        }
    };
    
    string sswap(string s,int a,int b){
        char t=s[a];
        s[a]=s[b];
        s[b]=t;
        return s;
    }
    
    queue<Node> q;
    set<string> condition;
    
    void insertNode(int p,int d,string s){
        string tmp=sswap(s,p,p+d);
        if(condition.find(tmp)==condition.end()){    //找到 
            condition.insert(tmp);
            q.push(Node(tmp,p+d));
        }
    }
    
    int main(){
    //    freopen("D:/CbWorkspace/blue_bridge/青蛙跳杯子.txt","r",stdin);
        char buf[20];
        I("%s",&buf);
        string s(buf);
        I("%s",&buf);
        string e(buf);
        Node root(s,s.find('*'));
    
        q.push(root);
        int len=s.length(),i;
        int cnt=0;
        int n=s.size();
        while(!q.empty()){
    //        cnt++;
            int size=q.size();
            for(i=0;i<size;i++){
                Node node=q.front();
                q.pop();
                if(node.s==e) goto END;
                int p=node.p;
                s=node.s;
                if(p-1>=0) insertNode(p,-1,s);
                if(p-2>=0) insertNode(p,-2,s);
                if(p-3>=0) insertNode(p,-3,s);
                if(p+1<n) insertNode(p,1,s);
                if(p+2<n) insertNode(p,2,s);
                if(p+3<n) insertNode(p,3,s);
            }
            cnt++;
        }
        END:
        printf("%d
    ",cnt);
        return 0;
    }
  • 相关阅读:
    string用法
    动手动脑
    你已经创建了多少个对象?
    动手动脑
    课程作业2
    课程作业1
    课程作业2
    《大道至简》第一章观后感
    java虚拟机内存区域
    Gitbook安装使用教程
  • 原文地址:https://www.cnblogs.com/TQCAI/p/8458090.html
Copyright © 2011-2022 走看看