E - Dragon's Cruller

題目鏈接:
題意:八數碼類似的題目,數字華容道,但是不同點在於格子可以上下左右移動,並且越界移動可以從另一邊出來,並且橫縱移動有不同的花費
解題思路:簡單bfs啊!現在竟然還有一點點的覺得有很多題都是算法題,是自己能力範圍之外的,其實不然,比如這一題就是一道簡單bfs外加上unordered_map維護一下就夠了吶,(其實本質上就是hash)
另外還有一種標記方式爲康託展開,下一篇詳細描述一下。


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

ll sc,vc;


struct node
{
    int a[10],pos;
    ll cost;
    ll now;
    friend bool operator <(node a,node b)
    {
        return a.cost>b.cost;
    }
};
//bool cmp(node a,node b)
//{
//    return a.cost<b.cost;
//}
priority_queue<node>Q;

node enl(node a,int p,int cost)
{
    node ans;
    int tem=a.a[p];
    for(int i=0;i<9;i++)
    {
        ans.a[i]=a.a[i];
    }
    ans.a[p]=0;
    ans.a[a.pos]=tem;
    ll lin=0;
    for(int i=0;i<9;i++)
    {
        lin=lin*10+(ll)ans.a[i];
    }
    ans.now=lin;
    ans.cost=a.cost+cost;
    ans.pos=p;
    return ans;
}

int main()
{

//    ios::sync_with_stdio(false);
//    cout.tie(NULL);
    while(cin>>sc>>vc)
    {
        if(sc==0&&vc==0)break;
        unordered_map<ll,bool>mp;
        while(!Q.empty())Q.pop();
        int st[10];ll lin=0;
        int et[10];ll fin=0;
        for(int i=0;i<9;i++)
        {
            cin>>st[i];
            lin=lin*10+(ll)st[i];
        }

        for(int i=0;i<9;i++)
        {
            cin>>et[i];
            fin=fin*10+(ll)et[i];
        }
        node ss;
        for(int i=0;i<9;i++)
        {
            ss.a[i]=st[i];
            if(st[i]==0)ss.pos=i;
        }
        ss.now=lin;
        ss.cost=0;
        Q.push(ss);
        ll ans=0;
        while(!Q.empty())
        {
            node temp=Q.top();
//            cout<<temp.now<<endl;
//            for(int i=0;i<9;i++)
//                cout<<temp.a[i]<<" ";
//            cout<<endl;
            Q.pop();
            if(temp.now==fin)
            {
                ans=temp.cost;
                break;
            }
            if(mp.count(temp.now))continue;
            mp[temp.now]=1;
            node A=enl(temp,(temp.pos+1)%9,sc);
            Q.push(A);
            node B=enl(temp,(temp.pos-1+9)%9,sc);
            Q.push(B);
            node C=enl(temp,(temp.pos+3)%9,vc);
            Q.push(C);
            node D=enl(temp,(temp.pos-3+9*9)%9,vc);
            Q.push(D);

        }
        cout<<ans<<endl;

    }
    return 0;
}

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