Interesting Calculator UVA

来源:互联网 发布:scp 指定端口 编辑:程序博客网 时间:2024/06/05 14:31

bfs的暴力搜索的优化,bfs的时候如果找到了一个最大值,那么之后bfs的时候如果得到一状态是小于这个最大值的才能继续判断,大于的就不行

然而只是这一种地方的优化是不够的,我们需要建立一个花费数组,mcost,存放着当前状态下的最小花费,如果这个花费比之前的小才可能进栈,

否则就不进入,进栈的时候同事更新他的最小值。

#include<bits/stdc++.h>using namespace std;int cost[4][10];int mcost[100861];struct aa{    int step;    int cost;    int num;} t,tt;int kase=1;void bfs(int s,int e){    int minstep=0x3f3f3f3f;    int mincost=0x3f3f3f3f;    t.num=s;    t.step=0;    t.cost=0;    queue<struct aa>ycq;    ycq.push(t);    mcost[s]=0;    while(!ycq.empty())    {        t=ycq.front();        ycq.pop();        if(t.num==e)        {            if(t.cost<mincost)            {                mincost=t.cost;                minstep=t.step;            }            continue;        }        for(int i=0; i<10; i++)//操作3        {            tt.num=t.num*i;            tt.cost=t.cost+cost[3][i];            tt.step=t.step+1;            if(tt.num>e||tt.cost>mincost)                continue;            if(tt.cost<mcost[tt.num])            {                ycq.push(tt);                mcost[tt.num]=tt.cost;            }        }        for(int i=0; i<10; i++)//操作1        {            tt.num=t.num*10+i;            tt.cost=t.cost+cost[1][i];            tt.step=t.step+1;            if(tt.num>e||tt.cost>mincost)                continue;            if(tt.cost<mcost[tt.num])            {                ycq.push(tt);                mcost[tt.num]=tt.cost;            }        }        for(int i=0; i<10; i++)//操作2        {            tt.num=t.num+i;            tt.cost=t.cost+cost[2][i];            tt.step=t.step+1;            if(tt.num>e||tt.cost>mincost)                continue;            if(tt.cost<mcost[tt.num])            {                ycq.push(tt);                mcost[tt.num]=tt.cost;            }        }    }    printf("Case %d: %d %d\n",kase++,mincost,minstep);}int main(){    int s,e;    while(scanf("%d%d",&s,&e)!=EOF)    {        for(int i=0; i<=e; i++)            mcost[i]=0x3f3f3f3f;        for(int i=1; i<=3; i++)        {            for(int j=0; j<10; j++)                scanf("%d",&cost[i][j]);        }        bfs(s,e);    }}