bfs40分
查看原帖
bfs40分
583610
DrAlfred楼主2022/5/26 09:24
/*
 * @author: Dr.Alfred
 */
#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
string num, foundAns[10001];
int k, x, y, ans;
vector<int> change[10],emptyVector;
inline bool foundString(string str){
    for (int it = 0; it < ans;it++){
        if(foundAns[it]==str){
            return true;
        }
    }
    return false;
}
inline bool CanBeReplaced(char c){
    return change[ c - '0'] != emptyVector;
}
inline void putFoundString(string str){
    foundAns[ans++] = str;
}
inline void bfs(){
    queue<string> que;
    que.push(num);
    while(!(que.empty())){
        string last = que.front();
        que.pop();
        //逐个寻找last中可以被替换的位置
        for (long long unsigned int i = 0; i < last.size(); i++){
            if(CanBeReplaced(last[i])){
                string NewAns = last;
                for (long long unsigned int j = 0;j<change[last[i]-'0'].size();j++){
                    NewAns[i] = change[last[i]-'0'][j] + '0';
                    if(!foundString(NewAns)){
                        que.push(NewAns);
                        putFoundString(NewAns);
                    }
                }
            }
        }
    }
}
// change[i]表示i经过变换后所得的数字,若不能变换则为 emptyvector
int main(int argc, char const *argv[]){
    cin >> num >> k;
    foundAns[ans++] = num;
    for (int i = 1; i <= k;i++){
        cin >> x >> y;
        change[x].push_back(y);
    }
    bfs();
    cout << ans;
    //system("pause");
    return 0;
}

2022/5/26 09:24
加载中...