coudeup 問題 D: 【寬搜入門】魔板

#include<iostream>
#include<queue>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
struct node{
    int state;
    int step;
    vector<char> c;
} temp;
set<int> s;
int mat[2][4], destination=0;
string str = "ABC";
queue<node> q;

int A(int n){
    int a[8];
    for(int i=0; i<8; i++){
        a[i] = n%10;
        n = n/10;
    }
    // reverse(a, a+8);
    int t=0;
    for(int i=0; i<8; i++){
        t = t*10+a[i];
    }
    return t;
}

int B(int n){
    int a = n/10000; //前四位
    int b = n%10000; //後4位
    int c = (a%10)*1000+(a/10); //前4位
    int d = (b/1000)+(b%1000)*10; //後4位
    return d+c*10000;
}

int C(int n){
    int a[8];
    for(int i=0; i<8; i++){
        a[7-i] = n%10;
        n = n/10;
    }
    int t = a[6];
    a[6] = a[5];
    a[5] = a[2];
    a[2] = a[1];
    a[1] = t;
    t=0;
    for(int i=0; i<8; i++){
        t = t*10+a[i];
    }
    return t;
}

int changeId(int i, int n){
    switch(i){
       case 0:return A(n);
       case 1:return B(n);
       case 2:return C(n);
    }   
}

void bfs(){
    while(!q.empty()){
        temp = q.front();
        q.pop();
        for(int i=0; i<3; i++){
            node temp1;
            temp1.state = changeId(i, temp.state);
            
            if(s.count(temp1.state)==0){
                temp1.step = temp.step+1;
                // 註釋的賦值法有誤
                // for(int j=0; j<temp.c.size(); j++){
                //     temp1.c.push_back(temp.c[i]);
                // }
                temp1.c = temp.c; //vector可以直接賦值
                temp1.c.push_back(str[i]);

                if(temp1.state==destination){
                    cout<<temp1.step<<endl;
                    for(int i=0; i<temp1.c.size(); i++) cout<<temp1.c[i];
                    return;
                }
                
                s.insert(temp1.state);
                q.push(temp1);
            }
        }
        
    }
}

int main(){
    for(int i=0; i<2; i++)
        for(int j=0; j<4; j++)
        {
            cin>>mat[i][j];
            destination = destination*10+mat[i][j];
        }
    temp.state = 12345678;
    temp.step = 0;
    q.push(temp);
    s.insert(temp.state);
    bfs();

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章