2017 ACM-ICPC 南宁区比赛 Minimum Distance in a Star Graph

2017-09-25 19:58:04

writer:pprp

题意看上去很难很难,但是耐心看看还是能看懂的,给你n位数字

你可以交换第一位和之后的某一位,问你采用最少的步数可以交换成目标

有五组数据

用BFS进行搜索,并进行剪枝,已经搜索过的点不再搜索

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <set>
#include <queue>

using namespace std;

string sa, sb;

int n;

struct node
{
    string str;
    int times;
    node()
    {
        str = "";
        times = 0;
    }
};

int bfs()
{
    queue<node> q;
    set<string> ss;
    node now , nex;
    now.str = sa;
    q.push(now);
    ss.insert(now.str);
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        if(now.str == sb)
            return now.times;
        for(int i = 1; i < n;i++)
        {
            nex.str = now.str;
            nex.times = now.times+1;
            nex.str[i] = now.str[0];
            nex.str[0] = now.str[i];
            if(ss.count(nex.str) == 0)
            {
                ss.insert(nex.str);
                q.push(nex);
            }
            else
                continue;
        }
    }
}

int main()
{
    cin >> n;
    for(int i = 0 ; i < 5 ;i++)
    {
        cin >> sa >> sb;
        cout << bfs() << endl;
    }


    return 0;
}

现阶段掌握搜索还不是太好,希望以后可以尽快掌握

posted @ 2017-09-25 20:03  pprp  阅读(322)  评论(0编辑  收藏  举报