Catch That Cow poj3278

简单()bfs
今天学的队列,后面还有手写的

                                     queue队列容器的头文件 #include<queue>

           queue队列的相关用法:先进先出(FIFO)

                                                 入队push()   //即插入元素

                                                 出队pop()    //即删除元素

                                                 front()        //读取队首元素

                                                 back()       //读取队尾元素

                                                 empty()     //判断队列是否为空

                                                 size()        //读取队列当前元素的个数         
#include<algorithm>
#include<queue>
#include<string.h>
#include<stdio.h>
using namespace std;

int n,k;
struct num
{
    int x;
    int step;
};
bool visit[100010];
void bfs()
{
    queue<num> q;
    num start,now,next;
    memset(visit,false,sizeof(visit));
    start.x=n;
    start.step=0;
    q.push(start);
    visit[start.x]=true;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        if(now.x==k)
        {
            printf("%d\n",now.step);
            return;
        }
        for(int i=0;i<3;i++)
        {
            if(i==0)
                next.x=now.x+1;
            else if(i==1)
                next.x=now.x-1;
            else if(i==2)
                next.x=now.x*2;
            if(next.x>=0&&next.x<100005&&!visit[next.x])
            {
                visit[next.x]=true;
                next.step=now.step+1;
                q.push(next);
            }
        }
    }
}
int main()
{
    scanf("%d%d",&n,&k);
    bfs();
    return 0;
}

手写的

#include<stdio.h>
#include<string.h>
struct node
{
    int x,step;
}q[10000000];
int book[200000];
int n,k;
void bfs()
{
    memset(book,0,sizeof(book));
    int head,tail,tx;
    head=tail=1;
    q[1].x=n,q[1].step=0;
    tail++;
    while(head<tail)
    {
        if(q[head].x==k)
        {
            printf("%d\n",q[head].step);
            return;
        }
        for(int i=0; i<3; i++)
            {
                if(i==0)
                tx=q[head].x-1;
                if(i==1)
                tx=q[head].x+1;
                if(i==2)
                tx=q[head].x*2;
                if(tx<=100000&&!book[tx])
                {
                    q[tail].x=tx;
                    q[tail].step=q[head].step+1;
                    book[tx]=1;
                    tail++;
                }
            }
        head++;
    }
}
int main()
{
    scanf("%d%d",&n,&k);
    bfs();
}

发布了17 篇原创文章 · 获赞 3 · 访问量 525

猜你喜欢

转载自blog.csdn.net/RUBGH/article/details/104690753