What a Ridiculous Election HihoCoder - 1426 bfs预处理

题目链接:https://vjudge.net/problem/HihoCoder-1426
转自:https://blog.csdn.net/xianpingping/article/details/82940242
题意:有一个数字序列,有三种操作:1.交换两个数字 2.将一个数字加1 3.将一个数字*2。其中操作2有3次,操作3有两次。问能够变成12345的最小步数。
思路:bfs预处理。直接用12345看能够到达哪些状态即可。

#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
int res[maxn][5][5];
const int inf=0x3f3f3f3f;
struct NODE
{
    int a[10],sec,thr,step;
    bool operator <(const NODE &a)const
    {
        return step>a.step;
    }
};
int trans(NODE a)
{
    int cnt=a.a[1];
    for(int i=2; i<=5; i++)
    {
        cnt*=10;
        cnt+=a.a[i];
    }
    return cnt;
}
void bfs(NODE a)
{
    res[12345][3][2]=0;
    priority_queue <NODE> q;
    q.push(a);
    while(!q.empty())
    {
        NODE u=q.top();
        q.pop();
        NODE temp;
        for(int i=2; i<=5; i++)
        {
            temp=u;
            temp.step++;
            swap(temp.a[i],temp.a[i-1]);
            int cnt=trans(temp);
            if(res[cnt][temp.sec][temp.thr]<=temp.step)
            {
                continue;
            }
            res[cnt][temp.sec][temp.thr]=temp.step;
            q.push(temp);
        }
        if(u.sec>0)
        {
            for(int i=1; i<=5; i++)
            {
                temp=u;
                temp.sec--;
                temp.step++;
                temp.a[i]=(temp.a[i]+1)%10;
                int cnt=trans(temp);
                if(temp.step>=res[cnt][temp.sec][temp.thr])
                    continue;
                res[cnt][temp.sec][temp.thr]=temp.step;
                q.push(temp);
            }
        }
        if(u.thr>0)
        {
            for(int i=1; i<=5; i++)
            {
                temp=u;
                temp.thr--;
                temp.step++;
                temp.a[i]=(temp.a[i]*2)%10;
                int cnt=trans(temp);
                if(temp.step>=res[cnt][temp.sec][temp.thr])
                    continue;
                res[cnt][temp.sec][temp.thr]=temp.step;
                q.push(temp);
            }
        }
    }
}
int main()
{
    NODE now;
    now.sec=3;
    now.thr=2;
    now.step=0;
    for(int i=1; i<=5; i++)
    {
        now.a[i]=i;
    }
    memset(res,inf,sizeof(res));
    bfs(now);
    int n;
    while(~scanf("%d",&n))
    {
        int ans=inf;
        for(int i=0; i<=3; i++)
        {
            for(int j=0; j<=2; j++)
            {
                ans=min(res[n][i][j],ans);
            }
        }
        if(ans==inf)
            ans=-1;
        printf("%d\n",ans);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值