歷屆試題 青蛙跳杯子

傳送門


思路:

觀察到數據範圍爲15,而且青蛙又有三種動作,進而想到這是一個bfs.由於 ‘*’空杯子是唯一的,所以我們每次就從‘*’來考慮青蛙的動作是否可行(即從空杯子來跳到青蛙那裏),那麼最多隻有六種情況。

隊列中最多有2^15 * 6 個串,複雜度是可以滿足的.注意所有字符串只進隊一次,所以需要對字符串去重,這個過程用set 或map 記錄一下即可。


#include<bits/stdc++.h>

using namespace std;
struct node
{
    string ss;
    int pos;
    int step;
    node(string _ = "",int x = 0,int y = 0)
    {
        ss = _,pos = x,step = y;
    }
};
string s,t;
map<string,int>mp;
int bfs()
{
    queue<node>Q;
    mp.clear();
    while(!Q.empty()) Q.pop();
    int rot = s.find('*');
    Q.push(node(s,rot,0));
    mp[s] = 1;
    while(!Q.empty())
    {
        node q = Q.front();
        Q.pop();
        cout << q.ss << endl;
        if(q.ss == t)
            return q.step;
        if(q.pos - 1 >= 0)
        {
            string tmp = q.ss;
            swap(tmp[q.pos - 1],tmp[q.pos]);
            if(!mp[tmp])
            {
                mp[tmp] = 1;
                Q.push(node(tmp,q.pos - 1,q.step + 1));
            }
        }
        if(q.pos - 2 >= 0)
        {
            string tmp = q.ss;
            swap(tmp[q.pos-2],tmp[q.pos]);
            if(!mp[tmp])
            {
                mp[tmp] = 1;
                Q.push(node(tmp,q.pos - 2,q.step + 1));
            }
        }
        if(q.pos -3 >= 0)
        {
            string tmp = q.ss;
             swap(tmp[q.pos-3],tmp[q.pos]);
           if(!mp[tmp])
            {
                mp[tmp] = 1;
                Q.push(node(tmp,q.pos - 3,q.step + 1));
            }
        }
        if(q.pos + 1 < s.size())
        {
            string tmp = q.ss;
            swap(tmp[q.pos],tmp[q.pos + 1]);
            if(!mp[tmp])
            {
                mp[tmp] = 1;
                Q.push(node(tmp,q.pos + 1,q.step + 1));
            }
        }
        if(q.pos + 2 < s.size())
        {
            string tmp = q.ss;
            swap(tmp[q.pos],tmp[q.pos+2]);
            if(!mp[tmp])
            {
                mp[tmp] = 1;
                Q.push(node(tmp,q.pos + 2,q.step + 1));
            }
        }
        if(q.pos + 3 < s.size())
        {
            string tmp = q.ss;
            swap(tmp[q.pos],tmp[q.pos+3]);
            if(!mp[tmp])
            {
                mp[tmp] = 1;
                Q.push(node(tmp,q.pos + 3,q.step + 1));
            }

        }
    }
    return -1;
}
int main()
{
    while(cin >> s >> t)
    {
        printf("%d\n",bfs());
    }
    return 0;
}

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