I - Interesting Calculator (bfs使用优先队列求步数最小或者花费最小)

题目链接:https://cn.vjudge.net/contest/245287#problem/I

代码:

使用普通的队列和优先队列相比,优先队列能更快地找到目的变量。

#include<iostream>
#include<string>
#include<cstring>
#include<iomanip>
#include<stack>
#include<queue>
#include<map>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
# define inf 0x3f3f3f3f
const int maxn=1e8+10;
int n,m;
int a[104][105];
int cost[maxn];
struct node
{
    int cost;
    int step;
    int mon;
    node() {}
    node(int xx,int yy,int zz)
    {
        cost=xx;
        step=yy;
        mon=zz;
    }
    friend bool operator < (node a,node b)
    {
        if(a.cost>b.cost)return true;
        else if(a.cost==b.cost&&a.step>b.step)return true;
        return false;
    }
} temp1,temp;
void bfs()
{
    memset(cost,inf,sizeof(cost));
    priority_queue<node>q;
    cost[n]=0;
    q.push(node(0,0,n));
    while(!q.empty())
    {
        temp=q.top();
        q.pop();
        if(temp.mon==m)
        {
            cout<<temp.cost<<" "<<temp.step<<endl;
            return ;
        }
        for(int i=1; i<=3; i++)
        {
            for(int j=1; j<=10; j++)
            {
                if(i==1)
                {
                    temp1.cost=temp.cost+a[i][j];
                    temp1.mon=temp.mon*10+j-1;
                    temp1.step=temp.step+1;
                }
                if(i==2)
                {
                    temp1.cost=temp.cost+a[i][j];
                    temp1.mon=temp.mon+j-1;
                    temp1.step=temp.step+1;
                }
                if(i==3)
                {
                    temp1.cost=temp.cost+a[i][j];
                    temp1.mon=temp.mon*(j-1);
                    temp1.step=temp.step+1;
                }
                if(temp1.mon<=m&&cost[temp1.mon]>temp1.cost)
                {
                    cost[temp1.mon]=temp1.cost;
                    q.push(temp1);
                }
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    int s=1;
    while(cin>>n>>m)
    {
        for(int i=1; i<=3; i++)
        {
            for(int j=1; j<=10; j++)
            {
                cin>>a[i][j];
            }
        }
        cout<<"Case "<<s++<<": ";
        bfs();
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/letlifestop/p/10262980.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值