2017南宁网络赛J.Minimum Distance in a Star Graph(bfs求最短路)

题意:

给你一个n维空间,有n!的节点,节点编号为n的全排列,每个节点num与n-1个节点相连(这n-1个节点的编号分别为num的第一位与后面n-1位交换的数,例如1234与2134,3214,4231相连)

思路:

bfs求最短路,由于节点的数比较大,用map离散化节点就好了。最好根据题意模拟一下相连的边。

代码:

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<ll,int> pii;
map<ll,int> mp;

ll Qpow(ll x,ll n)
{
    ll res = 1;
    while(n>0)
    {
        if(n&1)
            res = res*x;
        x = x*x;
        n>>=1;
    }
    return res;
}

int main()
{
    int n;
    cin>>n;
    int test = 5;
    while(test--)
    {
        ll st,en;
        scanf("%lld%lld",&st,&en);
        queue<pii> q;
        mp.clear();
        q.push(make_pair(st,0));
        mp[st]++;
        int ans = 0;
        while(!q.empty())
        {
            pii p = q.front();
            ll num = p.first;
            if(num==en)
            {
                ans = p.second;
                break;
            }
            q.pop();
            ll top = num/Qpow(10,n-1);
            ll temp = num;
            for(int i = 0;i<n-1;i++)
            {
                ll bac = temp%10;
                temp /= 10;
                ll now = num-top*Qpow(10,n-1)-bac*Qpow(10,i);
                now += bac*Qpow(10,n-1)+top*Qpow(10,i);
                if(!mp[now])
                {
                    mp[now]++;
                    q.push(make_pair(now,p.second+1));
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值