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

本文通过一道具体题目介绍了如何使用BFS(宽度优先搜索)算法解决数字交换问题,包括算法的具体实现过程及剪枝技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

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

转载于:https://www.cnblogs.com/pprp/p/7593679.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值