zoukankan      html  css  js  c++  java
  • P1032 字串变换

    bfs,把能换的全部换掉然后入队即可。

    #include<iostream>
    #include<map>
    #include<unordered_map>
    #include<queue>
    #include<vector>
    
    using namespace std;
    
    #define PSI pair<string, int>
    #define PSS pair<string, string>
    
    vector<PSS> ss;
    unordered_map<string, int> st;
    
    string a, b;
    
    vector<int> find(const string &a, const string &b){
        vector<int> res;
        int j = 0;
        for(int i = 0; i < a.size(); i ++){
            if(j == b.size()) res.push_back(i - j);
            if(j < b.size() && a[i] == b[j]) j ++;
            else i = i - j, j = 0;
        }
        
        if(j == b.size()) res.push_back(a.size() - j);
        
        return res;
    }
    
    int bfs(){
        queue<PSI> q;
        
        q.push({a, 0});
        
        while(q.size()){
            auto h = q.front();
            q.pop();
            
            for(auto t : ss){
                vector<int> k = find(h.first, t.first);
                
                for(int i = 0; i < k.size(); i ++){
                    string temp = h.first;
                    temp = temp.replace(k[i], t.first.size(), t.second);
                    if(st[temp] == 0){
                        st[temp] = 1;
                        q.push({temp, h.second + 1});
                    
                        if(temp == b || h.second + 1 > 10) return h.second + 1;
                    }
                }
            }
        }
    }
    
    int main(){
        cin >> a >> b;
        
        string p, q;
        while(cin >> p >> q) ss.push_back({p, q});
        
        int k = bfs();
        
        if(k > 10) puts("NO ANSWER!");
        else cout << k << endl;
        
        return 0;
    }
    
  • 相关阅读:
    leetcode 87. Scramble String
    leetcode 1278 分割回文串
    back propagation in NNs and RNNs
    刷题笔记——单调栈
    unsupervised learning -- K MEANS
    install j3d on macOS
    java extract jar file on MacOS
    back-propagation algorithm
    day 4
    day 3
  • 原文地址:https://www.cnblogs.com/tomori/p/13823172.html
Copyright © 2011-2022 走看看